Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33319ce2a8 | ||
|
|
77bb590bd8 | ||
|
|
5de7504b05 | ||
|
|
9d9ecd1b24 | ||
|
|
b7c0946458 | ||
|
|
ad4afef13d |
No files matched your search
@@ -64,13 +64,6 @@ function mockSpawnerLayer(statusJson = "{}") {
|
||||
);
|
||||
}
|
||||
|
||||
function dieOnSpawnLayer() {
|
||||
return Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")),
|
||||
);
|
||||
}
|
||||
|
||||
function makeEnvironmentLayer(baseDir: string, env: Record<string, string | undefined> = {}) {
|
||||
return makeDesktopEnvironmentLayer({
|
||||
dirname: "/repo/apps/desktop/src",
|
||||
@@ -93,7 +86,6 @@ function makeLayer(input: {
|
||||
readonly baseDir: string;
|
||||
readonly networkInterfaces?: DesktopNetworkInterfaces;
|
||||
readonly env?: Record<string, string | undefined>;
|
||||
readonly spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>;
|
||||
}) {
|
||||
const env = { T3CODE_HOME: input.baseDir, ...input.env };
|
||||
const environmentLayer = makeEnvironmentLayer(input.baseDir, env);
|
||||
@@ -105,7 +97,7 @@ function makeLayer(input: {
|
||||
Layer.provideMerge(DesktopAppSettings.layer),
|
||||
Layer.provideMerge(NodeFileSystem.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(input.spawnerLayer ?? mockSpawnerLayer()),
|
||||
Layer.provideMerge(mockSpawnerLayer()),
|
||||
Layer.provideMerge(networkLayer),
|
||||
Layer.provideMerge(DesktopConfig.layerTest(env)),
|
||||
Layer.provideMerge(environmentLayer),
|
||||
@@ -124,23 +116,13 @@ const withHarness = <A, E, R>(
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
>,
|
||||
env: Record<string, string | undefined> = {},
|
||||
spawnerLayer?: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-desktop-server-exposure-test-",
|
||||
});
|
||||
return yield* effect.pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
baseDir,
|
||||
networkInterfaces,
|
||||
env,
|
||||
...(spawnerLayer ? { spawnerLayer } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* effect.pipe(Effect.provide(makeLayer({ baseDir, networkInterfaces, env })));
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
|
||||
|
||||
describe("DesktopServerExposure", () => {
|
||||
@@ -257,27 +239,6 @@ describe("DesktopServerExposure", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not spawn the tailscale CLI while server exposure is local-only", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
Effect.gen(function* () {
|
||||
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
|
||||
yield* serverExposure.configureFromSettings({ port: 4173 });
|
||||
// mode stays at default "local-only", tailscaleServeEnabled stays false.
|
||||
|
||||
const endpoints = yield* serverExposure.getAdvertisedEndpoints;
|
||||
// Only the loopback endpoint; no tailscale spawn means the dieOnSpawnLayer
|
||||
// would have crashed the test if the gate was missing.
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["http://127.0.0.1:4173/"],
|
||||
);
|
||||
}),
|
||||
{},
|
||||
dieOnSpawnLayer(),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses ConfigProvider desktop exposure overrides", () =>
|
||||
withHarness(
|
||||
lanNetworkInterfaces,
|
||||
|
||||
@@ -12,7 +12,6 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -23,11 +22,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { DEFAULT_DESKTOP_SETTINGS, type DesktopSettings } from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
|
||||
import { readTailscaleStatus } from "@t3tools/tailscale";
|
||||
import * as DesktopAppSettingsService from "../settings/DesktopAppSettings.ts";
|
||||
|
||||
const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
|
||||
|
||||
export const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
|
||||
@@ -416,18 +412,6 @@ const make = Effect.gen(function* () {
|
||||
const desktopSettings = yield* DesktopAppSettingsService.DesktopAppSettings;
|
||||
const stateRef = yield* Ref.make(initialRuntimeState());
|
||||
|
||||
// Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App
|
||||
// Store Tailscale CLI lives inside Tailscale's sandbox container, so each
|
||||
// spawn re-triggers the "Other apps" TCC prompt.
|
||||
const cachedReadMagicDnsName = yield* Effect.cachedWithTTL(
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
),
|
||||
TAILSCALE_STATUS_CACHE_TTL,
|
||||
);
|
||||
|
||||
const readNetworkInterfaces = networkInterfaces.read;
|
||||
|
||||
const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
|
||||
@@ -532,20 +516,11 @@ const make = Effect.gen(function* () {
|
||||
exposure: toResolvedExposure(state),
|
||||
customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
|
||||
});
|
||||
|
||||
// Don't spawn the Tailscale CLI when the user hasn't opted into any
|
||||
// network exposure. The spawn itself triggers a macOS "Other apps"
|
||||
// TCC prompt on Mac App Store Tailscale builds.
|
||||
if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
|
||||
return coreEndpoints;
|
||||
}
|
||||
|
||||
const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: state.port,
|
||||
serveEnabled: state.tailscaleServeEnabled,
|
||||
servePort: state.tailscaleServePort,
|
||||
networkInterfaces: currentNetworkInterfaces,
|
||||
readMagicDnsName: cachedReadMagicDnsName,
|
||||
}).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
|
||||
Effect.provideService(HttpClient.HttpClient, httpClient),
|
||||
|
||||
@@ -104,25 +104,6 @@ describe("tailscale endpoint provider", () => {
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () =>
|
||||
Effect.gen(function* () {
|
||||
let readerCalls = 0;
|
||||
const endpoints = yield* resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
readMagicDnsName: Effect.sync(() => {
|
||||
readerCalls += 1;
|
||||
return "desktop.tail.ts.net";
|
||||
}),
|
||||
});
|
||||
assert.equal(readerCalls, 1);
|
||||
assert.deepEqual(
|
||||
endpoints.map((endpoint) => endpoint.httpBaseUrl),
|
||||
["https://desktop.tail.ts.net/"],
|
||||
);
|
||||
}).pipe(Effect.provide(unusedTailscaleExternalServicesLayer)),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable",
|
||||
() =>
|
||||
|
||||
@@ -105,11 +105,6 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: DesktopNetworkInterfaces;
|
||||
readonly statusJson?: string | null;
|
||||
readonly readMagicDnsName?: Effect.Effect<
|
||||
string | null,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
>;
|
||||
readonly probe?: (baseUrl: string) => Effect.Effect<boolean, never, HttpClient.HttpClient>;
|
||||
}): Effect.fn.Return<
|
||||
readonly AdvertisedEndpoint[],
|
||||
@@ -117,15 +112,12 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient
|
||||
> {
|
||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
||||
const readDnsName =
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed<string | null>(null)),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
? yield* readDnsName
|
||||
? yield* readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
)
|
||||
: input.statusJson
|
||||
? yield* parseTailscaleMagicDnsName(input.statusJson).pipe(
|
||||
Effect.orElseSucceed(() => null),
|
||||
|
||||
@@ -1,35 +1,29 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { afterEach } from "vite-plus/test";
|
||||
|
||||
import { fetchCloudAuth, validateClerkFrontendApiUrl } from "./cloudAuth.ts";
|
||||
|
||||
const originalClerkPublishableKey = process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
const clerkPublishableKey = (hostname: string): string =>
|
||||
`pk_test_${Buffer.from(`${hostname}$`).toString("base64")}`;
|
||||
|
||||
type FetchCall = readonly [input: RequestInfo | URL, init: RequestInit];
|
||||
|
||||
const recordedFetch = (...responses: ReadonlyArray<Response>) => {
|
||||
const calls: Array<FetchCall> = [];
|
||||
let responseIndex = 0;
|
||||
const fetchFn = ((input, init) => {
|
||||
calls.push([input, init ?? {}]);
|
||||
const response = responses[responseIndex++];
|
||||
if (!response) {
|
||||
return Promise.reject(new Error("Unexpected fetch call"));
|
||||
}
|
||||
return Promise.resolve(response);
|
||||
}) satisfies typeof fetch;
|
||||
|
||||
return { fetchFn, calls };
|
||||
};
|
||||
function makeHttpClientLayer(
|
||||
handler: (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
) => Effect.Effect<HttpClientResponse.HttpClientResponse, never>,
|
||||
) {
|
||||
return Layer.succeed(
|
||||
HttpClient.HttpClient,
|
||||
HttpClient.make((request) => handler(request)),
|
||||
);
|
||||
}
|
||||
|
||||
describe("Desktop cloud auth IPC", () => {
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalClerkPublishableKey === undefined) {
|
||||
delete process.env.T3CODE_CLERK_PUBLISHABLE_KEY;
|
||||
} else {
|
||||
@@ -39,8 +33,16 @@ describe("Desktop cloud auth IPC", () => {
|
||||
|
||||
it.effect("preserves Clerk's URL-encoded OAuth form content type", () => {
|
||||
const body = "strategy=oauth_google&redirect_url=t3code%3A%2F%2Fauth%2Fcallback";
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "sign_in_attempt" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "sign_in_attempt" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
@@ -53,25 +55,32 @@ describe("Desktop cloud auth IPC", () => {
|
||||
body,
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
const [url, init] = forwardedRequest;
|
||||
assert.equal(String(url), "https://example.clerk.accounts.dev/v1/client/sign_ins");
|
||||
assert.equal(init.method, "POST");
|
||||
assert(forwardedRequest !== null);
|
||||
assert.equal(
|
||||
new Headers(init.headers).get("content-type"),
|
||||
forwardedRequest.headers["content-type"],
|
||||
"application/x-www-form-urlencoded;charset=UTF-8",
|
||||
);
|
||||
assert.equal(new TextDecoder().decode(init.body as Uint8Array), body);
|
||||
});
|
||||
assert.equal(forwardedRequest.body._tag, "Uint8Array");
|
||||
if (forwardedRequest.body._tag === "Uint8Array") {
|
||||
assert.equal(new TextDecoder().decode(forwardedRequest.body.body), body);
|
||||
}
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"allows the custom Clerk Frontend API host encoded by the configured publishable key",
|
||||
() => {
|
||||
process.env.T3CODE_CLERK_PUBLISHABLE_KEY = clerkPublishableKey("clerk.t3.codes");
|
||||
const fetch = recordedFetch(Response.json({ response: { object: "client" } }));
|
||||
globalThis.fetch = fetch.fetchFn;
|
||||
let forwardedRequest: HttpClientRequest.HttpClientRequest | null = null;
|
||||
const layer = makeHttpClientLayer((request) =>
|
||||
Effect.sync(() => {
|
||||
forwardedRequest = request;
|
||||
return HttpClientResponse.fromWeb(
|
||||
request,
|
||||
Response.json({ response: { object: "client" } }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* fetchCloudAuth.handler({
|
||||
@@ -80,10 +89,9 @@ describe("Desktop cloud auth IPC", () => {
|
||||
headers: {},
|
||||
});
|
||||
|
||||
const forwardedRequest = fetch.calls[0];
|
||||
assert(forwardedRequest !== undefined);
|
||||
assert.equal(String(forwardedRequest[0]), "https://clerk.t3.codes/v1/client");
|
||||
});
|
||||
assert(forwardedRequest !== null);
|
||||
assert.equal(forwardedRequest.url.toString(), "https://clerk.t3.codes/v1/client");
|
||||
}).pipe(Effect.provide(layer));
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -8,11 +8,9 @@ import {
|
||||
} from "@t3tools/shared/relayAuth";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { identity } from "effect/Function";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import { Headers, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import * as DesktopCloudAuth from "../../app/DesktopCloudAuth.ts";
|
||||
import * as DesktopCloudAuthTokenStore from "../../app/DesktopCloudAuthTokenStore.ts";
|
||||
@@ -54,68 +52,6 @@ export function validateClerkFrontendApiUrl(rawUrl: string): URL {
|
||||
return url;
|
||||
}
|
||||
|
||||
function executeCloudAuthFetch(url: URL, input: typeof DesktopCloudAuthFetchInputSchema.Type) {
|
||||
return Effect.gen(function* () {
|
||||
const method = (input.method ?? "GET") as "GET" | "POST";
|
||||
const headers = new Headers(input.headers);
|
||||
const response = yield* HttpClientRequest.make(method)(url).pipe(
|
||||
HttpClientRequest.setHeaders(headers),
|
||||
input.body === undefined
|
||||
? identity
|
||||
: HttpClientRequest.bodyText(input.body, headers.get("content-type") ?? undefined),
|
||||
HttpClient.execute,
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed to execute.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const electronNetFetchLayer = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const electronFetch = yield* Effect.promise(async () => {
|
||||
const electron = (await import("electron")) as {
|
||||
readonly net?: { readonly fetch?: typeof globalThis.fetch };
|
||||
};
|
||||
return typeof electron.net?.fetch === "function"
|
||||
? electron.net.fetch.bind(electron.net)
|
||||
: null;
|
||||
}).pipe(Effect.catchCause(() => Effect.succeed(null)));
|
||||
|
||||
if (!electronFetch) {
|
||||
yield* Effect.logWarning(
|
||||
"electron.net.fetch is not available, falling back to global fetch. This may cause unexpected errors.",
|
||||
);
|
||||
}
|
||||
|
||||
return FetchHttpClient.layer.pipe(
|
||||
Layer.provide(Layer.succeed(FetchHttpClient.Fetch, electronFetch ?? globalThis.fetch)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
export const createCloudAuthRequest = makeIpcMethod({
|
||||
channel: IpcChannels.CREATE_CLOUD_AUTH_REQUEST_CHANNEL,
|
||||
payload: Schema.Void,
|
||||
@@ -172,6 +108,47 @@ export const fetchCloudAuth = makeIpcMethod({
|
||||
}),
|
||||
});
|
||||
|
||||
return yield* executeCloudAuthFetch(url, input).pipe(Effect.provide(electronNetFetchLayer));
|
||||
const requestWithoutBody = HttpClientRequest.make((input.method ?? "GET") as "GET" | "POST")(
|
||||
url,
|
||||
{
|
||||
headers: input.headers,
|
||||
},
|
||||
);
|
||||
const request =
|
||||
input.body === undefined
|
||||
? requestWithoutBody
|
||||
: HttpClientRequest.bodyText(
|
||||
requestWithoutBody,
|
||||
input.body,
|
||||
Option.getOrUndefined(Headers.get(requestWithoutBody.headers, "content-type")),
|
||||
);
|
||||
|
||||
const response = yield* HttpClient.execute(request).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch failed.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const body = yield* response.text.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopCloudAuthFetchError({
|
||||
reason: "Desktop cloud auth fetch response could not be read.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
ok: response.status >= 200 && response.status < 300,
|
||||
status: response.status,
|
||||
statusText: "",
|
||||
headers: response.headers,
|
||||
body,
|
||||
};
|
||||
}),
|
||||
});
|
||||
@@ -5,7 +5,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
import {
|
||||
@@ -34,8 +33,6 @@ function makeHttpClientLayer(
|
||||
);
|
||||
}
|
||||
|
||||
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
|
||||
|
||||
describe("SSH environment IPC", () => {
|
||||
it.effect("fetches and decodes the remote environment descriptor", () => {
|
||||
const requestUrls: string[] = [];
|
||||
@@ -86,7 +83,7 @@ describe("SSH environment IPC", () => {
|
||||
|
||||
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
|
||||
assert.equal(error.operation, "fetch-environment-descriptor");
|
||||
assert.isFalse(isSshHttpBridgeError(error.cause));
|
||||
assert.equal(error.cause instanceof SshHttpBridgeError, false);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
@@ -111,7 +108,7 @@ describe("SSH environment IPC", () => {
|
||||
const error = failure.value;
|
||||
|
||||
assert.instanceOf(error, DesktopSshEnvironmentRequestError);
|
||||
assert.isTrue(isSshHttpBridgeError(error.cause));
|
||||
assert.instanceOf(error.cause, SshHttpBridgeError);
|
||||
assert.equal(requestCount, 0);
|
||||
}).pipe(Effect.provide(layer));
|
||||
});
|
||||
|
||||
@@ -50,10 +50,12 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
|
||||
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
|
||||
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
|
||||
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
|
||||
const isSshHttpBridgeError = Schema.is(SshHttpBridgeError);
|
||||
|
||||
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
|
||||
if (cause instanceof RemoteEnvironmentAuthUndeclaredStatusError || isSshHttpBridgeError(cause)) {
|
||||
if (
|
||||
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
|
||||
cause instanceof SshHttpBridgeError
|
||||
) {
|
||||
return cause.status ?? null;
|
||||
}
|
||||
if (isEnvironmentRequestInvalidError(cause)) {
|
||||
|
||||
@@ -25,7 +25,6 @@ import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -80,13 +79,11 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
|
||||
return discoverSshHosts(input ?? {});
|
||||
}
|
||||
|
||||
const isSshPasswordPromptError = Schema.is(SshPasswordPromptError);
|
||||
|
||||
export function isDesktopSshPasswordPromptCancellation(
|
||||
error: unknown,
|
||||
): error is SshPasswordPromptError {
|
||||
return (
|
||||
isSshPasswordPromptError(error) &&
|
||||
error instanceof SshPasswordPromptError &&
|
||||
DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -344,26 +344,6 @@ function runtimeEventToActivities(
|
||||
];
|
||||
}
|
||||
|
||||
case "tool.denied": {
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "error",
|
||||
kind: "tool.denied",
|
||||
summary: `Tool denied: ${event.payload.toolName}`,
|
||||
payload: {
|
||||
toolName: event.payload.toolName,
|
||||
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
|
||||
...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),
|
||||
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "runtime.warning": {
|
||||
return [
|
||||
{
|
||||
@@ -371,9 +351,7 @@ function runtimeEventToActivities(
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "runtime.warning",
|
||||
// Use the adapter-supplied message as the row label so the work log
|
||||
// shows what the warning was about, not a generic "Runtime warning".
|
||||
summary: truncateDetail(event.payload.message, 120),
|
||||
summary: "Runtime warning",
|
||||
payload: {
|
||||
message: truncateDetail(event.payload.message),
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
|
||||
@@ -972,52 +972,6 @@ function sdkNativeMethod(message: SDKMessage): string {
|
||||
return `claude/${message.type}`;
|
||||
}
|
||||
|
||||
// Discriminator/identity keys carry no human-readable content; everything else
|
||||
// on an unmodeled SDK message is potentially worth surfacing in the work log.
|
||||
const SDK_MESSAGE_NOISE_KEYS = new Set([
|
||||
"type",
|
||||
"subtype",
|
||||
"uuid",
|
||||
"parent_uuid",
|
||||
"session_id",
|
||||
"parent_tool_use_id",
|
||||
"request_id",
|
||||
]);
|
||||
|
||||
// Pull the salient scalar content out of a message the adapter doesn't model
|
||||
// yet, so the work-log row shows what actually arrived (e.g. a notification's
|
||||
// text) instead of an opaque "unhandled subtype" placeholder. Nested structures
|
||||
// are left to the full payload retained in the event's `detail`.
|
||||
function previewUnknownSdkContent(message: unknown): string | undefined {
|
||||
if (!message || typeof message !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
const parts: string[] = [];
|
||||
for (const [key, value] of Object.entries(message as Record<string, unknown>)) {
|
||||
if (SDK_MESSAGE_NOISE_KEYS.has(key)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(`${key}: ${trimmed}`);
|
||||
}
|
||||
} else if (typeof value === "number" || typeof value === "boolean") {
|
||||
parts.push(`${key}: ${String(value)}`);
|
||||
}
|
||||
}
|
||||
if (parts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const joined = parts.join(" · ");
|
||||
return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;
|
||||
}
|
||||
|
||||
function describeUnknownSdkMessage(kind: string, message: unknown): string {
|
||||
const preview = previewUnknownSdkContent(message);
|
||||
return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;
|
||||
}
|
||||
|
||||
function sdkNativeItemId(message: SDKMessage): string | undefined {
|
||||
if (message.type === "assistant") {
|
||||
const maybeId = (message.message as { id?: unknown }).id;
|
||||
@@ -2313,31 +2267,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "thinking_tokens":
|
||||
return;
|
||||
case "permission_denied":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "tool.denied",
|
||||
payload: {
|
||||
toolName: message.tool_name,
|
||||
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
|
||||
...(message.decision_reason ? { reason: message.decision_reason } : {}),
|
||||
...(message.agent_id ? { agentId: message.agent_id } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "mirror_error":
|
||||
yield* emitRuntimeError(
|
||||
context,
|
||||
`Claude workspace mirror error: ${message.error}`,
|
||||
message,
|
||||
);
|
||||
return;
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
|
||||
`Unhandled Claude system message subtype '${message.subtype}'.`,
|
||||
message,
|
||||
);
|
||||
return;
|
||||
@@ -2451,7 +2384,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
context,
|
||||
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
|
||||
`Unhandled Claude SDK message type '${message.type}'.`,
|
||||
message,
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -392,20 +392,5 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
|
||||
expect(error.detail).toBe("Relative filesystem browse paths require a current project.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns an empty listing when the OS denies directory access", () =>
|
||||
Effect.gen(function* () {
|
||||
const workspaceEntries = yield* WorkspaceEntries;
|
||||
const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" });
|
||||
|
||||
const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });
|
||||
vi.spyOn(fsPromises, "readdir").mockRejectedValueOnce(denied);
|
||||
|
||||
const result = yield* workspaceEntries.browse({
|
||||
partialPath: appendSeparator(cwd),
|
||||
});
|
||||
expect(result).toEqual({ parentPath: cwd, entries: [] });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -457,18 +457,7 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
cause,
|
||||
}),
|
||||
}).pipe(
|
||||
// The user can deny macOS TCC prompts for the target dir (Documents,
|
||||
// Downloads, Music, etc.); surface an empty listing instead of an
|
||||
// error so the caller doesn't retry-loop the prompt.
|
||||
Effect.catchIf(
|
||||
(error) => {
|
||||
const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;
|
||||
return code === "EACCES" || code === "EPERM";
|
||||
},
|
||||
() => Effect.succeed<Dirent[]>([]),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const showHidden = endsWithSeparator || prefix.startsWith(".");
|
||||
const lowerPrefix = prefix.toLowerCase();
|
||||
|
||||
@@ -562,7 +562,11 @@ function OpenCommandPaletteDialog() {
|
||||
!relativePathNeedsActiveProject,
|
||||
});
|
||||
const browseEntries = browseResult?.entries ?? EMPTY_BROWSE_ENTRIES;
|
||||
const { filteredEntries: filteredBrowseEntries, exactEntry: exactBrowseEntry } = useMemo(
|
||||
const {
|
||||
filteredEntries: filteredBrowseEntries,
|
||||
highlightedEntry: highlightedBrowseEntry,
|
||||
exactEntry: exactBrowseEntry,
|
||||
} = useMemo(
|
||||
() => filterBrowseEntries({ browseEntries, browseFilterQuery, highlightedItemValue }),
|
||||
[browseEntries, browseFilterQuery, highlightedItemValue],
|
||||
);
|
||||
@@ -583,17 +587,27 @@ function OpenCommandPaletteDialog() {
|
||||
[browseEnvironmentId, currentProjectCwdForBrowse, fetchBrowseResult, queryClient],
|
||||
);
|
||||
|
||||
// Prefetch only the parent (for back-navigation). Prefetching the
|
||||
// highlighted child on every arrow-key press triggers a macOS TCC prompt
|
||||
// whenever the highlighted entry is a permission-gated home dir (Music,
|
||||
// Documents, Downloads, Desktop, etc.), so we wait for explicit navigation.
|
||||
// Prefetch the parent and the most likely next child so browse navigation
|
||||
// stays warm without scanning every child directory in large trees.
|
||||
useEffect(() => {
|
||||
if (!isBrowsing || filteredBrowseEntries.length === 0) return;
|
||||
|
||||
if (canNavigateUp(query)) {
|
||||
prefetchBrowsePath(getBrowseParentPath(query)!);
|
||||
}
|
||||
}, [filteredBrowseEntries.length, isBrowsing, prefetchBrowsePath, query]);
|
||||
|
||||
const nextChild = highlightedBrowseEntry ?? exactBrowseEntry;
|
||||
if (nextChild) {
|
||||
prefetchBrowsePath(appendBrowsePathSegment(query, nextChild.name));
|
||||
}
|
||||
}, [
|
||||
exactBrowseEntry,
|
||||
filteredBrowseEntries.length,
|
||||
highlightedBrowseEntry,
|
||||
isBrowsing,
|
||||
prefetchBrowsePath,
|
||||
query,
|
||||
]);
|
||||
|
||||
const openProjectFromSearch = useMemo(
|
||||
() => async (project: (typeof projects)[number]) => {
|
||||
|
||||
@@ -241,7 +241,6 @@ const ModelReroutedType = Schema.Literal("model.rerouted");
|
||||
const ConfigWarningType = Schema.Literal("config.warning");
|
||||
const DeprecationNoticeType = Schema.Literal("deprecation.notice");
|
||||
const FilesPersistedType = Schema.Literal("files.persisted");
|
||||
const ToolDeniedType = Schema.Literal("tool.denied");
|
||||
const RuntimeWarningType = Schema.Literal("runtime.warning");
|
||||
const RuntimeErrorType = Schema.Literal("runtime.error");
|
||||
|
||||
@@ -590,14 +589,6 @@ const FilesPersistedPayload = Schema.Struct({
|
||||
});
|
||||
export type FilesPersistedPayload = typeof FilesPersistedPayload.Type;
|
||||
|
||||
const ToolDeniedPayload = Schema.Struct({
|
||||
toolName: TrimmedNonEmptyStringSchema,
|
||||
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
reason: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
agentId: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type ToolDeniedPayload = typeof ToolDeniedPayload.Type;
|
||||
|
||||
const RuntimeWarningPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
@@ -943,13 +934,6 @@ const ProviderRuntimeFilesPersistedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;
|
||||
|
||||
const ProviderRuntimeToolDeniedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ToolDeniedType,
|
||||
payload: ToolDeniedPayload,
|
||||
});
|
||||
export type ProviderRuntimeToolDeniedEvent = typeof ProviderRuntimeToolDeniedEvent.Type;
|
||||
|
||||
const ProviderRuntimeWarningEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RuntimeWarningType,
|
||||
@@ -1010,7 +994,6 @@ export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeConfigWarningEvent,
|
||||
ProviderRuntimeDeprecationNoticeEvent,
|
||||
ProviderRuntimeFilesPersistedEvent,
|
||||
ProviderRuntimeToolDeniedEvent,
|
||||
ProviderRuntimeWarningEvent,
|
||||
ProviderRuntimeErrorEvent,
|
||||
]);
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import { assert, describe, expect, it } from "@effect/vitest";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
@@ -57,6 +63,47 @@ const makeSpawnerLayer = (commands: Array<string>) =>
|
||||
),
|
||||
);
|
||||
|
||||
const lockedFileInfo: FileSystem.File.Info = {
|
||||
type: "File",
|
||||
mtime: Option.none(),
|
||||
atime: Option.none(),
|
||||
birthtime: Option.none(),
|
||||
dev: 0,
|
||||
ino: Option.none(),
|
||||
mode: 0o644,
|
||||
nlink: Option.none(),
|
||||
uid: Option.none(),
|
||||
gid: Option.none(),
|
||||
rdev: Option.none(),
|
||||
size: FileSystem.Size(0),
|
||||
blksize: Option.none(),
|
||||
blocks: Option.none(),
|
||||
};
|
||||
|
||||
const fileSystemError = (tag: "AlreadyExists" | "NotFound", method: string, path: string) =>
|
||||
PlatformError.systemError({
|
||||
_tag: tag,
|
||||
module: "FileSystem",
|
||||
method,
|
||||
pathOrDescriptor: path,
|
||||
description: tag === "AlreadyExists" ? "File already exists" : "No such file or directory",
|
||||
});
|
||||
|
||||
const makeLockedFileSystemLayer = (attempts: { count: number }) =>
|
||||
FileSystem.layerNoop({
|
||||
makeDirectory: () => Effect.void,
|
||||
remove: () => Effect.void,
|
||||
stat: (path) =>
|
||||
path.endsWith(".lock")
|
||||
? Effect.succeed(lockedFileInfo)
|
||||
: Effect.fail(fileSystemError("NotFound", "stat", path)),
|
||||
writeFileString: (path) =>
|
||||
Effect.gen(function* () {
|
||||
attempts.count += 1;
|
||||
return yield* fileSystemError("AlreadyExists", "writeFileString", path);
|
||||
}),
|
||||
});
|
||||
|
||||
describe("RelayClient", () => {
|
||||
it.effect("resolves explicit overrides before managed and PATH executables", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -227,6 +274,100 @@ describe("RelayClient", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("fails with install_locked after the lock retry schedule is exhausted", () => {
|
||||
const commands: Array<string> = [];
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
const attempts = { count: 0 };
|
||||
return Effect.gen(function* () {
|
||||
const baseDir = "/tmp/t3-cloudflared-test-locked";
|
||||
const manager = yield* makeCloudflaredRelayClient({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(bytes)),
|
||||
archive: "binary",
|
||||
},
|
||||
configProvider: emptyConfigProvider,
|
||||
});
|
||||
|
||||
const install = yield* manager.install.pipe(Effect.flip, Effect.forkScoped);
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
const error = yield* Fiber.join(install);
|
||||
|
||||
assert.ok(error instanceof RelayClientInstallError);
|
||||
assert.equal(error.reason, "install_locked");
|
||||
assert.equal(attempts.count, 100);
|
||||
assert.equal(commands.length, 0);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
makeLockedFileSystemLayer(attempts),
|
||||
TestClock.layer(),
|
||||
makeHttpClientLayer(bytes),
|
||||
makeSpawnerLayer(commands),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("removes stale install locks before downloading the managed executable", () => {
|
||||
const commands: Array<string> = [];
|
||||
const bytes = new TextEncoder().encode("test-cloudflared-binary");
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-cloudflared-test-stale-lock-",
|
||||
});
|
||||
const managedPath = resolveManagedCloudflaredPath({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
});
|
||||
const lockPath = `${managedPath}.lock`;
|
||||
const path = yield* Path.Path;
|
||||
yield* fileSystem.makeDirectory(path.dirname(managedPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(lockPath, "stale");
|
||||
yield* fileSystem.utimes(lockPath, 0, 0);
|
||||
const manager = yield* makeCloudflaredRelayClient({
|
||||
baseDir,
|
||||
platform: "linux",
|
||||
arch: "x64",
|
||||
releaseAsset: {
|
||||
url: "https://example.test/cloudflared",
|
||||
sha256: Encoding.encodeHex(sha256(bytes)),
|
||||
archive: "binary",
|
||||
},
|
||||
configProvider: emptyConfigProvider,
|
||||
});
|
||||
|
||||
yield* TestClock.adjust(Duration.minutes(6));
|
||||
const installed = yield* manager.install;
|
||||
|
||||
assert.deepStrictEqual(installed, {
|
||||
status: "available",
|
||||
executablePath: managedPath,
|
||||
source: "managed",
|
||||
version: CLOUDFLARED_VERSION,
|
||||
});
|
||||
assert.equal(commands.length, 1);
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
TestClock.layer(),
|
||||
makeHttpClientLayer(bytes),
|
||||
makeSpawnerLayer(commands),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("observes PATH changes after the manager has been constructed", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import type {
|
||||
RelayClientInstallProgressEvent,
|
||||
RelayClientInstallProgressStage,
|
||||
@@ -8,6 +7,8 @@ import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
@@ -15,6 +16,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -62,6 +64,12 @@ class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError"
|
||||
readonly exitCode: number;
|
||||
}> {}
|
||||
|
||||
class RelayClientInstallLockUnavailable extends Data.TaggedError(
|
||||
"RelayClientInstallLockUnavailable",
|
||||
)<{
|
||||
readonly lockPath: string;
|
||||
}> {}
|
||||
|
||||
export interface CloudflaredReleaseAsset {
|
||||
readonly url: string;
|
||||
readonly sha256: string;
|
||||
@@ -99,8 +107,11 @@ const CLOUDFLARED_RELEASE_ASSETS: Readonly<
|
||||
};
|
||||
|
||||
const INSTALL_LOCK_RETRY_COUNT = 100;
|
||||
const INSTALL_LOCK_RETRY_DELAY = "100 millis";
|
||||
const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
|
||||
const INSTALL_LOCK_RETRY_DELAY = Duration.millis(100);
|
||||
const INSTALL_LOCK_STALE_AFTER = Duration.minutes(5);
|
||||
const INSTALL_LOCK_RETRY_SCHEDULE = Schedule.spaced(INSTALL_LOCK_RETRY_DELAY).pipe(
|
||||
Schedule.both(Schedule.recurs(INSTALL_LOCK_RETRY_COUNT - 1)),
|
||||
);
|
||||
|
||||
const trimmedString = (name: string) =>
|
||||
Config.string(name).pipe(
|
||||
@@ -354,28 +365,45 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function
|
||||
const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
|
||||
lockPath: string,
|
||||
) {
|
||||
for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
const acquireInstallLockOnce = Effect.fn("cloudflared.acquireInstallLockOnce")(function* () {
|
||||
while (true) {
|
||||
const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catch((error) =>
|
||||
isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
|
||||
),
|
||||
);
|
||||
if (acquired) return;
|
||||
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
continue;
|
||||
const now = yield* DateTime.now;
|
||||
const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
|
||||
const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
|
||||
const staleBefore = DateTime.subtractDuration(now, INSTALL_LOCK_STALE_AFTER);
|
||||
if (
|
||||
Option.isSome(mtime) &&
|
||||
DateTime.Order(DateTime.fromDateUnsafe(mtime.value), staleBefore) < 0
|
||||
) {
|
||||
yield* fileSystem.remove(lockPath, { force: true });
|
||||
continue;
|
||||
}
|
||||
return yield* new RelayClientInstallLockUnavailable({ lockPath });
|
||||
}
|
||||
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
|
||||
}
|
||||
return yield* new RelayClientInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another relay client installation is still in progress.",
|
||||
});
|
||||
|
||||
return yield* acquireInstallLockOnce().pipe(
|
||||
Effect.retry({
|
||||
schedule: INSTALL_LOCK_RETRY_SCHEDULE,
|
||||
while: (error) => error instanceof RelayClientInstallLockUnavailable,
|
||||
}),
|
||||
Effect.catchTag("RelayClientInstallLockUnavailable", () =>
|
||||
Effect.fail(
|
||||
new RelayClientInstallError({
|
||||
reason: "install_locked",
|
||||
message: "Another relay client installation is still in progress.",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
|
||||
|
||||
@@ -219,7 +219,7 @@ describe("ssh command", () => {
|
||||
username: "julius",
|
||||
port: 2222,
|
||||
},
|
||||
{ timeout: Duration.millis(1) },
|
||||
{ timeoutMs: 1 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -14,7 +14,7 @@ import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
|
||||
import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
|
||||
|
||||
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
|
||||
const DEFAULT_SSH_COMMAND_TIMEOUT = Duration.seconds(60);
|
||||
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000;
|
||||
const MAX_SSH_ERROR_OUTPUT_LENGTH = 4_000;
|
||||
export const SSH_COMMAND = process.platform === "win32" ? "ssh.exe" : "ssh";
|
||||
|
||||
@@ -29,8 +29,6 @@ export interface RunSshCommandOptions extends SshAuthOptions {
|
||||
readonly preHostArgs?: ReadonlyArray<string>;
|
||||
readonly remoteCommandArgs?: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly timeout?: Duration.Input;
|
||||
/** @deprecated Prefer `timeout` with an Effect Duration input. */
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
@@ -159,10 +157,6 @@ function stdinStream(input: string | undefined) {
|
||||
return input === undefined ? Stream.empty : Stream.make(encoder.encode(input));
|
||||
}
|
||||
|
||||
function resolveSshCommandTimeout(input: RunSshCommandOptions): Duration.Duration {
|
||||
return Duration.fromInputUnsafe(input.timeout ?? input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT);
|
||||
}
|
||||
|
||||
const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(function* (
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
input: RunSshCommandOptions,
|
||||
@@ -197,12 +191,11 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
|
||||
...(input.remoteCommandArgs ?? []),
|
||||
];
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const timeout = resolveSshCommandTimeout(input);
|
||||
yield* Effect.logDebug("ssh.command.start", {
|
||||
...sshTargetLogFields(target),
|
||||
command: [SSH_COMMAND, ...args],
|
||||
hasStdin: input.stdin !== undefined,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
|
||||
});
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
@@ -289,12 +282,10 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
|
||||
SshCommandError | SshInvalidTargetError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
const timeout = resolveSshCommandTimeout(input);
|
||||
const timeoutMs = Duration.toMillis(timeout);
|
||||
return yield* Effect.scopedWith((commandScope) =>
|
||||
runSshCommandInScope(target, input, commandScope),
|
||||
).pipe(
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onSome: Effect.succeed,
|
||||
@@ -302,7 +293,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.logWarning("ssh.command.timedOut", {
|
||||
...sshTargetLogFields(target),
|
||||
timeoutMs,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS,
|
||||
remoteCommandArgs: input.remoteCommandArgs ?? [],
|
||||
preHostArgs: input.preHostArgs ?? [],
|
||||
hasStdin: input.stdin !== undefined,
|
||||
@@ -311,7 +302,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
|
||||
command: ["ssh"],
|
||||
exitCode: null,
|
||||
stderr: "",
|
||||
message: `SSH command timed out after ${timeoutMs}ms.`,
|
||||
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`,
|
||||
});
|
||||
}),
|
||||
}),
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { SshCommandError, SshError } from "./errors.ts";
|
||||
|
||||
const encodeSshError = Schema.encodeSync(SshError);
|
||||
const isSshError = Schema.is(SshError);
|
||||
|
||||
describe("ssh errors", () => {
|
||||
it("encodes schema-backed SSH errors as tagged serializable data", () => {
|
||||
const error = new SshCommandError({
|
||||
message: "SSH command failed.",
|
||||
command: ["ssh", "devbox"],
|
||||
exitCode: 255,
|
||||
stderr: "permission denied",
|
||||
});
|
||||
|
||||
assert.isTrue(isSshError(error));
|
||||
assert.deepEqual(encodeSshError(error), {
|
||||
_tag: "SshCommandError",
|
||||
message: "SSH command failed.",
|
||||
command: ["ssh", "devbox"],
|
||||
exitCode: 255,
|
||||
stderr: "permission denied",
|
||||
});
|
||||
});
|
||||
});
|
||||
+39
-73
@@ -1,81 +1,47 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Data from "effect/Data";
|
||||
|
||||
const SshCommandArgs = Schema.Array(Schema.String);
|
||||
export class SshHostDiscoveryError extends Data.TaggedError("SshHostDiscoveryError")<{
|
||||
readonly message: string;
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshHostDiscoveryError extends Schema.TaggedErrorClass<SshHostDiscoveryError>()(
|
||||
"SshHostDiscoveryError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
export class SshInvalidTargetError extends Data.TaggedError("SshInvalidTargetError")<{
|
||||
readonly message: string;
|
||||
}> {}
|
||||
|
||||
export class SshInvalidTargetError extends Schema.TaggedErrorClass<SshInvalidTargetError>()(
|
||||
"SshInvalidTargetError",
|
||||
{
|
||||
message: Schema.String,
|
||||
},
|
||||
) {}
|
||||
export class SshCommandError extends Data.TaggedError("SshCommandError")<{
|
||||
readonly message: string;
|
||||
readonly command: readonly string[];
|
||||
readonly exitCode: number | null;
|
||||
readonly stderr: string;
|
||||
readonly stdout?: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshCommandError extends Schema.TaggedErrorClass<SshCommandError>()("SshCommandError", {
|
||||
message: Schema.String,
|
||||
command: SshCommandArgs,
|
||||
exitCode: Schema.NullOr(Schema.Number),
|
||||
stderr: Schema.String,
|
||||
stdout: Schema.optional(Schema.String),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
export class SshLaunchError extends Data.TaggedError("SshLaunchError")<{
|
||||
readonly message: string;
|
||||
readonly stdout: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshLaunchError extends Schema.TaggedErrorClass<SshLaunchError>()("SshLaunchError", {
|
||||
message: Schema.String,
|
||||
stdout: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
export class SshPairingError extends Data.TaggedError("SshPairingError")<{
|
||||
readonly message: string;
|
||||
readonly stdout: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshPairingError extends Schema.TaggedErrorClass<SshPairingError>()("SshPairingError", {
|
||||
message: Schema.String,
|
||||
stdout: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
}) {}
|
||||
export class SshHttpBridgeError extends Data.TaggedError("SshHttpBridgeError")<{
|
||||
readonly message: string;
|
||||
readonly status?: number;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshHttpBridgeError extends Schema.TaggedErrorClass<SshHttpBridgeError>()(
|
||||
"SshHttpBridgeError",
|
||||
{
|
||||
message: Schema.String,
|
||||
status: Schema.optional(Schema.Number),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
export class SshReadinessError extends Data.TaggedError("SshReadinessError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
export class SshReadinessError extends Schema.TaggedErrorClass<SshReadinessError>()(
|
||||
"SshReadinessError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export class SshPasswordPromptError extends Schema.TaggedErrorClass<SshPasswordPromptError>()(
|
||||
"SshPasswordPromptError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
export const SshEnvironmentError = Schema.Union([
|
||||
SshCommandError,
|
||||
SshInvalidTargetError,
|
||||
SshLaunchError,
|
||||
SshPairingError,
|
||||
SshReadinessError,
|
||||
SshPasswordPromptError,
|
||||
]);
|
||||
export type SshEnvironmentError = typeof SshEnvironmentError.Type;
|
||||
|
||||
export const SshError = Schema.Union([
|
||||
SshHostDiscoveryError,
|
||||
SshHttpBridgeError,
|
||||
SshEnvironmentError,
|
||||
]);
|
||||
export type SshError = typeof SshError.Type;
|
||||
export class SshPasswordPromptError extends Data.TaggedError("SshPasswordPromptError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
|
||||
Effect.result(
|
||||
waitForHttpReady({
|
||||
baseUrl: "http://127.0.0.1:41773/",
|
||||
timeout: Duration.seconds(1),
|
||||
interval: Duration.millis(100),
|
||||
probeTimeout: Duration.millis(250),
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 100,
|
||||
probeTimeoutMs: 250,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
+22
-50
@@ -51,14 +51,11 @@ import {
|
||||
|
||||
export const DEFAULT_REMOTE_PORT = 3773;
|
||||
const REMOTE_PORT_SCAN_WINDOW = 200;
|
||||
const SSH_READY_TIMEOUT = Duration.seconds(20);
|
||||
const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
|
||||
const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
|
||||
const REMOTE_READY_TIMEOUT = Duration.seconds(15);
|
||||
const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
|
||||
const DEFAULT_HTTP_READY_TIMEOUT = Duration.seconds(30);
|
||||
const DEFAULT_HTTP_READY_INTERVAL = Duration.millis(100);
|
||||
const isSshReadinessError = Schema.is(SshReadinessError);
|
||||
const SSH_READY_TIMEOUT_MS = 20_000;
|
||||
const SSH_READY_PROBE_TIMEOUT_MS = 1_000;
|
||||
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000;
|
||||
const REMOTE_READY_TIMEOUT_MS = 15_000;
|
||||
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000;
|
||||
|
||||
export interface RemoteT3RunnerOptions {
|
||||
readonly packageSpec?: string;
|
||||
@@ -236,7 +233,7 @@ function applyScriptPlaceholders(
|
||||
}
|
||||
|
||||
export function describeReadinessCause(cause: unknown): unknown {
|
||||
if (isSshReadinessError(cause)) {
|
||||
if (cause instanceof SshReadinessError) {
|
||||
return {
|
||||
_tag: cause._tag,
|
||||
message: cause.message,
|
||||
@@ -685,9 +682,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
|
||||
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
|
||||
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
|
||||
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
|
||||
T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
|
||||
T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
|
||||
T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
|
||||
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS),
|
||||
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS),
|
||||
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -859,7 +856,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
|
||||
const result = yield* runSshCommand(target, {
|
||||
remoteCommandArgs: ["sh", "-s"],
|
||||
stdin: buildRemoteLogTailScript(target),
|
||||
timeout: Duration.seconds(10),
|
||||
timeoutMs: 10_000,
|
||||
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
|
||||
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
|
||||
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
|
||||
@@ -867,42 +864,17 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
function resolveDurationInput(
|
||||
duration: Duration.Input | undefined,
|
||||
durationMs: number | undefined,
|
||||
fallback: Duration.Duration,
|
||||
): Duration.Duration {
|
||||
return Duration.fromInputUnsafe(duration ?? durationMs ?? fallback);
|
||||
}
|
||||
|
||||
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
|
||||
readonly baseUrl: string;
|
||||
readonly timeout?: Duration.Input;
|
||||
readonly interval?: Duration.Input;
|
||||
readonly probeTimeout?: Duration.Input;
|
||||
/** @deprecated Prefer `timeout` with an Effect Duration input. */
|
||||
readonly timeoutMs?: number;
|
||||
/** @deprecated Prefer `interval` with an Effect Duration input. */
|
||||
readonly intervalMs?: number;
|
||||
/** @deprecated Prefer `probeTimeout` with an Effect Duration input. */
|
||||
readonly probeTimeoutMs?: number;
|
||||
readonly path?: string;
|
||||
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
|
||||
const timeout = resolveDurationInput(input.timeout, input.timeoutMs, DEFAULT_HTTP_READY_TIMEOUT);
|
||||
const interval = resolveDurationInput(
|
||||
input.interval,
|
||||
input.intervalMs,
|
||||
DEFAULT_HTTP_READY_INTERVAL,
|
||||
);
|
||||
const probeTimeout = resolveDurationInput(
|
||||
input.probeTimeout,
|
||||
input.probeTimeoutMs,
|
||||
SSH_READY_PROBE_TIMEOUT,
|
||||
);
|
||||
const timeoutMs = Duration.toMillis(timeout);
|
||||
const intervalMs = Duration.toMillis(interval);
|
||||
const probeTimeoutMs = Duration.toMillis(probeTimeout);
|
||||
const retryPolicy = Schedule.spaced(interval).pipe(
|
||||
const timeoutMs = input.timeoutMs ?? 30_000;
|
||||
const intervalMs = input.intervalMs ?? 100;
|
||||
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS;
|
||||
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe(
|
||||
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))),
|
||||
);
|
||||
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
|
||||
@@ -924,7 +896,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
Effect.gen(function* () {
|
||||
attempt += 1;
|
||||
const responseOption = yield* effect.pipe(
|
||||
Effect.timeoutOption(probeTimeout),
|
||||
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SshReadinessError({
|
||||
@@ -949,7 +921,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isSshReadinessError(cause)
|
||||
cause instanceof SshReadinessError
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
@@ -970,14 +942,14 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
|
||||
|
||||
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isSshReadinessError(cause)
|
||||
cause instanceof SshReadinessError
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(timeout),
|
||||
Effect.timeoutOption(Duration.millis(timeoutMs)),
|
||||
);
|
||||
|
||||
return yield* Option.match(result, {
|
||||
@@ -1194,7 +1166,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
|
||||
yield* Effect.raceFirst(
|
||||
waitForHttpReady({
|
||||
baseUrl: input.httpBaseUrl,
|
||||
timeout: SSH_READY_TIMEOUT,
|
||||
timeoutMs: SSH_READY_TIMEOUT_MS,
|
||||
}),
|
||||
exitFailure,
|
||||
).pipe(
|
||||
@@ -1254,7 +1226,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
|
||||
: child
|
||||
.kill({
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
|
||||
})
|
||||
.pipe(Effect.ignore),
|
||||
),
|
||||
@@ -1498,7 +1470,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
|
||||
[
|
||||
tunnelEntry.process.kill({
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
|
||||
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS,
|
||||
}),
|
||||
stopRemoteServer(
|
||||
tunnelEntry.target,
|
||||
@@ -1552,7 +1524,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
|
||||
remotePort: entry.remotePort,
|
||||
});
|
||||
const readinessExit = yield* Effect.exit(
|
||||
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
|
||||
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }),
|
||||
);
|
||||
if (Exit.isSuccess(readinessExit)) {
|
||||
yield* Effect.logDebug("ssh.environment.tunnel.reused", {
|
||||
|
||||
Reference in new issue
Block a user