Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 431692222d Use Duration policies in SSH readiness
Co-authored-by: Julius Marminge <[email protected]>
2026-06-01 16:06:46 +00:00
4 changed files with 54 additions and 41 deletions

No files matched your search

+1 -1
View File
@@ -139,7 +139,7 @@ describe("ssh command", () => {
username: "julius", username: "julius",
port: 2222, port: 2222,
}, },
{ timeoutMs: 1 }, { timeout: Duration.millis(1) },
), ),
), ),
); );
+10 -6
View File
@@ -14,7 +14,7 @@ import { buildSshChildEnvironment, type SshAuthOptions } from "./auth.ts";
import { SshCommandError, SshInvalidTargetError } from "./errors.ts"; import { SshCommandError, SshInvalidTargetError } from "./errors.ts";
const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u; const PUBLISHABLE_T3_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u;
const DEFAULT_SSH_COMMAND_TIMEOUT_MS = 60_000; const DEFAULT_SSH_COMMAND_TIMEOUT = Duration.seconds(60);
const encoder = new TextEncoder(); const encoder = new TextEncoder();
@@ -27,7 +27,7 @@ export interface RunSshCommandOptions extends SshAuthOptions {
readonly preHostArgs?: ReadonlyArray<string>; readonly preHostArgs?: ReadonlyArray<string>;
readonly remoteCommandArgs?: ReadonlyArray<string>; readonly remoteCommandArgs?: ReadonlyArray<string>;
readonly stdin?: string; readonly stdin?: string;
readonly timeoutMs?: number; readonly timeout?: Duration.Input;
} }
export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget { export function parseSshResolveOutput(alias: string, stdout: string): DesktopSshEnvironmentTarget {
@@ -146,6 +146,8 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> { > {
const hostSpec = yield* buildSshHostSpecEffect(target); const hostSpec = yield* buildSshHostSpecEffect(target);
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_SSH_COMMAND_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
const environment = yield* buildSshChildEnvironment({ const environment = yield* buildSshChildEnvironment({
...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), ...(input.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input.authSecret === undefined ? {} : { authSecret: input.authSecret }),
@@ -174,7 +176,7 @@ const runSshCommandInScope = Effect.fn("ssh/command.runSshCommand.inScope")(func
...sshTargetLogFields(target), ...sshTargetLogFields(target),
command: ["ssh", ...args], command: ["ssh", ...args],
hasStdin: input.stdin !== undefined, hasStdin: input.stdin !== undefined,
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS, timeoutMs,
}); });
const child = yield* spawner const child = yield* spawner
.spawn( .spawn(
@@ -258,10 +260,12 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
SshCommandError | SshInvalidTargetError, SshCommandError | SshInvalidTargetError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> { > {
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_SSH_COMMAND_TIMEOUT);
const timeoutMs = Duration.toMillis(timeout);
return yield* Effect.scopedWith((commandScope) => return yield* Effect.scopedWith((commandScope) =>
runSshCommandInScope(target, input, commandScope), runSshCommandInScope(target, input, commandScope),
).pipe( ).pipe(
Effect.timeoutOption(Duration.millis(input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS)), Effect.timeoutOption(timeout),
Effect.flatMap((result) => Effect.flatMap((result) =>
Option.match(result, { Option.match(result, {
onSome: Effect.succeed, onSome: Effect.succeed,
@@ -269,7 +273,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
Effect.gen(function* () { Effect.gen(function* () {
yield* Effect.logWarning("ssh.command.timedOut", { yield* Effect.logWarning("ssh.command.timedOut", {
...sshTargetLogFields(target), ...sshTargetLogFields(target),
timeoutMs: input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS, timeoutMs,
remoteCommandArgs: input.remoteCommandArgs ?? [], remoteCommandArgs: input.remoteCommandArgs ?? [],
preHostArgs: input.preHostArgs ?? [], preHostArgs: input.preHostArgs ?? [],
hasStdin: input.stdin !== undefined, hasStdin: input.stdin !== undefined,
@@ -278,7 +282,7 @@ export const runSshCommand = Effect.fn("ssh/command.runSshCommand")(function* (
command: ["ssh"], command: ["ssh"],
exitCode: null, exitCode: null,
stderr: "", stderr: "",
message: `SSH command timed out after ${input.timeoutMs ?? DEFAULT_SSH_COMMAND_TIMEOUT_MS}ms.`, message: `SSH command timed out after ${timeoutMs}ms.`,
}); });
}), }),
}), }),
+3 -3
View File
@@ -242,9 +242,9 @@ describe("ssh tunnel scripts", () => {
Effect.result( Effect.result(
waitForHttpReady({ waitForHttpReady({
baseUrl: "http://127.0.0.1:41773/", baseUrl: "http://127.0.0.1:41773/",
timeoutMs: 1_000, timeout: Duration.seconds(1),
intervalMs: 100, interval: Duration.millis(100),
probeTimeoutMs: 250, probeTimeout: Duration.millis(250),
}), }),
), ),
); );
+40 -31
View File
@@ -50,11 +50,11 @@ import {
export const DEFAULT_REMOTE_PORT = 3773; export const DEFAULT_REMOTE_PORT = 3773;
const REMOTE_PORT_SCAN_WINDOW = 200; const REMOTE_PORT_SCAN_WINDOW = 200;
const SSH_READY_TIMEOUT_MS = 20_000; const SSH_READY_TIMEOUT = Duration.seconds(20);
const SSH_READY_PROBE_TIMEOUT_MS = 1_000; const SSH_READY_PROBE_TIMEOUT = Duration.seconds(1);
const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000; const TUNNEL_SHUTDOWN_TIMEOUT = Duration.seconds(2);
const REMOTE_READY_TIMEOUT_MS = 15_000; const REMOTE_READY_TIMEOUT = Duration.seconds(15);
const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000; const REMOTE_REUSE_READY_TIMEOUT = Duration.seconds(2);
export interface RemoteT3RunnerOptions { export interface RemoteT3RunnerOptions {
readonly packageSpec?: string; readonly packageSpec?: string;
@@ -686,9 +686,9 @@ export function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string {
T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT), T3_WAIT_READY_SCRIPT: stripTrailingNewlines(REMOTE_WAIT_READY_SCRIPT),
T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT), T3_DEFAULT_REMOTE_PORT: String(DEFAULT_REMOTE_PORT),
T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW), T3_REMOTE_PORT_SCAN_WINDOW: String(REMOTE_PORT_SCAN_WINDOW),
T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS), T3_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_READY_TIMEOUT)),
T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS), T3_REUSE_READY_TIMEOUT_MS: String(Duration.toMillis(REMOTE_REUSE_READY_TIMEOUT)),
T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS), T3_READY_PROBE_TIMEOUT_MS: String(Duration.toMillis(SSH_READY_PROBE_TIMEOUT)),
}); });
} }
@@ -860,7 +860,7 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
const result = yield* runSshCommand(target, { const result = yield* runSshCommand(target, {
remoteCommandArgs: ["sh", "-s"], remoteCommandArgs: ["sh", "-s"],
stdin: buildRemoteLogTailScript(target), stdin: buildRemoteLogTailScript(target),
timeoutMs: 10_000, timeout: Duration.seconds(10),
...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }), ...(input?.authSecret === undefined ? {} : { authSecret: input.authSecret }),
...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }), ...(input?.batchMode === undefined ? {} : { batchMode: input.batchMode }),
...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }), ...(input?.interactiveAuth === undefined ? {} : { interactiveAuth: input.interactiveAuth }),
@@ -870,20 +870,26 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: { export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
readonly baseUrl: string; readonly baseUrl: string;
readonly timeoutMs?: number; readonly timeout?: Duration.Input;
readonly intervalMs?: number; readonly interval?: Duration.Input;
readonly probeTimeoutMs?: number; readonly probeTimeout?: Duration.Input;
readonly path?: string; readonly path?: string;
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> { }): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
const timeoutMs = input.timeoutMs ?? 30_000; const timeout = Duration.fromInputUnsafe(input.timeout ?? Duration.seconds(30));
const intervalMs = input.intervalMs ?? 100; const interval = Duration.fromInputUnsafe(input.interval ?? Duration.millis(100));
const probeTimeoutMs = input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS; const probeTimeout = Duration.fromInputUnsafe(input.probeTimeout ?? SSH_READY_PROBE_TIMEOUT);
const retryPolicy = Schedule.spaced(Duration.millis(intervalMs)).pipe( const timeoutMs = Duration.toMillis(timeout);
Schedule.take(Math.max(0, Math.ceil(timeoutMs / intervalMs))), const intervalMs = Duration.toMillis(interval);
); const probeTimeoutMs = Duration.toMillis(probeTimeout);
const retryPolicy = Schedule.spaced(interval);
const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString(); const requestUrl = new URL(input.path ?? "/", input.baseUrl).toString();
const client = yield* HttpClient.HttpClient; const client = yield* HttpClient.HttpClient;
const lastProbeFailure = yield* Ref.make<unknown>(null); const lastProbeFailure = yield* Ref.make(
Option.none<{
readonly attempt: number;
readonly cause: unknown;
}>(),
);
let attempt = 0; let attempt = 0;
yield* Effect.logDebug("ssh.tunnel.httpReady.start", { yield* Effect.logDebug("ssh.tunnel.httpReady.start", {
@@ -900,7 +906,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
Effect.gen(function* () { Effect.gen(function* () {
attempt += 1; attempt += 1;
const responseOption = yield* effect.pipe( const responseOption = yield* effect.pipe(
Effect.timeoutOption(Duration.millis(probeTimeoutMs)), Effect.timeoutOption(probeTimeout),
Effect.mapError( Effect.mapError(
(cause) => (cause) =>
new SshReadinessError({ new SshReadinessError({
@@ -933,10 +939,13 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
}), }),
), ),
Effect.tapError((cause) => Effect.tapError((cause) =>
Ref.set(lastProbeFailure, { Ref.set(
attempt, lastProbeFailure,
cause: describeReadinessCause(cause), Option.some({
}), attempt,
cause: describeReadinessCause(cause),
}),
),
), ),
), ),
), ),
@@ -953,7 +962,7 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
cause, cause,
}), }),
), ),
Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.timeoutOption(timeout),
); );
return yield* Option.match(result, { return yield* Option.match(result, {
@@ -973,11 +982,11 @@ export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(functio
intervalMs, intervalMs,
probeTimeoutMs, probeTimeoutMs,
attempts: attempt, attempts: attempt,
lastFailure, lastFailure: Option.getOrNull(lastFailure),
}); });
return yield* new SshReadinessError({ return yield* new SshReadinessError({
message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`, message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`,
cause: lastFailure, cause: Option.getOrUndefined(lastFailure),
}); });
}), }),
}); });
@@ -1236,7 +1245,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
yield* Effect.raceFirst( yield* Effect.raceFirst(
waitForHttpReady({ waitForHttpReady({
baseUrl: input.httpBaseUrl, baseUrl: input.httpBaseUrl,
timeoutMs: SSH_READY_TIMEOUT_MS, timeout: SSH_READY_TIMEOUT,
}), }),
exitFailure, exitFailure,
).pipe( ).pipe(
@@ -1296,7 +1305,7 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
: child : child
.kill({ .kill({
killSignal: "SIGTERM", killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
}) })
.pipe(Effect.ignore), .pipe(Effect.ignore),
), ),
@@ -1540,7 +1549,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
[ [
tunnelEntry.process.kill({ tunnelEntry.process.kill({
killSignal: "SIGTERM", killSignal: "SIGTERM",
forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT_MS, forceKillAfter: TUNNEL_SHUTDOWN_TIMEOUT,
}), }),
stopRemoteServer( stopRemoteServer(
tunnelEntry.target, tunnelEntry.target,
@@ -1594,7 +1603,7 @@ const makeSshEnvironmentManager = Effect.fn("ssh/tunnel.SshEnvironmentManager.ma
remotePort: entry.remotePort, remotePort: entry.remotePort,
}); });
const readinessExit = yield* Effect.exit( const readinessExit = yield* Effect.exit(
waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeoutMs: 2_000 }), waitForHttpReady({ baseUrl: entry.httpBaseUrl, timeout: Duration.seconds(2) }),
); );
if (Exit.isSuccess(readinessExit)) { if (Exit.isSuccess(readinessExit)) {
yield* Effect.logDebug("ssh.environment.tunnel.reused", { yield* Effect.logDebug("ssh.environment.tunnel.reused", {