Reuse a shared HTTP readiness probe across ssh + desktop
The desktop backend manager and the SSH tunnel each had their own HTTP readiness probe. Extract the richer SSH implementation into @t3tools/shared/httpReadiness as a generic waitForHttpReady parameterized by a makeError callback, so each caller keeps its own tagged error: - ssh/tunnel: thin wrapper that still fails with SshReadinessError (tag, messages, and cause shapes unchanged). - DesktopBackendManager: delegates to the shared probe, still failing with BackendTimeoutError; its external signature is unchanged. It picks up the per-probe timeout + bounded-retry behavior the SSH probe already had. Verified: shared + ssh + desktop typecheck clean; full ssh suite (25) and desktop backend tests (14) pass; SshReadinessError is unchanged.
This commit is contained in:
1 parent
e7b98cac74
commit
61fa07149c
4 files changed
+222
-152
No files matched your search
@@ -47,6 +47,7 @@ import {
|
||||
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
} from "@t3tools/contracts";
|
||||
import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness";
|
||||
|
||||
import * as DesktopObservability from "../app/DesktopObservability.ts";
|
||||
|
||||
@@ -274,23 +275,20 @@ const closeRun = (
|
||||
).pipe(Effect.ignore);
|
||||
};
|
||||
|
||||
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
|
||||
const waitForHttpReady = (
|
||||
baseUrl: URL,
|
||||
timeout: Duration.Duration,
|
||||
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
|
||||
): Effect.Effect<void, BackendTimeoutError, HttpClient.HttpClient> => {
|
||||
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
|
||||
const client = (yield* HttpClient.HttpClient).pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
|
||||
HttpClient.retry(Schedule.spaced(DEFAULT_BACKEND_READINESS_INTERVAL)),
|
||||
);
|
||||
|
||||
yield* client.get(readinessUrl).pipe(
|
||||
Effect.asVoid,
|
||||
Effect.timeout(timeout),
|
||||
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
|
||||
);
|
||||
});
|
||||
return waitForHttpReadyShared({
|
||||
baseUrl: baseUrl.href,
|
||||
path: BACKEND_READINESS_PATH,
|
||||
timeoutMs: Duration.toMillis(timeout),
|
||||
intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL),
|
||||
probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT),
|
||||
makeError: () => new BackendTimeoutError({ url: readinessUrl }),
|
||||
});
|
||||
};
|
||||
|
||||
function describeProcessExit(
|
||||
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
|
||||
|
||||
@@ -170,6 +170,10 @@
|
||||
"./hostProcess": {
|
||||
"types": "./src/hostProcess.ts",
|
||||
"import": "./src/hostProcess.ts"
|
||||
},
|
||||
"./httpReadiness": {
|
||||
"types": "./src/httpReadiness.ts",
|
||||
"import": "./src/httpReadiness.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
export const DEFAULT_HTTP_READY_PROBE_TIMEOUT_MS = 1_000;
|
||||
|
||||
/**
|
||||
* Normalizes an arbitrary readiness probe failure into a plain, structured value
|
||||
* suitable for diagnostic logging. Preserves the tagged-error `_tag` (and
|
||||
* message/cause) shape for Effect tagged errors while recursing through nested
|
||||
* `cause`/`reason` chains.
|
||||
*/
|
||||
export function describeReadinessCause(cause: unknown): unknown {
|
||||
if (cause instanceof Error) {
|
||||
const tag = (cause as { readonly _tag?: unknown })._tag;
|
||||
const nested = (cause as { readonly cause?: unknown }).cause;
|
||||
return {
|
||||
...(typeof tag === "string" ? { _tag: tag } : { name: cause.name }),
|
||||
message: cause.message,
|
||||
...(nested === undefined ? {} : { cause: describeReadinessCause(nested) }),
|
||||
};
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return cause;
|
||||
}
|
||||
|
||||
const record = cause as Readonly<Record<string, unknown>>;
|
||||
return {
|
||||
...(typeof record._tag === "string" ? { _tag: record._tag } : {}),
|
||||
...(typeof record.message === "string" ? { message: record.message } : {}),
|
||||
...(record.reason === undefined ? {} : { reason: describeReadinessCause(record.reason) }),
|
||||
...(record.cause === undefined ? {} : { cause: describeReadinessCause(record.cause) }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic HTTP readiness probe shared by the SSH tunnel and the desktop backend
|
||||
* manager. Polls `baseUrl + path` until it returns a 2xx response or the overall
|
||||
* `timeoutMs` elapses. Each individual probe is bounded by `probeTimeoutMs` so a
|
||||
* single hung request cannot stall the retry loop, and the retry cadence is
|
||||
* `intervalMs` bounded to roughly `timeoutMs / intervalMs` attempts.
|
||||
*
|
||||
* The error type is left to the caller via `makeError`, so each consumer keeps
|
||||
* its own tagged error. `makeError` is called at every failure site; callers can
|
||||
* inspect `cause` (which carries a `kind` discriminator for the probe-timeout and
|
||||
* overall-timeout cases) to reproduce phase-specific messages, or ignore it.
|
||||
*/
|
||||
export const waitForHttpReady = Effect.fn("shared.httpReadiness.waitForHttpReady")(function* <E>(input: {
|
||||
readonly baseUrl: string;
|
||||
readonly path?: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly intervalMs?: number;
|
||||
readonly probeTimeoutMs?: number;
|
||||
readonly makeError: (info: {
|
||||
readonly requestUrl: string;
|
||||
readonly probeTimeoutMs: number;
|
||||
readonly attempt: number;
|
||||
readonly cause: unknown;
|
||||
}) => E;
|
||||
}): Effect.fn.Return<void, E, HttpClient.HttpClient> {
|
||||
const timeoutMs = input.timeoutMs ?? 30_000;
|
||||
const intervalMs = input.intervalMs ?? 100;
|
||||
const probeTimeoutMs = input.probeTimeoutMs ?? DEFAULT_HTTP_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();
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const lastProbeFailure = yield* Ref.make<unknown>(null);
|
||||
let attempt = 0;
|
||||
|
||||
// Tracks errors this function itself produced via `makeError`, so the
|
||||
// pass-through guards below never double-wrap an already-constructed error
|
||||
// (mirrors the SSH original's `cause instanceof SshReadinessError` checks).
|
||||
const makeError = input.makeError;
|
||||
const madeErrors = new WeakSet<object>();
|
||||
const fail = (cause: unknown): E => {
|
||||
const error = makeError({ requestUrl, probeTimeoutMs, attempt, cause });
|
||||
if (typeof error === "object" && error !== null) {
|
||||
madeErrors.add(error);
|
||||
}
|
||||
return error;
|
||||
};
|
||||
const isMadeError = (value: unknown): value is E =>
|
||||
typeof value === "object" && value !== null && madeErrors.has(value);
|
||||
|
||||
yield* Effect.logDebug("httpReadiness.start", {
|
||||
baseUrl: input.baseUrl,
|
||||
requestUrl,
|
||||
timeoutMs,
|
||||
intervalMs,
|
||||
probeTimeoutMs,
|
||||
});
|
||||
|
||||
const readinessClient = client.pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transform((effect) =>
|
||||
Effect.gen(function* () {
|
||||
attempt += 1;
|
||||
const responseOption = yield* effect.pipe(
|
||||
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
|
||||
Effect.mapError((cause) => fail(cause)),
|
||||
);
|
||||
return yield* Option.match(responseOption, {
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
fail({
|
||||
kind: "probe-timeout",
|
||||
attempt,
|
||||
probeTimeoutMs,
|
||||
}),
|
||||
),
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) => (isMadeError(cause) ? cause : fail(cause))),
|
||||
Effect.tapError((cause) =>
|
||||
Ref.set(lastProbeFailure, {
|
||||
attempt,
|
||||
cause: describeReadinessCause(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
HttpClient.tap((response) => response.text.pipe(Effect.ignore)),
|
||||
HttpClient.retry(retryPolicy),
|
||||
);
|
||||
|
||||
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
|
||||
Effect.mapError((cause) => (isMadeError(cause) ? cause : fail(cause))),
|
||||
Effect.timeoutOption(Duration.millis(timeoutMs)),
|
||||
);
|
||||
|
||||
return yield* Option.match(result, {
|
||||
onSome: () =>
|
||||
Effect.logDebug("httpReadiness.succeeded", {
|
||||
baseUrl: input.baseUrl,
|
||||
requestUrl,
|
||||
attempts: attempt,
|
||||
}),
|
||||
onNone: () =>
|
||||
Effect.gen(function* () {
|
||||
const lastFailure = yield* Ref.get(lastProbeFailure);
|
||||
yield* Effect.logWarning("httpReadiness.timedOut", {
|
||||
baseUrl: input.baseUrl,
|
||||
requestUrl,
|
||||
timeoutMs,
|
||||
intervalMs,
|
||||
probeTimeoutMs,
|
||||
attempts: attempt,
|
||||
lastFailure,
|
||||
});
|
||||
return yield* Effect.fail(
|
||||
fail({
|
||||
kind: "overall-timeout",
|
||||
baseUrl: input.baseUrl,
|
||||
timeoutMs,
|
||||
lastFailure,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
});
|
||||
});
|
||||
+40
-138
@@ -2,24 +2,24 @@ import type {
|
||||
DesktopSshEnvironmentBootstrap,
|
||||
DesktopSshEnvironmentTarget,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
describeReadinessCause,
|
||||
waitForHttpReady as waitForHttpReadyShared,
|
||||
} from "@t3tools/shared/httpReadiness";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import { extractJsonObject, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { satisfiesSemverRange } from "@t3tools/shared/semver";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
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 Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
import { HttpClient } from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import {
|
||||
@@ -232,33 +232,9 @@ function applyScriptPlaceholders(
|
||||
return result;
|
||||
}
|
||||
|
||||
export function describeReadinessCause(cause: unknown): unknown {
|
||||
if (cause instanceof SshReadinessError) {
|
||||
return {
|
||||
_tag: cause._tag,
|
||||
message: cause.message,
|
||||
...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
|
||||
};
|
||||
}
|
||||
if (cause instanceof Error) {
|
||||
return {
|
||||
name: cause.name,
|
||||
message: cause.message,
|
||||
...(cause.cause === undefined ? {} : { cause: describeReadinessCause(cause.cause) }),
|
||||
};
|
||||
}
|
||||
if (typeof cause !== "object" || cause === null) {
|
||||
return cause;
|
||||
}
|
||||
|
||||
const record = cause as Readonly<Record<string, unknown>>;
|
||||
return {
|
||||
...(typeof record._tag === "string" ? { _tag: record._tag } : {}),
|
||||
...(typeof record.message === "string" ? { message: record.message } : {}),
|
||||
...(record.reason === undefined ? {} : { reason: describeReadinessCause(record.reason) }),
|
||||
...(record.cause === undefined ? {} : { cause: describeReadinessCause(record.cause) }),
|
||||
};
|
||||
}
|
||||
// Re-exported from the shared HTTP readiness module so existing importers
|
||||
// (notably tunnel.test.ts) keep resolving it from here.
|
||||
export { describeReadinessCause };
|
||||
|
||||
export const REMOTE_PICK_PORT_SCRIPT = `const fs = require("node:fs");
|
||||
const net = require("node:net");
|
||||
@@ -865,120 +841,46 @@ const readRemoteServerLogTail = Effect.fn("ssh/tunnel.readRemoteServerLogTail")(
|
||||
return result.stdout.trim();
|
||||
});
|
||||
|
||||
export const waitForHttpReady = Effect.fn("ssh/tunnel.waitForHttpReady")(function* (input: {
|
||||
export const waitForHttpReady = (input: {
|
||||
readonly baseUrl: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly intervalMs?: number;
|
||||
readonly probeTimeoutMs?: number;
|
||||
readonly path?: string;
|
||||
}): Effect.fn.Return<void, SshReadinessError, HttpClient.HttpClient> {
|
||||
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();
|
||||
const client = yield* HttpClient.HttpClient;
|
||||
const lastProbeFailure = yield* Ref.make<unknown>(null);
|
||||
let attempt = 0;
|
||||
|
||||
yield* Effect.logDebug("ssh.tunnel.httpReady.start", {
|
||||
}): Effect.Effect<void, SshReadinessError, HttpClient.HttpClient> =>
|
||||
waitForHttpReadyShared({
|
||||
baseUrl: input.baseUrl,
|
||||
requestUrl,
|
||||
timeoutMs,
|
||||
intervalMs,
|
||||
probeTimeoutMs,
|
||||
});
|
||||
|
||||
const readinessClient = client.pipe(
|
||||
HttpClient.filterStatusOk,
|
||||
HttpClient.transform((effect) =>
|
||||
Effect.gen(function* () {
|
||||
attempt += 1;
|
||||
const responseOption = yield* effect.pipe(
|
||||
Effect.timeoutOption(Duration.millis(probeTimeoutMs)),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return yield* Option.match(responseOption, {
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new SshReadinessError({
|
||||
message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
|
||||
cause: {
|
||||
kind: "probe-timeout",
|
||||
attempt,
|
||||
probeTimeoutMs,
|
||||
},
|
||||
}),
|
||||
),
|
||||
});
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SshReadinessError
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.tapError((cause) =>
|
||||
Ref.set(lastProbeFailure, {
|
||||
attempt,
|
||||
cause: describeReadinessCause(cause),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
HttpClient.tap((response) => response.text.pipe(Effect.ignore)),
|
||||
HttpClient.retry(retryPolicy),
|
||||
);
|
||||
|
||||
const result = yield* readinessClient.execute(HttpClientRequest.get(requestUrl)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause instanceof SshReadinessError
|
||||
? cause
|
||||
: new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
...(input.path === undefined ? {} : { path: input.path }),
|
||||
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
|
||||
...(input.intervalMs === undefined ? {} : { intervalMs: input.intervalMs }),
|
||||
probeTimeoutMs: input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS,
|
||||
makeError: ({ requestUrl, probeTimeoutMs, cause }) => {
|
||||
if (typeof cause === "object" && cause !== null && "kind" in cause) {
|
||||
const kind = (cause as { readonly kind?: unknown }).kind;
|
||||
if (kind === "probe-timeout") {
|
||||
return new SshReadinessError({
|
||||
message: `Backend readiness probe exceeded ${probeTimeoutMs}ms at ${requestUrl}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(Duration.millis(timeoutMs)),
|
||||
);
|
||||
|
||||
return yield* Option.match(result, {
|
||||
onSome: () =>
|
||||
Effect.logDebug("ssh.tunnel.httpReady.succeeded", {
|
||||
baseUrl: input.baseUrl,
|
||||
requestUrl,
|
||||
attempts: attempt,
|
||||
}),
|
||||
onNone: () =>
|
||||
Effect.gen(function* () {
|
||||
const lastFailure = yield* Ref.get(lastProbeFailure);
|
||||
yield* Effect.logWarning("ssh.tunnel.httpReady.timedOut", {
|
||||
baseUrl: input.baseUrl,
|
||||
requestUrl,
|
||||
timeoutMs,
|
||||
intervalMs,
|
||||
probeTimeoutMs,
|
||||
attempts: attempt,
|
||||
lastFailure,
|
||||
});
|
||||
return yield* new SshReadinessError({
|
||||
message: `Timed out waiting ${timeoutMs}ms for backend readiness at ${input.baseUrl}.`,
|
||||
cause: lastFailure,
|
||||
});
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (kind === "overall-timeout") {
|
||||
const overall = cause as unknown as {
|
||||
readonly baseUrl: string;
|
||||
readonly timeoutMs: number;
|
||||
readonly lastFailure: unknown;
|
||||
};
|
||||
return new SshReadinessError({
|
||||
message: `Timed out waiting ${overall.timeoutMs}ms for backend readiness at ${overall.baseUrl}.`,
|
||||
cause: overall.lastFailure,
|
||||
});
|
||||
}
|
||||
}
|
||||
return new SshReadinessError({
|
||||
message: `Backend readiness probe failed at ${requestUrl}.`,
|
||||
cause,
|
||||
});
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
function isLoopbackHostname(hostname: string): boolean {
|
||||
const normalized = hostname
|
||||
|
||||
Reference in new issue
Block a user