fix: clean up the remote server update reconnect flow
Clicking "Update server" on a relay-connected server showed a spinner, then a disconnected banner with a raw transport error, then hung until the page was refreshed. Three separate causes: 1. The boot-service (systemd) update path ran `systemctl --user restart` synchronously inside the RPC handler, so the process died before the acknowledgement flushed. Every successful update reached the client as an interrupt, which ServerUpdateAction released quietly — no success toast, and nothing told the connection layer a restart was coming. The restart is now deferred like the respawn path. Rollback and the in-flight reset move onto the detached fiber and log instead of failing the (already-acknowledged) RPC. 2. Reconnect backoff escalates to 16s, so the client was frequently asleep exactly when the server came back; refreshing reset the failure count, which is why refreshing "fixed" it. A restart-expected overlay is now armed before dispatch and retries on a flat 2s cadence while it is active, and only while the supervisor is sleeping in backoff so a live attempt is never interrupted. It expires on its own after 90s and is withdrawn on an explicit RPC failure, which proves the server stayed up. 3. Two consecutive websocket-ticket failures evicted the cached DPoP token, forcing a full relay bootstrap and token exchange during reconnect. Eviction is now limited to failures suggesting a stale endpoint; plain unreachability (network/timeout) — the shape of a restart — keeps the token. Also stops piping raw transport messages (which embed internal endpoint URLs) into the composer banner: presentation maps each failure reason to a stable summary and carries the reason for callers, while the raw message remains on the supervisor state for diagnostics. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
202e5609ff
commit
b462ae5f2f
13 files changed
+414
-55
No files matched your search
@@ -771,7 +771,9 @@ export function ReviewSheet(props: ReviewSheetProps) {
|
||||
environment.presentation?.connection ?? {
|
||||
phase: "available",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
}
|
||||
}
|
||||
resourceName="review"
|
||||
|
||||
@@ -1209,7 +1209,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
environment.presentation?.connection ?? {
|
||||
phase: "available",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
}
|
||||
}
|
||||
resourceName="terminal"
|
||||
|
||||
@@ -40,7 +40,9 @@ function environment(
|
||||
connection: {
|
||||
phase,
|
||||
error: phase === "error" ? "Connection failed." : null,
|
||||
reason: phase === "error" ? "authentication" : null,
|
||||
traceId: phase === "error" ? "trace-1" : null,
|
||||
retryAt: null,
|
||||
},
|
||||
serverConfig: null,
|
||||
};
|
||||
|
||||
@@ -26,6 +26,30 @@ import * as SelfUpdate from "./selfUpdate.ts";
|
||||
|
||||
const NODE_PATH = "/usr/local/bin/node";
|
||||
|
||||
/**
|
||||
* The deferred restart runs on a detached fiber, so its rollback performs
|
||||
* real filesystem I/O that advancing the TestClock does not await. Poll on
|
||||
* real time until the expected content lands.
|
||||
*/
|
||||
const eventuallyFileString = Effect.fn("test.eventuallyFileString")(function* (
|
||||
filePath: string,
|
||||
expected: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
let last = "";
|
||||
for (let iteration = 0; iteration < 1_000; iteration += 1) {
|
||||
last = yield* fs.readFileString(filePath);
|
||||
if (last === expected) {
|
||||
return last;
|
||||
}
|
||||
// Yielding (rather than sleeping) keeps this on the real event loop:
|
||||
// TestClock would only advance virtual time and never let the
|
||||
// detached fiber's filesystem writes land.
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
return yield* Effect.die(new Error(`Expected file contents were not observed at ${filePath}.`));
|
||||
});
|
||||
|
||||
interface RecordedCommand {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
@@ -490,7 +514,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("rewrites the systemd unit and restarts the boot service", () =>
|
||||
it.effect("rewrites the systemd unit and defers the boot-service restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* makeContext({ bootService: true });
|
||||
const result = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
@@ -504,12 +528,15 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
context.path.join(context.home, ".config", "systemd", "user", "t3code.service"),
|
||||
);
|
||||
assert.include(unit, `ExecStart=${NODE_PATH} ${pinnedEntry} serve`);
|
||||
// The restart is deferred so the RPC acknowledgement flushes before
|
||||
// systemd stops this process.
|
||||
assert.deepEqual(
|
||||
context.commands.map((entry) => entry.command),
|
||||
["npm", NODE_PATH, "systemctl", "systemctl"],
|
||||
["npm", NODE_PATH, "systemctl"],
|
||||
);
|
||||
assert.deepEqual(context.commands[2]?.args, ["--user", "daemon-reload"]);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
assert.deepEqual(context.commands[3], {
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", "t3code.service"],
|
||||
@@ -520,7 +547,7 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("restores the previous unit and permits a retry when systemd restart fails", () =>
|
||||
it.effect("restores the previous unit and permits a retry when the deferred restart fails", () =>
|
||||
Effect.gen(function* () {
|
||||
let failRestart = true;
|
||||
const context = yield* makeContext({
|
||||
@@ -542,9 +569,12 @@ it.layer(NodeServices.layer)("ServerSelfUpdate.update", (it) => {
|
||||
);
|
||||
const previousUnit = yield* context.fs.readFileString(unitPath);
|
||||
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" }).pipe(Effect.flip);
|
||||
assert.include(first.reason, "Restarting the systemd boot service failed");
|
||||
assert.equal(yield* context.fs.readFileString(unitPath), previousUnit);
|
||||
// The RPC acknowledges before the restart runs, so a rejected
|
||||
// restart can only roll back and log — never fail the request.
|
||||
const first = yield* context.service.update({ targetVersion: "0.0.29" });
|
||||
assert.deepEqual(first, { targetVersion: "0.0.29", method: "boot-service" });
|
||||
yield* TestClock.adjust(Duration.seconds(10));
|
||||
yield* eventuallyFileString(unitPath, previousUnit);
|
||||
assert.deepEqual(
|
||||
context.commands.slice(-2).map((entry) => entry.args),
|
||||
[
|
||||
|
||||
@@ -349,37 +349,46 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* (option
|
||||
yield* Effect.logInfo("Server self-update installed; restarting boot service.", {
|
||||
targetVersion,
|
||||
});
|
||||
// A successful systemd restart stops this process, so the RPC is
|
||||
// interrupted and the reconnecting client observes the new version.
|
||||
// A rejected restart returns while the old process is still alive;
|
||||
// restore the previous unit and report that failure through the RPC.
|
||||
yield* Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
// Deferred like the respawn path: a synchronous systemctl restart
|
||||
// stops this process mid-RPC, so every successful update used to
|
||||
// surface to the client as an interrupted call indistinguishable
|
||||
// from a dropped connection. Deferring lets the acknowledgement
|
||||
// flush first. The trade: a rejected restart can no longer be
|
||||
// reported through this RPC — it rolls back, logs, and clears the
|
||||
// in-flight guard so a retry works.
|
||||
yield* scheduleRestart(
|
||||
Effect.gen(function* () {
|
||||
const restart = yield* runner
|
||||
.run({
|
||||
command: "systemctl",
|
||||
args: ["--user", "restart", BOOT_SERVICE_UNIT_FILE],
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
failWith("Could not restart the systemd boot service.", cause),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
Effect.logError(
|
||||
"Server self-update restart was rejected; restoring the previous systemd unit.",
|
||||
).pipe(
|
||||
Effect.annotateLogs({ targetVersion, error: restartError.reason }),
|
||||
Effect.andThen(
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(Effect.andThen(reloadSystemd())),
|
||||
),
|
||||
Effect.catch((rollbackError) =>
|
||||
Effect.logError(
|
||||
"Server self-update could not restore the previous systemd unit after a rejected restart.",
|
||||
).pipe(Effect.annotateLogs({ targetVersion, error: String(rollbackError) })),
|
||||
),
|
||||
Effect.ensuring(Ref.set(inFlight, false)),
|
||||
),
|
||||
);
|
||||
if (restart.code !== 0) {
|
||||
return yield* failWith(
|
||||
`Restarting the systemd boot service failed (exit code ${String(restart.code)}).`,
|
||||
);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.catch((restartError) =>
|
||||
writeUnitAtomically(unitPath, previousUnit).pipe(
|
||||
Effect.andThen(reloadSystemd()),
|
||||
Effect.mapError((rollbackError) =>
|
||||
failWith("Could not restore the previous systemd unit.", {
|
||||
restartError,
|
||||
rollbackError,
|
||||
}),
|
||||
),
|
||||
Effect.andThen(Effect.fail(restartError)),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
connectionStatusTitle,
|
||||
type EnvironmentConnectionPresentation,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { clearExpectedServerRestart, useServerRestartExpected } from "~/serverRestartStore";
|
||||
import { effectiveSettled, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import {
|
||||
parseScopedThreadKey,
|
||||
@@ -275,6 +276,7 @@ import { RightPanelSheet } from "./RightPanelSheet";
|
||||
import { previewEnvironment } from "../state/preview";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { Button } from "./ui/button";
|
||||
import { Spinner } from "./ui/spinner";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogClose,
|
||||
@@ -1619,6 +1621,37 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
connection: activeEnvironment.connection,
|
||||
};
|
||||
}, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]);
|
||||
// While a server self-update restart is expected, disconnects are routine:
|
||||
// present them calmly and retry fast instead of letting exponential
|
||||
// backoff strand the client asleep when the server comes back.
|
||||
const activeEnvironmentId = activeEnvironment?.environmentId ?? null;
|
||||
const activeEnvironmentRestartExpected = useServerRestartExpected(activeEnvironmentId);
|
||||
const activeEnvironmentRestarting =
|
||||
activeEnvironmentRestartExpected && activeEnvironmentUnavailable;
|
||||
useEffect(() => {
|
||||
if (activeEnvironmentId === null || !activeEnvironmentRestartExpected) {
|
||||
return;
|
||||
}
|
||||
if (activeEnvironmentConnectionPhase === "connected") {
|
||||
clearExpectedServerRestart(activeEnvironmentId);
|
||||
return;
|
||||
}
|
||||
// Only wake the supervisor out of a backoff sleep; while an attempt is
|
||||
// live, retryNow would interrupt and restart it.
|
||||
if (activeEnvironment?.connection.retryAt == null) {
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
void retryEnvironment(activeEnvironmentId);
|
||||
}, 2_000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [
|
||||
activeEnvironment?.connection.retryAt,
|
||||
activeEnvironmentConnectionPhase,
|
||||
activeEnvironmentId,
|
||||
activeEnvironmentRestartExpected,
|
||||
retryEnvironment,
|
||||
]);
|
||||
const handleReconnectActiveEnvironment = useCallback(
|
||||
async (environmentId: EnvironmentId) => {
|
||||
const result = await retryEnvironment(environmentId);
|
||||
@@ -1832,7 +1865,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
|
||||
const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
|
||||
const items: ComposerBannerStackItem[] = [];
|
||||
if (activeEnvironmentUnavailableState) {
|
||||
if (activeEnvironmentUnavailableState && activeEnvironmentRestarting) {
|
||||
// An expected self-update restart: the disconnect and the transient
|
||||
// connection errors behind it are routine, so keep the tone neutral
|
||||
// and let the fast auto-retry loop do the work instead of asking the
|
||||
// user to reconnect by hand.
|
||||
items.push({
|
||||
id: `environment-restarting:${activeEnvironmentUnavailableState.environmentId}`,
|
||||
variant: "info",
|
||||
icon: <Spinner className="size-4" />,
|
||||
title: `${activeEnvironmentUnavailableState.label} is restarting`,
|
||||
description: "Finishing the server update — reconnecting automatically.",
|
||||
});
|
||||
} else if (activeEnvironmentUnavailableState) {
|
||||
const connection = activeEnvironmentUnavailableState.connection;
|
||||
const isReconnecting =
|
||||
connection.phase === "connecting" || connection.phase === "reconnecting";
|
||||
@@ -1872,7 +1917,10 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
showVersionMismatchBanner &&
|
||||
versionMismatch &&
|
||||
versionMismatchDismissKey &&
|
||||
versionMismatchEnvironmentId
|
||||
versionMismatchEnvironmentId &&
|
||||
// The mismatch data predates the disconnect; during an expected
|
||||
// restart it is stale and its update action would double-trigger.
|
||||
!activeEnvironmentRestarting
|
||||
) {
|
||||
items.push({
|
||||
id: `version-mismatch:${versionMismatchDismissKey}`,
|
||||
@@ -1906,6 +1954,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return items;
|
||||
}, [
|
||||
activeEnvironmentRestarting,
|
||||
activeEnvironmentUnavailableState,
|
||||
handleReconnectActiveEnvironment,
|
||||
navigate,
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { clearExpectedServerRestart, expectServerRestart } from "~/serverRestartStore";
|
||||
import { serverEnvironment } from "~/state/server";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { manualServerUpdateCommand } from "~/versionSkew";
|
||||
@@ -116,6 +117,13 @@ export function ServerUpdateAction({
|
||||
expiry = armExpiry();
|
||||
}
|
||||
};
|
||||
// Armed before dispatch: the boot-service path acknowledges and then
|
||||
// drops every connection, and even the respawn acknowledgement can lose
|
||||
// the race against the disconnect. An explicit RPC failure proves the
|
||||
// server stayed alive, so the expectation is withdrawn there; on
|
||||
// success or interrupt it stays armed and expires on its own if the
|
||||
// server never returns.
|
||||
expectServerRestart(environmentId);
|
||||
void Promise.resolve()
|
||||
.then(() =>
|
||||
updateServer({
|
||||
@@ -133,6 +141,7 @@ export function ServerUpdateAction({
|
||||
if (isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
clearExpectedServerRestart(environmentId);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
@@ -152,6 +161,7 @@ export function ServerUpdateAction({
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (!ownsAttempt()) return;
|
||||
clearExpectedServerRestart(environmentId);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Server update failed",
|
||||
|
||||
@@ -7,7 +7,7 @@ function connection(
|
||||
phase: EnvironmentConnectionPresentation["phase"],
|
||||
error: string | null = null,
|
||||
): EnvironmentConnectionPresentation {
|
||||
return { phase, error, traceId: null };
|
||||
return { phase, error, reason: null, traceId: null, retryAt: null };
|
||||
}
|
||||
|
||||
describe("saved cloud environment connection presentation", () => {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Environment-scoped "a server restart is expected" overlay.
|
||||
*
|
||||
* Set around a server self-update so the connection UI can tell an
|
||||
* intentional restart apart from a genuine outage: while the window is
|
||||
* active, disconnects present as a calm "restarting" notice and the client
|
||||
* retries on a fast flat cadence instead of escalating backoff. This is
|
||||
* deliberately not a connection-supervisor phase — the supervisor state
|
||||
* machine stays transport-only, and this store is UI-side intent that
|
||||
* expires on its own if the server never comes back.
|
||||
*/
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useEffect, useReducer } from "react";
|
||||
import { create } from "zustand";
|
||||
|
||||
/**
|
||||
* How long after the last update signal (dispatch, RPC acknowledgement, or
|
||||
* interrupted RPC) a disconnect is still attributed to the restart. Covers
|
||||
* the respawn shim (~3s), boot-service systemd swap, server boot, and relay
|
||||
* re-registration with generous margin; after it lapses the normal error
|
||||
* presentation returns.
|
||||
*/
|
||||
export const SERVER_RESTART_EXPECTED_WINDOW_MS = 90_000;
|
||||
|
||||
interface ServerRestartState {
|
||||
readonly expectedUntilByEnvironmentId: Readonly<Record<string, number>>;
|
||||
readonly expect: (environmentId: EnvironmentId) => void;
|
||||
readonly clear: (environmentId: EnvironmentId) => void;
|
||||
}
|
||||
|
||||
export const useServerRestartStore = create<ServerRestartState>()((set) => ({
|
||||
expectedUntilByEnvironmentId: {},
|
||||
expect: (environmentId) =>
|
||||
set((state) => ({
|
||||
expectedUntilByEnvironmentId: {
|
||||
...state.expectedUntilByEnvironmentId,
|
||||
[environmentId]: Date.now() + SERVER_RESTART_EXPECTED_WINDOW_MS,
|
||||
},
|
||||
})),
|
||||
clear: (environmentId) =>
|
||||
set((state) => {
|
||||
if (!(environmentId in state.expectedUntilByEnvironmentId)) {
|
||||
return state;
|
||||
}
|
||||
const next = { ...state.expectedUntilByEnvironmentId };
|
||||
delete next[environmentId];
|
||||
return { expectedUntilByEnvironmentId: next };
|
||||
}),
|
||||
}));
|
||||
|
||||
export function expectServerRestart(environmentId: EnvironmentId): void {
|
||||
useServerRestartStore.getState().expect(environmentId);
|
||||
}
|
||||
|
||||
export function clearExpectedServerRestart(environmentId: EnvironmentId): void {
|
||||
useServerRestartStore.getState().clear(environmentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a restart window is currently active for the environment.
|
||||
* Re-renders when the window is set, cleared, or lapses.
|
||||
*/
|
||||
export function useServerRestartExpected(environmentId: EnvironmentId | null): boolean {
|
||||
const expiresAt = useServerRestartStore((state) =>
|
||||
environmentId === null ? null : (state.expectedUntilByEnvironmentId[environmentId] ?? null),
|
||||
);
|
||||
const [, tick] = useReducer((count: number) => count + 1, 0);
|
||||
useEffect(() => {
|
||||
if (expiresAt === null) {
|
||||
return;
|
||||
}
|
||||
const remaining = expiresAt - Date.now();
|
||||
if (remaining <= 0) {
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(tick, remaining + 50);
|
||||
return () => clearTimeout(timer);
|
||||
}, [expiresAt]);
|
||||
return expiresAt !== null && expiresAt > Date.now();
|
||||
}
|
||||
@@ -316,6 +316,42 @@ describe("RemoteEnvironmentAuthorization", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a cached token when the endpoint is merely unreachable", () =>
|
||||
Effect.gen(function* () {
|
||||
const cached = new TokenStore.RemoteDpopAccessToken({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: DESCRIPTOR.label,
|
||||
endpoint: ENDPOINT,
|
||||
accessToken: "cached-access-token",
|
||||
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
|
||||
dpopThumbprint: "thumbprint-1",
|
||||
});
|
||||
// A restarting server refuses connections outright rather than
|
||||
// answering; re-bootstrapping would not produce a better endpoint, so
|
||||
// the token must survive to keep reconnects to a single request.
|
||||
const harness = yield* makeHarness({
|
||||
initialToken: cached,
|
||||
responses: [],
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const failure = yield* remote
|
||||
.authorizeDpop({
|
||||
expectedEnvironmentId: ENVIRONMENT_ID,
|
||||
obtainBootstrap: harness.obtainBootstrap,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
expect(failure._tag).toBe("ConnectionTransientError");
|
||||
}
|
||||
}).pipe(Effect.provide(harness.layer));
|
||||
|
||||
expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toBe(cached);
|
||||
expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not persist a refreshed token until its websocket ticket succeeds", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
|
||||
@@ -60,6 +60,24 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
|
||||
const TOKEN_EXPIRY_SAFETY_MARGIN_MS = 60_000;
|
||||
const CACHED_ENDPOINT_FAILURE_THRESHOLD = 2;
|
||||
|
||||
/**
|
||||
* Transient reasons that suggest the *cached endpoint itself* is stale —
|
||||
* something answered and rejected or could not route the request — so
|
||||
* re-bootstrapping may hand back a different endpoint.
|
||||
*
|
||||
* `network` and `timeout` are excluded on purpose: they only prove the
|
||||
* endpoint was unreachable right now, which is the normal shape of a server
|
||||
* restart or a brief outage. Evicting on those threw away a perfectly good
|
||||
* token and forced a full relay bootstrap + token exchange on every
|
||||
* reconnect, adding latency exactly when the server was coming back.
|
||||
*/
|
||||
const CACHED_ENDPOINT_STALE_REASONS: ReadonlySet<string> = new Set([
|
||||
"endpoint-unavailable",
|
||||
"remote-unavailable",
|
||||
"relay-unavailable",
|
||||
"transport",
|
||||
]);
|
||||
|
||||
function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) {
|
||||
return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError"
|
||||
? error
|
||||
@@ -215,6 +233,11 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
const mappedFailure = mapDpopSocketError(cachedSocket.failure);
|
||||
if (mappedFailure._tag === "ConnectionTransientError") {
|
||||
if (!CACHED_ENDPOINT_STALE_REASONS.has(mappedFailure.reason)) {
|
||||
// Pure unreachability: keep the cached token so the next attempt
|
||||
// is a single ticket request rather than a full re-bootstrap.
|
||||
return yield* mappedFailure;
|
||||
}
|
||||
const failureCount = yield* recordCachedEndpointFailure(input.expectedEnvironmentId);
|
||||
if (failureCount < CACHED_ENDPOINT_FAILURE_THRESHOLD) {
|
||||
return yield* mappedFailure;
|
||||
|
||||
@@ -5,6 +5,7 @@ import * as Option from "effect/Option";
|
||||
import { BearerConnectionProfile, type ConnectionCatalogEntry } from "./catalog.ts";
|
||||
import {
|
||||
BearerConnectionTarget,
|
||||
ConnectionBlockedError,
|
||||
ConnectionTransientError,
|
||||
type SupervisorConnectionState,
|
||||
} from "./model.ts";
|
||||
@@ -59,7 +60,9 @@ describe("connection presentation", () => {
|
||||
expect(presentConnectionState(supervisorState({ phase: "connecting", attempt: 1 }))).toEqual({
|
||||
phase: "connecting",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
});
|
||||
expect(
|
||||
presentConnectionState(
|
||||
@@ -75,8 +78,10 @@ describe("connection presentation", () => {
|
||||
),
|
||||
).toEqual({
|
||||
phase: "reconnecting",
|
||||
error: "Socket closed.",
|
||||
error: "The connection to the environment was interrupted.",
|
||||
reason: "transport",
|
||||
traceId: "trace-previous",
|
||||
retryAt: null,
|
||||
});
|
||||
expect(
|
||||
presentConnectionState(
|
||||
@@ -93,8 +98,48 @@ describe("connection presentation", () => {
|
||||
),
|
||||
).toEqual({
|
||||
phase: "reconnecting",
|
||||
error: "Disconnected.",
|
||||
error: "The connection to the environment was interrupted.",
|
||||
reason: "transport",
|
||||
traceId: "trace-1",
|
||||
retryAt: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("summarizes transport failures without exposing endpoint internals", () => {
|
||||
const presented = presentConnectionState(
|
||||
supervisorState({
|
||||
phase: "backoff",
|
||||
attempt: 2,
|
||||
retryAt: 5,
|
||||
lastFailure: new ConnectionTransientError({
|
||||
reason: "network",
|
||||
detail:
|
||||
"Failed to fetch remote environment endpoint https://prod-6e7fc14fddd8f0fb.t3coderelay.com/api/auth/websocket-ticket (HttpClientError: Transport error).",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(presented.error).toBe("The environment could not be reached.");
|
||||
expect(presented.error).not.toContain("t3coderelay.com");
|
||||
expect(presented.reason).toBe("network");
|
||||
});
|
||||
|
||||
it("keeps authored blocked-failure messages, which are already actionable", () => {
|
||||
expect(
|
||||
presentConnectionState(
|
||||
supervisorState({
|
||||
phase: "blocked",
|
||||
lastFailure: new ConnectionBlockedError({
|
||||
reason: "authentication",
|
||||
detail: "The environment credential is invalid.",
|
||||
}),
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
phase: "error",
|
||||
error: "The environment credential is invalid.",
|
||||
reason: "authentication",
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -106,7 +151,7 @@ describe("connection presentation", () => {
|
||||
stage: "opening",
|
||||
attempt: 2,
|
||||
lastFailure: new ConnectionTransientError({
|
||||
reason: "transport",
|
||||
reason: "timeout",
|
||||
detail: "Relay connection timed out.",
|
||||
traceId: "trace-retry",
|
||||
}),
|
||||
@@ -114,8 +159,10 @@ describe("connection presentation", () => {
|
||||
),
|
||||
).toEqual({
|
||||
phase: "reconnecting",
|
||||
error: "Relay connection timed out.",
|
||||
error: "The environment did not respond in time.",
|
||||
reason: "timeout",
|
||||
traceId: "trace-retry",
|
||||
retryAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -127,7 +174,9 @@ describe("connection presentation", () => {
|
||||
const connection = {
|
||||
phase: "reconnecting",
|
||||
error: "Relay request timed out.",
|
||||
reason: "timeout",
|
||||
traceId: "trace-retry",
|
||||
retryAt: null,
|
||||
} as const;
|
||||
expect(connectionStatusText(connection)).toBe(
|
||||
"Failed to connect. Reconnecting... Reason: Relay request timed out.",
|
||||
@@ -147,7 +196,9 @@ describe("connection presentation", () => {
|
||||
).toEqual({
|
||||
phase: "offline",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -163,7 +214,9 @@ describe("connection presentation", () => {
|
||||
).toEqual({
|
||||
phase: "connected",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -181,7 +234,9 @@ describe("connection presentation", () => {
|
||||
).toEqual({
|
||||
phase: "available",
|
||||
error: null,
|
||||
reason: null,
|
||||
traceId: null,
|
||||
retryAt: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import type { ServerConfig } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type { ConnectionCatalogEntry } from "./catalog.ts";
|
||||
import type { NetworkStatus, SupervisorConnectionState } from "./model.ts";
|
||||
import type { ConnectionAttemptError, NetworkStatus, SupervisorConnectionState } from "./model.ts";
|
||||
|
||||
export type EnvironmentConnectionPhase =
|
||||
| "available"
|
||||
@@ -12,10 +12,18 @@ export type EnvironmentConnectionPhase =
|
||||
| "connected"
|
||||
| "error";
|
||||
|
||||
export type EnvironmentConnectionFailureReason = ConnectionAttemptError["reason"];
|
||||
|
||||
export interface EnvironmentConnectionPresentation {
|
||||
readonly phase: EnvironmentConnectionPhase;
|
||||
readonly error: string | null;
|
||||
readonly reason: EnvironmentConnectionFailureReason | null;
|
||||
readonly traceId: string | null;
|
||||
/** Epoch ms of the next scheduled attempt while the supervisor sleeps in
|
||||
backoff; null while an attempt is live. Callers that want to retry
|
||||
early (retryNow) should only do so while this is set — waking an
|
||||
in-flight attempt cancels and restarts it. */
|
||||
readonly retryAt: number | null;
|
||||
}
|
||||
|
||||
export interface EnvironmentPresentation {
|
||||
@@ -24,38 +32,91 @@ export interface EnvironmentPresentation {
|
||||
readonly serverConfig: ServerConfig | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transport errors carry internal endpoint URLs and raw causes (see
|
||||
* rpc/http.ts) that belong in diagnostics, not user-facing banners. Present
|
||||
* a stable per-reason summary instead; the raw message stays available on
|
||||
* the supervisor state for connection diagnostics.
|
||||
*/
|
||||
export function connectionFailureSummary(failure: ConnectionAttemptError): string {
|
||||
switch (failure.reason) {
|
||||
case "network":
|
||||
return "The environment could not be reached.";
|
||||
case "transport":
|
||||
return "The connection to the environment was interrupted.";
|
||||
case "timeout":
|
||||
return "The environment did not respond in time.";
|
||||
case "endpoint-unavailable":
|
||||
case "remote-unavailable":
|
||||
return "The environment is not accepting connections yet.";
|
||||
case "relay-unavailable":
|
||||
return "The relay is temporarily unavailable.";
|
||||
// Blocked reasons are actionable, and their details are authored
|
||||
// messages (errors.ts) rather than raw transport dumps.
|
||||
case "authentication":
|
||||
case "permission":
|
||||
case "configuration":
|
||||
case "unsupported":
|
||||
return failure.message;
|
||||
}
|
||||
}
|
||||
|
||||
function presentFailure(failure: ConnectionAttemptError | null): {
|
||||
readonly error: string | null;
|
||||
readonly reason: EnvironmentConnectionFailureReason | null;
|
||||
readonly traceId: string | null;
|
||||
} {
|
||||
if (failure === null) {
|
||||
return { error: null, reason: null, traceId: null };
|
||||
}
|
||||
return {
|
||||
error: connectionFailureSummary(failure),
|
||||
reason: failure.reason,
|
||||
traceId: failure.traceId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function presentConnectionState(
|
||||
state: SupervisorConnectionState,
|
||||
): EnvironmentConnectionPresentation {
|
||||
switch (state.phase) {
|
||||
case "available":
|
||||
return { phase: "available", error: null, traceId: null };
|
||||
return { phase: "available", ...presentFailure(null), retryAt: null };
|
||||
case "offline":
|
||||
return { phase: "offline", error: null, traceId: null };
|
||||
return { phase: "offline", ...presentFailure(null), retryAt: null };
|
||||
case "connecting":
|
||||
return {
|
||||
phase: state.attempt <= 1 && state.lastFailure === null ? "connecting" : "reconnecting",
|
||||
error: state.lastFailure?.message ?? null,
|
||||
traceId: state.lastFailure?.traceId ?? null,
|
||||
...presentFailure(state.lastFailure),
|
||||
retryAt: null,
|
||||
};
|
||||
case "connected":
|
||||
return { phase: "connected", error: null, traceId: null };
|
||||
return { phase: "connected", ...presentFailure(null), retryAt: null };
|
||||
case "backoff":
|
||||
return {
|
||||
phase: "reconnecting",
|
||||
error: state.lastFailure?.message ?? null,
|
||||
traceId: state.lastFailure?.traceId ?? null,
|
||||
...presentFailure(state.lastFailure),
|
||||
retryAt: state.retryAt,
|
||||
};
|
||||
case "blocked":
|
||||
return {
|
||||
phase: "error",
|
||||
error: state.lastFailure?.message ?? null,
|
||||
traceId: state.lastFailure?.traceId ?? null,
|
||||
...presentFailure(state.lastFailure),
|
||||
retryAt: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function connectionStatusText(connection: EnvironmentConnectionPresentation): string {
|
||||
/** The status helpers only read phase and error, so callers holding a phase
|
||||
and a message do not have to synthesize a whole presentation. traceId is
|
||||
accepted (and ignored) because callers commonly carry it alongside. */
|
||||
export interface ConnectionStatusTextInput {
|
||||
readonly phase: EnvironmentConnectionPhase;
|
||||
readonly error: string | null;
|
||||
readonly traceId?: string | null;
|
||||
}
|
||||
|
||||
export function connectionStatusText(connection: ConnectionStatusTextInput): string {
|
||||
switch (connection.phase) {
|
||||
case "available":
|
||||
return "Available";
|
||||
@@ -76,7 +137,7 @@ export function connectionStatusText(connection: EnvironmentConnectionPresentati
|
||||
}
|
||||
}
|
||||
|
||||
export function connectionStatusTitle(connection: EnvironmentConnectionPresentation): string {
|
||||
export function connectionStatusTitle(connection: ConnectionStatusTextInput): string {
|
||||
if (connection.phase === "reconnecting" && connection.error) {
|
||||
return "Failed to connect. Reconnecting...";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user