fix(server): back off relay client restarts after rapid exits (#8788)

This commit is contained in:
Derek Trimm authored and GitHub committed 2026-09-03 18:16:16 -07:00
1 parent 2b96220f00
commit b90898077e
2 files changed
+174 -1

No files matched your search

@@ -1,6 +1,7 @@
import { describe, expect, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
@@ -8,6 +9,7 @@ import * as Option from "effect/Option";
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 { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as RelayClient from "@t3tools/shared/relayClient";
@@ -283,6 +285,126 @@ describe("CloudManagedEndpointRuntime", () => {
}),
);
const makeCrashLoopSpawner = (basePid: number, slots: number) =>
Effect.gen(function* () {
const spawned: Array<number> = [];
const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];
const spawnSignals: Array<Deferred.Deferred<void>> = [];
for (let index = 0; index < slots; index += 1) {
exits.push(yield* Deferred.make<ChildProcessSpawner.ExitCode>());
spawnSignals.push(yield* Deferred.make<void>());
}
const spawner = ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const index = spawned.length;
spawned.push(basePid + index);
yield* Deferred.succeed(spawnSignals[index]!, undefined);
const handle = makeHandle({
pid: basePid + index,
exitCode: Deferred.await(exits[index]!),
onKill: () => {},
});
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
return handle;
}),
);
return { spawner, spawned, exits, spawnSignals };
});
it.effect("backs off restarts while the connector crash-loops", () =>
Effect.gen(function* () {
const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(600, 4);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
tunnelId: "tunnel-1",
});
expect(spawned).toEqual([600]);
// The first crash restarts immediately.
yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
yield* Deferred.await(spawnSignals[1]!);
expect(spawned).toEqual([600, 601]);
// The second rapid crash waits out the base delay before restarting.
yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
yield* TestClock.adjust(Duration.millis(999));
expect(spawned).toEqual([600, 601]);
yield* TestClock.adjust(Duration.millis(1));
yield* Deferred.await(spawnSignals[2]!);
expect(spawned).toEqual([600, 601, 602]);
// The third rapid crash doubles the delay.
yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
yield* TestClock.adjust(Duration.millis(1999));
expect(spawned).toEqual([600, 601, 602]);
yield* TestClock.adjust(Duration.millis(1));
yield* Deferred.await(spawnSignals[3]!);
expect(spawned).toEqual([600, 601, 602, 603]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("resets the backoff after the connector runs stably", () =>
Effect.gen(function* () {
const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(700, 5);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token",
});
// One rapid crash arms the backoff.
yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
yield* Deferred.await(spawnSignals[1]!);
// The replacement stays up past the stable-uptime window, so its exit
// restarts immediately and the backoff starts over.
yield* TestClock.adjust(Duration.millis(30_000));
yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
yield* Deferred.await(spawnSignals[2]!);
yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
yield* Deferred.await(spawnSignals[3]!);
// The next rapid crash waits the base delay again, not a doubled one.
yield* Deferred.succeed(exits[3]!, ChildProcessSpawner.ExitCode(1));
yield* TestClock.adjust(Duration.millis(999));
expect(spawned).toEqual([700, 701, 702, 703]);
yield* TestClock.adjust(Duration.millis(1));
yield* Deferred.await(spawnSignals[4]!);
expect(spawned).toEqual([700, 701, 702, 703, 704]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("an explicit config change clears the backoff and preempts a delayed restart", () =>
Effect.gen(function* () {
const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(800, 3);
const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-1",
});
yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
yield* Deferred.await(spawnSignals[1]!);
// Leave the supervisor sleeping on the base delay, then change config.
yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
const status = yield* runtime.applyConfig({
providerKind: "cloudflare_tunnel",
connectorToken: "token-2",
});
expect(status).toMatchObject({ status: "running", pid: 802 });
expect(spawned).toEqual([800, 801, 802]);
// The preempted supervisor wakes later and must not spawn a duplicate.
yield* TestClock.adjust(Duration.millis(60_000));
expect(spawned).toEqual([800, 801, 802]);
}).pipe(Effect.provide(TestClock.layer())),
);
it.effect("serializes concurrent connector config changes", () =>
Effect.gen(function* () {
const spawned: Array<number> = [];
@@ -1,6 +1,8 @@
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
@@ -66,8 +68,18 @@ interface ActiveConnector {
readonly scope: Scope.Closeable;
readonly configKey: string;
readonly config: RelayManagedEndpointRuntimeConfig;
readonly startedAtMillis: number;
}
// A connector that exits before running this long is treated as part of a
// crash loop; one that stays up at least this long earns an immediate restart
// again. Without the backoff below, a relay client that fails instantly (a
// stale version-manager shim, a bad binary) respawns ~100 times per second
// until the accumulated tracing exhausts the V8 heap.
const RELAY_RESTART_STABLE_UPTIME_MS = 30_000;
const RELAY_RESTART_BACKOFF_BASE_MS = 1_000;
const RELAY_RESTART_BACKOFF_MAX_MS = 60_000;
export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
if (/\bRegistered tunnel connection\b/iu.test(line)) {
return "connected";
@@ -105,6 +117,7 @@ export const make = Effect.gen(function* () {
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
const reconcileSemaphore = yield* Semaphore.make(1);
const restartDelayRef = yield* Ref.make(0);
let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
const stopActive = Effect.gen(function* () {
@@ -115,6 +128,39 @@ export const make = Effect.gen(function* () {
const superviseConnector = (connector: ActiveConnector) =>
Effect.gen(function* () {
const result = yield* Effect.result(connector.child.exitCode);
const activeAtExit = yield* Ref.get(activeRef);
if (
activeAtExit?.child.pid !== connector.child.pid ||
activeAtExit.configKey !== connector.configKey
) {
return;
}
const uptimeMillis = (yield* Clock.currentTimeMillis) - connector.startedAtMillis;
// The first crash restarts immediately; every further crash inside the
// stable-uptime window doubles the wait, up to the cap. The delay runs
// before the semaphore so a user config change is never blocked behind
// it, and reconcileConfig re-checks the desired config afterwards.
const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
return [0, 0];
}
return [
current,
current === 0
? RELAY_RESTART_BACKOFF_BASE_MS
: Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
];
});
if (restartDelayMillis > 0) {
yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
pid: Number(connector.child.pid),
uptimeMillis,
restartDelayMillis,
tunnelId: connector.config.tunnelId,
tunnelName: connector.config.tunnelName,
});
yield* Effect.sleep(Duration.millis(restartDelayMillis));
}
yield* reconcileSemaphore.withPermits(1)(
Effect.gen(function* () {
const active = yield* Ref.get(activeRef);
@@ -274,6 +320,7 @@ export const make = Effect.gen(function* () {
scope: connectorScope,
configKey: nextConfigKey,
config,
startedAtMillis: yield* Clock.currentTimeMillis,
} satisfies ActiveConnector;
yield* Ref.set(activeRef, connector);
yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
@@ -299,7 +346,11 @@ export const make = Effect.gen(function* () {
const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
(config: RelayManagedEndpointRuntimeConfig | null) =>
reconcileSemaphore.withPermits(1)(
Ref.set(desiredConfigRef, config).pipe(Effect.andThen(reconcileConfig(config))),
// An explicit config change starts over with a fresh backoff.
Ref.set(restartDelayRef, 0).pipe(
Effect.andThen(Ref.set(desiredConfigRef, config)),
Effect.andThen(reconcileConfig(config)),
),
),
);