TypeScript
fix(server): T3 Connect falls back to HTTP/2 after repeated QUIC stalls (#20382)
Лев Федорец96a76b140de5
diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.tsindex 10cf761e20a..246aca55cd7 100644--- a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts+++ b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts@@ -261,6 +261,216 @@ describe("CloudManagedEndpointRuntime", () => {}),);+ const tunnelConfig = {+ providerKind: "cloudflare_tunnel" as const,+ connectorToken: "token",+ tunnelId: "tunnel-1",+ };+ const quicDialWarning =+ '2026-10-16T20:29:43Z ERR Failed to dial a quic connection error="failed to dial to edge with quic: timeout: no recent network activity" connIndex=1\n';+ const quicDatagramWarning =+ '2026-10-16T20:29:41Z ERR Connection terminated error="datagram manager error: timeout: no recent network activity" connIndex=1\n';++ const makeTransportSpawner = Effect.fnUntraced(function* (+ options: {+ transport?: string;+ failSpawn?: number;+ isRunning?: Effect.Effect<boolean>;+ } = {},+ ) {+ yield* Effect.acquireRelease(+ Effect.sync(() => {+ const previous = process.env.TUNNEL_TRANSPORT_PROTOCOL;+ if (options.transport === undefined) delete process.env.TUNNEL_TRANSPORT_PROTOCOL;+ else process.env.TUNNEL_TRANSPORT_PROTOCOL = options.transport;+ return previous;+ }),+ (previous) =>+ Effect.sync(() => {+ if (previous === undefined) delete process.env.TUNNEL_TRANSPORT_PROTOCOL;+ else process.env.TUNNEL_TRANSPORT_PROTOCOL = previous;+ }),+ );+ const spawned: Array<ChildProcess.StandardCommand> = [];+ const killed: Array<number> = [];+ const outputs: Array<Queue.Queue<Uint8Array>> = [];+ const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];+ const started = yield* Queue.unbounded<number>();+ const spawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ if (!ChildProcess.isStandardCommand(command)) {+ return yield* Effect.die("Expected standard command.");+ }+ const index = spawned.length;+ spawned.push(command);+ if (index === options.failSpawn) {+ return yield* PlatformError.systemError({+ _tag: "NotFound",+ module: "ChildProcess",+ method: "spawn",+ description: "cloudflared temporarily unavailable",+ });+ }+ const output = yield* Queue.unbounded<Uint8Array>();+ const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();+ outputs[index] = output;+ exits[index] = exit;+ const handle = ChildProcessSpawner.makeHandle({+ ...makeHandle({+ pid: 800 + index,+ exitCode: Deferred.await(exit),+ output: Stream.fromQueue(output),+ onKill: () => {+ killed.push(800 + index);+ Deferred.doneUnsafe(exit, Exit.succeed(ChildProcessSpawner.ExitCode(143)));+ },+ }),+ isRunning: options.isRunning ?? Effect.succeed(true),+ });+ yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));+ yield* Queue.offer(started, index);+ return handle;+ }),+ );+ const emit = (index: number, lines: string) =>+ Queue.offer(outputs[index]!, new TextEncoder().encode(lines));+ const observe = (+ runtime: ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"],+ index: number,+ lines = "",+ ) =>+ emit(+ index,+ lines + "2026-10-16T20:30:00Z INF Registered tunnel connection connIndex=0\n",+ ).pipe(Effect.andThen(Stream.runHead(runtime.tunnelConnected)));+ return { spawner, spawned, killed, exits, started, emit, observe };+ });++ it.effect("falls back after 30 recent QUIC stalls across exits, until the runtime restarts", () =>+ Effect.gen(function* () {+ const fixture = yield* makeTransportSpawner();+ const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);+ yield* runtime.applyConfig(tunnelConfig);+ expect(yield* Queue.take(fixture.started)).toBe(0);+ expect(fixture.spawned[0]!.args).not.toContain("--protocol");++ yield* fixture.observe(runtime, 0, quicDialWarning.repeat(20));+ yield* TestClock.adjust(Duration.minutes(4));+ yield* fixture.observe(runtime, 0, quicDatagramWarning.repeat(9));+ yield* TestClock.adjust(Duration.minutes(1));+ // The first 20 have expired, but the newer nine must survive this restart.+ yield* Deferred.succeed(fixture.exits[0]!, ChildProcessSpawner.ExitCode(1));+ expect(yield* Queue.take(fixture.started)).toBe(1);+ yield* fixture.observe(runtime, 1, quicDialWarning.repeat(20));+ yield* fixture.observe(+ runtime,+ 1,+ '2026-10-16T20:30:00Z ERR Register tunnel error from server side error="context deadline exceeded" connIndex=0\n'.repeat(+ 30,+ ),+ );+ expect(fixture.spawned).toHaveLength(2);+ expect(fixture.spawned[1]!.args).not.toContain("--protocol");++ yield* fixture.emit(1, quicDatagramWarning);+ expect(yield* Queue.take(fixture.started)).toBe(2);+ yield* fixture.observe(runtime, 2);+ expect(fixture.killed).toEqual([800, 801]);+ expect(fixture.spawned[2]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);++ yield* TestClock.adjust(Duration.seconds(30));+ yield* Deferred.succeed(fixture.exits[2]!, ChildProcessSpawner.ExitCode(1));+ expect(yield* Queue.take(fixture.started)).toBe(3);+ yield* fixture.observe(runtime, 3);+ expect(fixture.spawned[3]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);+ yield* runtime.applyConfig(null);+ expect(fixture.killed).toEqual([800, 801, 802, 803]);++ const freshRuntime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);+ yield* freshRuntime.applyConfig(tunnelConfig);+ expect(yield* Queue.take(fixture.started)).toBe(4);+ expect(fixture.spawned[4]!.args).not.toContain("--protocol");+ }).pipe(Effect.provide(TestClock.layer())),+ );++ it.effect("preserves an explicit transport choice despite repeated QUIC stalls", () =>+ Effect.gen(function* () {+ const fixture = yield* makeTransportSpawner({ transport: "quic" });+ const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);+ yield* runtime.applyConfig(tunnelConfig);+ yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30));+ yield* fixture.observe(runtime, 0, quicDatagramWarning.repeat(30));+ expect(fixture.spawned).toHaveLength(1);+ expect(fixture.killed).toEqual([]);+ expect(fixture.spawned[0]!.args).not.toContain("--protocol");+ expect(fixture.spawned[0]!.options.env?.TUNNEL_TRANSPORT_PROTOCOL).toBe("quic");+ }),+ );++ it.effect("requests recovery after a failed HTTP/2 spawn and retries with HTTP/2", () =>+ Effect.gen(function* () {+ const fixture = yield* makeTransportSpawner({ failSpawn: 1 });+ const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);+ yield* runtime.applyConfig(tunnelConfig);+ expect(yield* Queue.take(fixture.started)).toBe(0);+ yield* fixture.emit(0, quicDialWarning.repeat(30));++ const requested = Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests));+ expect(requested).toEqual(tunnelConfig);+ expect(fixture.killed).toEqual([800]);+ expect(fixture.spawned).toHaveLength(2);+ expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);+ expect(yield* runtime.applyConfig(requested)).toMatchObject({ status: "running", pid: 802 });+ yield* fixture.observe(runtime, 2);+ expect(fixture.spawned[2]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);+ }),+ );++ it.effect("discards a pending fallback when its connector is replaced or removed", () =>+ Effect.gen(function* () {+ for (const nextConfig of [{ ...tunnelConfig, connectorToken: "replacement" }, null]) {+ yield* Effect.gen(function* () {+ const checking = yield* Deferred.make<void>();+ const releaseCheck = yield* Deferred.make<void>();+ const fixture = yield* makeTransportSpawner({+ isRunning: Deferred.succeed(checking, undefined).pipe(+ Effect.andThen(Deferred.await(releaseCheck)),+ Effect.as(true),+ ),+ });+ const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);+ yield* runtime.applyConfig(tunnelConfig);+ yield* fixture.observe(runtime, 0);++ // Hold reconciliation in a process probe so config changes queue before fallback.+ const probe = yield* runtime.applyConfig(tunnelConfig).pipe(Effect.forkChild);+ yield* Deferred.await(checking);+ const change = yield* runtime+ .applyConfig(nextConfig)+ .pipe(Effect.forkChild({ startImmediately: true }));+ yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30));+ yield* Deferred.succeed(releaseCheck, undefined);+ yield* Fiber.join(probe);+ yield* Fiber.join(change);+ yield* TestClock.adjust(Duration.zero);++ expect(fixture.killed).toEqual([800]);+ expect(fixture.spawned).toHaveLength(nextConfig ? 2 : 1);+ if (nextConfig) {+ expect(fixture.spawned[1]!.options.env?.TUNNEL_TOKEN).toBe("replacement");+ expect(fixture.spawned[1]!.args).not.toContain("--protocol");+ }+ yield* runtime.applyConfig(null);+ // Buffered output and the old exit cannot revive a removed configuration.+ yield* fixture.emit(0, quicDialWarning.repeat(30));+ yield* TestClock.adjust(Duration.minutes(5));+ expect(fixture.spawned).toHaveLength(nextConfig ? 2 : 1);+ expect(fixture.killed).toEqual(nextConfig ? [800, 801] : [800]);+ }).pipe(Effect.scoped);+ }+ }).pipe(Effect.provide(TestClock.layer())),+ );+it.effect("recovers a rejected tunnel without waiting for the connector to exit", () =>Effect.gen(function* () {const output = yield* Queue.unbounded<Uint8Array>();diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.ts b/apps/server/src/cloud/ManagedEndpointRuntime.tsindex 03fc9def012..1ec54b5e839 100644--- a/apps/server/src/cloud/ManagedEndpointRuntime.ts+++ b/apps/server/src/cloud/ManagedEndpointRuntime.ts@@ -86,6 +86,10 @@ const CONNECTOR_READINESS_REQUEST_TIMEOUT = Duration.seconds(5);const CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART = 6;const CONNECTOR_NOT_READY_CHECKS_MAX = 60;const RELAY_CLIENT_METRICS_LINE = /\bStarting metrics server on (127\.0\.0\.1:\d+)\/metrics\b/u;+// Registration resets cloudflared's own fallback, even when QUIC stalls again+// immediately. Keep that evidence across registrations and connector restarts.+const QUIC_STALLS_BEFORE_HTTP2 = 30;+const QUIC_STALL_WINDOW_MS = 5 * 60_000;// A failed background install of the pinned relay client is retried no sooner// than this, so a crash-looping connector or an offline host does not redownload// on every reconcile.@@ -178,6 +182,10 @@ export const make = Effect.gen(function* () {const prunedRef = yield* Ref.make(false);const retryLoopRunningRef = yield* Ref.make(false);const notReadyChecksBeforeRestartRef = yield* Ref.make(CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);+ // An explicit cloudflared transport in the environment is the user's choice.+ const transportChosenByUser = process.env.TUNNEL_TRANSPORT_PROTOCOL !== undefined;+ const http2Ref = yield* Ref.make(false);+ const quicStallsRef = yield* Ref.make<ReadonlyArray<number>>([]);let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];const stopActive = Effect.gen(function* () {@@ -429,6 +437,38 @@ export const make = Effect.gen(function* () {}});+ const switchToHttp2 = Effect.fnUntraced(function* (connector: ActiveConnector) {+ const active = yield* Ref.get(activeRef);+ const desiredConfig = yield* Ref.get(desiredConfigRef);+ if ((yield* Ref.get(http2Ref)) || active !== connector || !desiredConfig) return;+ yield* Ref.set(http2Ref, true);+ yield* Effect.logWarning("Relay client keeps losing QUIC connections; switching to HTTP/2", {+ pid: Number(connector.child.pid),+ tunnelId: connector.config.tunnelId,+ tunnelName: connector.config.tunnelName,+ });+ // Shutdown must not interrupt cleanup after active ownership is cleared.+ yield* Effect.uninterruptible(stopActive);+ const status = yield* reconcileConfig(desiredConfig);+ // A failed spawn has no supervisor to request recovery.+ if (status.status !== "running") {+ yield* Queue.offer(recoveryRequests, desiredConfig);+ }+ }, reconcileSemaphore.withPermits(1));++ const noteQuicStall = Effect.fnUntraced(function* (connector: ActiveConnector) {+ if (transportChosenByUser || (yield* Ref.get(http2Ref))) return;+ const now = yield* Clock.currentTimeMillis;+ if ((yield* Ref.get(activeRef)) !== connector) return;+ const stalls = yield* Ref.updateAndGet(quicStallsRef, (previous) => [+ ...previous.filter((at) => now - at < QUIC_STALL_WINDOW_MS),+ now,+ ]);+ if (stalls.length < QUIC_STALLS_BEFORE_HTTP2) return;+ // Stopping the connector interrupts the output observer that called this.+ yield* Effect.forkIn(switchToHttp2(connector), runtimeScope);+ });+const observeConnectorOutput = (connector: ActiveConnector) => {let rejectedRegistrations = 0;@@ -465,6 +505,13 @@ export const make = Effect.gen(function* () {Effect.asVoid,);case "warning":+ if (/\btimeout: no recent network activity\b/u.test(line)) {+ return noteQuicStall(connector).pipe(+ Effect.andThen(+ Effect.logWarning("Relay client reported a transport warning", attributes),+ ),+ );+ }if (isRejectedRelayClientTunnelOutput(line)) {rejectedRegistrations += 1;if (rejectedRegistrations >= TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY) {@@ -544,6 +591,7 @@ export const make = Effect.gen(function* () {} satisfies CloudManagedEndpointRuntimeStatus;}+ const http2 = yield* Ref.get(http2Ref);const connectorScope = yield* Scope.make("sequential");const child = yield* spawner.spawn(@@ -558,6 +606,7 @@ export const make = Effect.gen(function* () {"default","--metrics","127.0.0.1:0",+ ...(http2 ? ["--protocol", "http2"] : []),"run",],{@@ -579,6 +628,7 @@ export const make = Effect.gen(function* () {pid: Number(child.pid),source: executable.source,version: executable.version,+ protocol: http2 ? "http2" : "auto",tunnelId: config.tunnelId,tunnelName: config.tunnelName,}),