Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ManagedEndpointRuntime.test.ts

1,145 lines44.0 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { describe, expect, it } from "@effect/vitest";
3import * as Context from "effect/Context";
4import * as Deferred from "effect/Deferred";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Fiber from "effect/Fiber";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Option from "effect/Option";
12import * as PlatformError from "effect/PlatformError";
13import * as Queue from "effect/Queue";
14import * as References from "effect/References";
15import * as Sink from "effect/Sink";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19import { HttpClient } from "effect/http";
20import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
21import * as RelayClient from "@t3tools/shared/relayClient";
22​
23import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
24import * as ServerConfig from "../config.ts";
25import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
26​
27const layerRelayClientAvailable = Layer.succeed(
28 RelayClient.RelayClient,
29 RelayClient.RelayClient.of({
30 resolve: Effect.succeed({
31 status: "available",
32 executablePath: "cloudflared",
33 source: "path",
34 version: RelayClient.CLOUDFLARED_VERSION,
35 }),
36 install: Effect.die("unused"),
37 installWithProgress: () => Effect.die("unused"),
38 pruneManagedVersions: Effect.void,
39 }),
40);
41​
42const unusedHttpClient = HttpClient.make(() => Effect.die("unused"));
43​
44const emptySecretStoreLayer = Layer.mock(ServerSecretStore.ServerSecretStore)({
45 get: () => Effect.succeedNone,
46 set: () => Effect.void,
47});
48​
49const runtimeDependencies = (
50 spawner: ReturnType<typeof ChildProcessSpawner.make>,
51 relayClientLayer = layerRelayClientAvailable,
52 httpClient = unusedHttpClient,
53 secretStoreLayer = emptySecretStoreLayer,
54) =>
55 Layer.mergeAll(
56 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
57 Layer.succeed(HttpClient.HttpClient, httpClient),
58 relayClientLayer,
59 secretStoreLayer,
60 );
61​
62const buildCloudManagedEndpointRuntime = (
63 spawner: ReturnType<typeof ChildProcessSpawner.make>,
64 relayClientLayer = layerRelayClientAvailable,
65 httpClient = unusedHttpClient,
66 secretStoreLayer = emptySecretStoreLayer,
67) =>
68 Effect.gen(function* () {
69 const context = yield* Layer.build(
70 ManagedEndpointRuntime.layer.pipe(
71 Layer.provide(runtimeDependencies(spawner, relayClientLayer, httpClient, secretStoreLayer)),
72 ),
73 );
74 return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
75 Effect.provide(context),
76 );
77 });
78​
79function makeHandle(input: {
80 readonly pid: number;
81 readonly onKill: () => void;
82 readonly isRunning?: () => boolean;
83 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
84 readonly output?: Stream.Stream<Uint8Array>;
85}) {
86 return ChildProcessSpawner.makeHandle({
87 pid: ChildProcessSpawner.ProcessId(input.pid),
88 exitCode: input.exitCode ?? Effect.never,
89 isRunning: Effect.sync(() => input.isRunning?.() ?? true),
90 kill: () =>
91 Effect.sync(() => {
92 input.onKill();
93 }),
94 unref: Effect.succeed(Effect.void),
95 stdin: Sink.drain,
96 stdout: Stream.empty,
97 stderr: Stream.empty,
98 all: input.output ?? Stream.empty,
99 getInputFd: () => Sink.drain,
100 getOutputFd: () => Stream.empty,
101 });
103​
104describe("CloudManagedEndpointRuntime", () => {
105 it.effect("serializes updates to persisted cloud link state", () =>
106 Effect.gen(function* () {
107 const firstEntered = yield* Deferred.make<void>();
108 const releaseFirst = yield* Deferred.make<void>();
109 const secondEntered = yield* Deferred.make<void>();
110 const runtime = yield* buildCloudManagedEndpointRuntime(
111 ChildProcessSpawner.make(() => Effect.die("unused")),
112 );
113​
114 const first = yield* runtime
115 .withLinkStateLock(
116 Deferred.succeed(firstEntered, undefined).pipe(
117 Effect.andThen(Deferred.await(releaseFirst)),
118 ),
119 )
120 .pipe(Effect.forkChild);
121 yield* Deferred.await(firstEntered);
122​
123 const second = yield* runtime
124 .withLinkStateLock(Deferred.succeed(secondEntered, undefined))
125 .pipe(Effect.forkChild);
126 expect(yield* Deferred.isDone(secondEntered)).toBe(false);
127​
128 yield* Deferred.succeed(releaseFirst, undefined);
129 yield* Fiber.join(first);
130 yield* Fiber.join(second);
131 expect(yield* Deferred.isDone(secondEntered)).toBe(true);
132 }),
133 );
134​
135 it("classifies Cloudflare connection and warning output", () => {
136 expect(
137 ManagedEndpointRuntime.classifyRelayClientOutput(
138 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
139 ),
140 ).toBe("connected");
141 expect(
142 ManagedEndpointRuntime.classifyRelayClientOutput(
143 "2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
144 ),
145 ).toBe("warning");
146 expect(
147 ManagedEndpointRuntime.classifyRelayClientOutput(
148 "2026-06-17T02:00:00Z INF Starting metrics server",
149 ),
150 ).toBe("debug");
151 expect(
152 ManagedEndpointRuntime.classifyRelayClientOutput(
153 "2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",
154 ),
155 ).toBe("warning");
156 expect(
157 ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),
158 ).toBe("warning");
159 });
160​
161 it("classifies connection unregistration apart from registration and routine output", () => {
162 expect(
163 ManagedEndpointRuntime.classifyRelayClientOutput(
164 "2026-10-06T00:00:00Z INF Unregistered tunnel connection connIndex=0 event=0 ip=198.41.200.23",
165 ),
166 ).toBe("unregistered");
167 for (const level of ["ERR", "WRN", "FTL", "PNC"]) {
168 expect(
169 ManagedEndpointRuntime.classifyRelayClientOutput(
170 `2026-10-06T00:00:00Z ${level} Unregistered tunnel connection connIndex=0`,
171 ),
172 ).toBe("warning");
173 }
174 for (const line of [
175 "2026-10-06T00:00:00Z INF Initiating graceful shutdown due to signal terminated ...",
176 "2026-10-06T00:00:00Z INF Starting metrics server on 127.0.0.1:20241/metrics",
177 "2026-10-06T00:00:00Z DBG Unregistered tunnel connection connIndex=0",
178 ]) {
179 expect(ManagedEndpointRuntime.classifyRelayClientOutput(line)).toBe("debug");
180 }
181 });
182​
183 it("recognizes tunnel authorization failures without matching ordinary transport errors", () => {
184 expect(
185 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
186 '2026-09-15T06:30:43Z ERR Register tunnel error from server side error="Failed to get tunnel" connIndex=0 event=0 ip=198.41.200.23',
187 ),
188 ).toBe(true);
189 expect(
190 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
191 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="Unauthorized: Record for tunnel not found" connIndex=0',
192 ),
193 ).toBe(true);
194 expect(
195 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
196 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="Unauthorized: Invalid tunnel secret" connIndex=0',
197 ),
198 ).toBe(true);
199 expect(
200 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
201 '2026-10-06T12:00:00Z ERR Register tunnel error from server side error="Unauthorized: Tunnel not found" connIndex=0 event=0 ip=198.41.200.23',
202 ),
203 ).toBe(true);
204 expect(
205 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
206 '2026-10-06T12:00:00Z ERR Register tunnel error from server side error="Tunnel not found" connIndex=0',
207 ),
208 ).toBe(true);
209 expect(
210 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
211 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="connection timed out" connIndex=0',
212 ),
213 ).toBe(false);
214 expect(
215 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
216 '2026-06-17T02:00:00Z ERR Failed to serve tunnel connection error="Unauthorized: Tunnel not found" connIndex=0',
217 ),
218 ).toBe(false);
219 });
220​
221 it.effect("keeps recovery requests sent before the server starts consuming them", () =>
222 Effect.gen(function* () {
223 const runtime = yield* buildCloudManagedEndpointRuntime(
224 ChildProcessSpawner.make(() => Effect.die("unused")),
225 );
226 const config = {
227 providerKind: "cloudflare_tunnel" as const,
228 connectorToken: "token",
229 tunnelId: "tunnel-1",
230 };
231​
232 yield* runtime.requestRecovery(config);
233​
234 expect(Option.getOrNull(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
235 }),
236 );
237​
238 it.effect("logs a connection unregistration at info with the connector token redacted", () => {
239 const logs: Array<{ readonly level: string; readonly message: unknown }> = [];
240 const unregistrationLogged = Deferred.makeUnsafe<void>();
241 const logger = Logger.make(({ logLevel, message }) => {
242 logs.push({ level: logLevel, message });
243 if (Array.isArray(message) && message[0] === "Relay client tunnel connection unregistered") {
244 Deferred.doneUnsafe(unregistrationLogged, Effect.void);
245 }
246 });
247​
248 return Effect.gen(function* () {
249 const config = {
250 providerKind: "cloudflare_tunnel" as const,
251 connectorToken: "secret-connector-token",
252 tunnelId: "tunnel-1",
253 };
254 const encoder = new TextEncoder();
255 const output = yield* Queue.unbounded<Uint8Array>();
256 const spawner = ChildProcessSpawner.make(() =>
257 Effect.gen(function* () {
258 const handle = makeHandle({
259 pid: 701,
260 onKill: () => {},
261 output: Stream.fromQueue(output),
262 });
263 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
264 return handle;
265 }),
266 );
267 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
268 yield* runtime.applyConfig(config);
269 yield* Queue.offer(
270 output,
271 encoder.encode(
272 "2026-10-06T00:00:00Z INF Unregistered tunnel connection connIndex=0 token=secret-connector-token\n",
273 ),
274 );
275 yield* Deferred.await(unregistrationLogged);
276​
277 // An unregistration is not a registration, so the registration timeout still recovers.
278 yield* TestClock.adjust(Duration.minutes(3));
279 expect(Option.getOrNull(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
280​
281 yield* Queue.offer(
282 output,
283 encoder.encode(
284 "2026-10-06T00:00:01Z INF Starting metrics server on 127.0.0.1:20241/metrics\n" +
285 "2026-10-06T00:00:01Z INF Registered tunnel connection connIndex=0\n",
286 ),
287 );
288 yield* Stream.runHead(runtime.tunnelConnected);
289​
290 const relayLogs = logs.filter(
291 ({ message }) =>
292 Array.isArray(message) && String(message[0]).startsWith("Relay client tunnel"),
293 );
294 expect(relayLogs.map(({ level, message }) => [level, (message as unknown[])[0]])).toEqual([
295 ["Info", "Relay client tunnel connection unregistered"],
296 ["Info", "Relay client tunnel connection registered"],
297 ]);
298 expect((relayLogs[0]!.message as unknown[])[1]).toMatchObject({
299 output:
300 "2026-10-06T00:00:00Z INF Unregistered tunnel connection connIndex=0 token=<redacted>",
301 });
302 const logged = JSON.stringify(logs.map(({ message }) => message));
303 expect(logged).not.toContain("secret-connector-token");
304 expect(logged).not.toContain("Starting metrics server");
305 }).pipe(
306 Effect.provide(
307 Layer.merge(
308 Logger.layer([logger], { mergeWithExisting: false }),
309 Layer.succeed(References.MinimumLogLevel, "Info"),
310 ),
311 ),
312 );
313 });
314​
315 const tunnelConfig = {
316 providerKind: "cloudflare_tunnel" as const,
317 connectorToken: "token",
318 tunnelId: "tunnel-1",
319 };
320 const quicDialWarning =
321 '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';
322 const quicDatagramWarning =
323 '2026-10-16T20:29:41Z ERR Connection terminated error="datagram manager error: timeout: no recent network activity" connIndex=1\n';
324​
325 const makeTransportSpawner = Effect.fnUntraced(function* (
326 options: {
327 transport?: string;
328 failSpawn?: number;
329 isRunning?: Effect.Effect<boolean>;
330 } = {},
331 ) {
332 yield* Effect.acquireRelease(
333 Effect.sync(() => {
334 const previous = process.env.TUNNEL_TRANSPORT_PROTOCOL;
335 if (options.transport === undefined) delete process.env.TUNNEL_TRANSPORT_PROTOCOL;
336 else process.env.TUNNEL_TRANSPORT_PROTOCOL = options.transport;
337 return previous;
338 }),
339 (previous) =>
340 Effect.sync(() => {
341 if (previous === undefined) delete process.env.TUNNEL_TRANSPORT_PROTOCOL;
342 else process.env.TUNNEL_TRANSPORT_PROTOCOL = previous;
343 }),
344 );
345 const spawned: Array<ChildProcess.StandardCommand> = [];
346 const killed: Array<number> = [];
347 const outputs: Array<Queue.Queue<Uint8Array>> = [];
348 const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];
349 const started = yield* Queue.unbounded<number>();
350 const spawner = ChildProcessSpawner.make((command) =>
351 Effect.gen(function* () {
352 if (!ChildProcess.isStandardCommand(command)) {
353 return yield* Effect.die("Expected standard command.");
354 }
355 const index = spawned.length;
356 spawned.push(command);
357 if (index === options.failSpawn) {
358 return yield* PlatformError.systemError({
359 _tag: "NotFound",
360 module: "ChildProcess",
361 method: "spawn",
362 description: "cloudflared temporarily unavailable",
363 });
364 }
365 const output = yield* Queue.unbounded<Uint8Array>();
366 const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
367 outputs[index] = output;
368 exits[index] = exit;
369 const handle = ChildProcessSpawner.makeHandle({
370 ...makeHandle({
371 pid: 800 + index,
372 exitCode: Deferred.await(exit),
373 output: Stream.fromQueue(output),
374 onKill: () => {
375 killed.push(800 + index);
376 Deferred.doneUnsafe(exit, Exit.succeed(ChildProcessSpawner.ExitCode(143)));
377 },
378 }),
379 isRunning: options.isRunning ?? Effect.succeed(true),
380 });
381 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
382 yield* Queue.offer(started, index);
383 return handle;
384 }),
385 );
386 const emit = (index: number, lines: string) =>
387 Queue.offer(outputs[index]!, new TextEncoder().encode(lines));
388 const observe = (
389 runtime: ManagedEndpointRuntime.CloudManagedEndpointRuntime["Service"],
390 index: number,
391 lines = "",
392 ) =>
393 emit(
394 index,
395 lines + "2026-10-16T20:30:00Z INF Registered tunnel connection connIndex=0\n",
396 ).pipe(Effect.andThen(Stream.runHead(runtime.tunnelConnected)));
397 return { spawner, spawned, killed, exits, started, emit, observe };
398 });
399​
400 it.effect("preserves an explicit transport choice despite repeated QUIC stalls", () =>
401 Effect.gen(function* () {
402 const fixture = yield* makeTransportSpawner({ transport: "quic" });
403 const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);
404 yield* runtime.applyConfig(tunnelConfig);
405 yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30));
406 yield* fixture.observe(runtime, 0, quicDatagramWarning.repeat(30));
407 expect(fixture.spawned).toHaveLength(1);
408 expect(fixture.killed).toEqual([]);
409 expect(fixture.spawned[0]!.args).not.toContain("--protocol");
410 expect(fixture.spawned[0]!.options.env?.TUNNEL_TRANSPORT_PROTOCOL).toBe("quic");
411 }),
412 );
413​
414 it.effect(
415 "retains automatic HTTP/2 fallback across restarts until expiry and respects overrides",
416 () =>
417 Effect.gen(function* () {
418 const context = yield* Layer.build(
419 ServerSecretStore.layer.pipe(
420 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-transport-test-" })),
421 Layer.provide(NodeServices.layer),
422 ),
423 );
424 const secretStoreLayer = Layer.succeed(
425 ServerSecretStore.ServerSecretStore,
426 context.pipe(Context.get(ServerSecretStore.ServerSecretStore)),
427 );
428 const fixture = yield* makeTransportSpawner();
429 const start = (spawner = fixture.spawner) =>
430 buildCloudManagedEndpointRuntime(
431 spawner,
432 layerRelayClientAvailable,
433 unusedHttpClient,
434 secretStoreLayer,
435 );
436 yield* Effect.gen(function* () {
437 const runtime = yield* start();
438 yield* runtime.applyConfig(tunnelConfig);
439 expect(yield* Queue.take(fixture.started)).toBe(0);
440 expect(fixture.spawned[0]!.args).not.toContain("--protocol");
441 yield* fixture.emit(0, quicDialWarning.repeat(30));
442 expect(yield* Queue.take(fixture.started)).toBe(1);
443 yield* fixture.observe(runtime, 1);
444 expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
445 }).pipe(Effect.scoped);
446​
447 yield* TestClock.adjust(Duration.hours(1));
448 for (const transport of [undefined, "quic", "http2", "auto", undefined]) {
449 yield* Effect.gen(function* () {
450 const next = yield* makeTransportSpawner(transport ? { transport } : {});
451 const restarted = yield* start(next.spawner);
452 yield* restarted.applyConfig(tunnelConfig);
453 if (transport === undefined) {
454 expect(next.spawned[0]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
455 } else {
456 expect(next.spawned[0]!.args).not.toContain("--protocol");
457 expect(next.spawned[0]!.options.env?.TUNNEL_TRANSPORT_PROTOCOL).toBe(transport);
458 yield* next.observe(restarted, 0, quicDialWarning.repeat(30));
459 expect(next.spawned).toHaveLength(1);
460 }
461 }).pipe(Effect.scoped);
462 }
463​
464 // Reusing the hint one hour later must not extend its original lifetime.
465 yield* TestClock.adjust(Duration.hours(23));
466 yield* Effect.gen(function* () {
467 const next = yield* makeTransportSpawner();
468 const restarted = yield* start(next.spawner);
469 yield* restarted.applyConfig(tunnelConfig);
470 expect(next.spawned[0]!.args).not.toContain("--protocol");
471 expect(yield* Queue.take(next.started)).toBe(0);
472 yield* next.emit(0, quicDatagramWarning.repeat(30));
473 expect(yield* Queue.take(next.started)).toBe(1);
474 expect(next.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
475 }).pipe(Effect.scoped);
476 }),
477 );
478​
479 it.effect(
480 "ignores invalid or unreadable fallback state and still falls back if persistence fails",
481 () =>
482 Effect.gen(function* () {
483 for (const cached of [
484 "not json",
485 '{"fellBackAt":"invalid"}',
486 '{"fellBackAt":9007199254740991}',
487 null,
488 ]) {
489 yield* Effect.gen(function* () {
490 const fixture = yield* makeTransportSpawner();
491 const runtime = yield* buildCloudManagedEndpointRuntime(
492 fixture.spawner,
493 layerRelayClientAvailable,
494 unusedHttpClient,
495 Layer.mock(ServerSecretStore.ServerSecretStore)({
496 get: () =>
497 cached === null
498 ? Effect.fail(
499 new ServerSecretStore.SecretStoreReadError({
500 resource: "test",
501 cause: "unreadable",
502 }),
503 )
504 : Effect.succeedSome(new TextEncoder().encode(cached)),
505 set: () =>
506 Effect.fail(
507 new ServerSecretStore.SecretStorePersistError({
508 resource: "test",
509 cause: "read-only",
510 }),
511 ),
512 }),
513 );
514 yield* runtime.applyConfig(tunnelConfig);
515 expect(yield* Queue.take(fixture.started)).toBe(0);
516 expect(fixture.spawned[0]!.args).not.toContain("--protocol");
517 yield* fixture.emit(0, quicDialWarning.repeat(30));
518 expect(yield* Queue.take(fixture.started)).toBe(1);
519 expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
520 }).pipe(Effect.scoped);
521 }
522 }),
523 );
524​
525 it.effect("requests recovery after a failed HTTP/2 spawn and retries with HTTP/2", () =>
526 Effect.gen(function* () {
527 const fixture = yield* makeTransportSpawner({ failSpawn: 1 });
528 const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);
529 yield* runtime.applyConfig(tunnelConfig);
530 expect(yield* Queue.take(fixture.started)).toBe(0);
531 yield* fixture.emit(0, quicDialWarning.repeat(30));
532​
533 const requested = Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests));
534 expect(requested).toEqual(tunnelConfig);
535 expect(fixture.killed).toEqual([800]);
536 expect(fixture.spawned).toHaveLength(2);
537 expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
538 expect(yield* runtime.applyConfig(requested)).toMatchObject({ status: "running", pid: 802 });
539 yield* fixture.observe(runtime, 2);
540 expect(fixture.spawned[2]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
541 }),
542 );
543​
544 it.effect("discards a pending fallback when its connector is replaced or removed", () =>
545 Effect.gen(function* () {
546 for (const nextConfig of [{ ...tunnelConfig, connectorToken: "replacement" }, null]) {
547 yield* Effect.gen(function* () {
548 const checking = yield* Deferred.make<void>();
549 const releaseCheck = yield* Deferred.make<void>();
550 const fixture = yield* makeTransportSpawner({
551 isRunning: Deferred.succeed(checking, undefined).pipe(
552 Effect.andThen(Deferred.await(releaseCheck)),
553 Effect.as(true),
554 ),
555 });
556 const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);
557 yield* runtime.applyConfig(tunnelConfig);
558 yield* fixture.observe(runtime, 0);
559​
560 // Hold reconciliation in a process probe so config changes queue before fallback.
561 const probe = yield* runtime.applyConfig(tunnelConfig).pipe(Effect.forkChild);
562 yield* Deferred.await(checking);
563 const change = yield* runtime
564 .applyConfig(nextConfig)
565 .pipe(Effect.forkChild({ startImmediately: true }));
566 yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30));
567 yield* Deferred.succeed(releaseCheck, undefined);
568 yield* Fiber.join(probe);
569 yield* Fiber.join(change);
570 yield* TestClock.adjust(Duration.zero);
571​
572 expect(fixture.killed).toEqual([800]);
573 expect(fixture.spawned).toHaveLength(nextConfig ? 2 : 1);
574 if (nextConfig) {
575 expect(fixture.spawned[1]!.options.env?.TUNNEL_TOKEN).toBe("replacement");
576 expect(fixture.spawned[1]!.args).not.toContain("--protocol");
577 }
578 yield* runtime.applyConfig(null);
579 // Buffered output and the old exit cannot revive a removed configuration.
580 yield* fixture.emit(0, quicDialWarning.repeat(30));
581 yield* TestClock.adjust(Duration.minutes(5));
582 expect(fixture.spawned).toHaveLength(nextConfig ? 2 : 1);
583 expect(fixture.killed).toEqual(nextConfig ? [800, 801] : [800]);
584 }).pipe(Effect.scoped);
585 }
586 }).pipe(Effect.provide(TestClock.layer())),
587 );
588​
589 it.effect("recovers a rejected tunnel without waiting for the connector to exit", () =>
590 Effect.gen(function* () {
591 const output = yield* Queue.unbounded<Uint8Array>();
592 const firstBatchObserved = yield* Deferred.make<void>();
593 const secondBatchObserved = yield* Deferred.make<void>();
594 const recoveryRequested = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
595 const recoveryRetried = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
596 let recoveryRequestCount = 0;
597 const spawned: Array<number> = [];
598 const encoder = new TextEncoder();
599 const connectorOutput = Stream.fromQueue(output).pipe(
600 Stream.tap((chunk) => {
601 const line = new TextDecoder().decode(chunk);
602 if (line === "first checkpoint\n") {
603 return Deferred.succeed(firstBatchObserved, undefined).pipe(Effect.asVoid);
604 }
605 if (line === "second checkpoint\n") {
606 return Deferred.succeed(secondBatchObserved, undefined).pipe(Effect.asVoid);
607 }
608 return Effect.void;
609 }),
610 );
611 const spawner = ChildProcessSpawner.make(() =>
612 Effect.gen(function* () {
613 const pid = 600;
614 spawned.push(pid);
615 const handle = makeHandle({ pid, onKill: () => {}, output: connectorOutput });
616 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
617 return handle;
618 }),
619 );
620 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
621 const config = {
622 providerKind: "cloudflare_tunnel" as const,
623 connectorToken: "token",
624 tunnelId: "deleted-tunnel",
625 };
626 const rejectedLine =
627 '2026-09-15T06:30:43Z ERR Register tunnel error from server side error="Failed to get tunnel" connIndex=0 event=0 ip=198.41.200.23\n';
628​
629 yield* runtime.recoveryRequests.pipe(
630 Stream.runForEach((requested) => {
631 recoveryRequestCount += 1;
632 return Deferred.succeed(
633 recoveryRequestCount === 1 ? recoveryRequested : recoveryRetried,
634 requested,
635 ).pipe(Effect.asVoid);
636 }),
637 Effect.forkChild,
638 );
639 yield* runtime.applyConfig(config);
640​
641 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(3)));
642 yield* Queue.offer(output, encoder.encode("first checkpoint\n"));
643 yield* Deferred.await(firstBatchObserved);
644 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
645​
646 yield* Queue.offer(
647 output,
648 encoder.encode(
649 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0\n" +
650 rejectedLine.repeat(3),
651 ),
652 );
653 yield* Queue.offer(output, encoder.encode("second checkpoint\n"));
654 yield* Deferred.await(secondBatchObserved);
655 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
656​
657 yield* Queue.offer(output, encoder.encode(rejectedLine));
658​
659 expect(yield* Deferred.await(recoveryRequested)).toEqual(config);
660​
661 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(4)));
662​
663 expect(yield* Deferred.await(recoveryRetried)).toEqual(config);
664 expect(spawned).toEqual([600]);
665 }),
666 );
667​
668 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
669 Effect.gen(function* () {
670 const spawned: Array<ChildProcess.StandardCommand> = [];
671 const killed: Array<number> = [];
672 let nextPid = 100;
673 const spawner = ChildProcessSpawner.make((command) =>
674 Effect.gen(function* () {
675 if (!ChildProcess.isStandardCommand(command)) {
676 throw new Error("Expected standard command.");
677 }
678 spawned.push(command);
679 const pid = nextPid;
680 nextPid += 1;
681 const handle = makeHandle({
682 pid,
683 onKill: () => {
684 killed.push(pid);
685 },
686 });
687 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
688 return handle;
689 }),
690 );
691 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
692​
693 yield* runtime.applyConfig({
694 providerKind: "cloudflare_tunnel",
695 connectorToken: "token-1",
696 tunnelId: "tunnel-1",
697 tunnelName: "t3-code-env-1",
698 });
699 yield* runtime.applyConfig({
700 providerKind: "cloudflare_tunnel",
701 connectorToken: "token-1",
702 tunnelId: "tunnel-1",
703 tunnelName: "t3-code-env-1",
704 });
705 yield* runtime.applyConfig({
706 providerKind: "cloudflare_tunnel",
707 connectorToken: "token-2",
708 tunnelId: "tunnel-1",
709 tunnelName: "t3-code-env-1",
710 });
711 const stopped = yield* runtime.applyConfig(null);
712​
713 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
714 expect(spawned.map((command) => command.args)).toEqual([
715 [
716 "tunnel",
717 "--no-autoupdate",
718 "--loglevel",
719 "info",
720 "--output",
721 "default",
722 "--metrics",
723 "127.0.0.1:0",
724 "run",
725 ],
726 [
727 "tunnel",
728 "--no-autoupdate",
729 "--loglevel",
730 "info",
731 "--output",
732 "default",
733 "--metrics",
734 "127.0.0.1:0",
735 "run",
736 ],
737 ]);
738 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
739 "token-1",
740 "token-2",
741 ]);
742 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
743 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
744 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
745 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
746 expect(killed).toEqual([100, 101]);
747 expect(stopped).toEqual({ status: "disabled" });
748 }),
749 );
750​
751 it.effect("supervises the active connector and restarts it after process exit", () =>
752 Effect.gen(function* () {
753 const spawned: Array<number> = [];
754 const killed: Array<number> = [];
755 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
756 const secondSpawned = yield* Deferred.make<void>();
757 const spawner = ChildProcessSpawner.make(() =>
758 Effect.gen(function* () {
759 const pid = spawned.length === 0 ? 400 : 401;
760 spawned.push(pid);
761 if (pid === 401) {
762 yield* Deferred.succeed(secondSpawned, undefined);
763 }
764 const handle = makeHandle({
765 pid,
766 exitCode:
767 pid === 400
768 ? Deferred.await(firstExit)
769 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
770 onKill: () => {
771 killed.push(pid);
772 },
773 });
774 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
775 return handle;
776 }),
777 );
778 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
779​
780 const started = yield* runtime.applyConfig({
781 providerKind: "cloudflare_tunnel",
782 connectorToken: "token",
783 tunnelId: "tunnel-1",
784 });
785 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
786 yield* Deferred.await(secondSpawned);
787​
788 expect(started).toMatchObject({ status: "running", pid: 400 });
789 expect(spawned).toEqual([400, 401]);
790 expect(killed).toEqual([400]);
791 }),
792 );
793​
794 it.effect("serializes concurrent connector config changes", () =>
795 Effect.gen(function* () {
796 const spawned: Array<number> = [];
797 const killed: Array<number> = [];
798 const firstSpawnEntered = yield* Deferred.make<void>();
799 const releaseFirstSpawn = yield* Deferred.make<void>();
800 const spawner = ChildProcessSpawner.make(() =>
801 Effect.gen(function* () {
802 const pid = 500 + spawned.length;
803 spawned.push(pid);
804 if (pid === 500) {
805 yield* Deferred.succeed(firstSpawnEntered, undefined);
806 yield* Deferred.await(releaseFirstSpawn);
807 }
808 const handle = makeHandle({
809 pid,
810 onKill: () => {
811 killed.push(pid);
812 },
813 });
814 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
815 return handle;
816 }),
817 );
818 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
819​
820 const first = yield* runtime
821 .applyConfig({
822 providerKind: "cloudflare_tunnel",
823 connectorToken: "token-1",
824 })
825 .pipe(Effect.forkChild);
826 yield* Deferred.await(firstSpawnEntered);
827 const second = yield* runtime
828 .applyConfig({
829 providerKind: "cloudflare_tunnel",
830 connectorToken: "token-2",
831 })
832 .pipe(Effect.forkChild);
833 yield* Deferred.succeed(releaseFirstSpawn, undefined);
834​
835 yield* Fiber.join(first);
836 const status = yield* Fiber.join(second);
837​
838 expect(status).toMatchObject({ status: "running", pid: 501 });
839 expect(spawned).toEqual([500, 501]);
840 expect(killed).toEqual([500]);
841 }),
842 );
843​
844 it.effect(
845 "runs an older relay client while the pinned one installs, then hands off to it and prunes",
846 () =>
847 Effect.gen(function* () {
848 const olderClient = {
849 status: "available",
850 executablePath: "/managed/2025.9.0/cloudflared",
851 source: "managed",
852 version: "2025.9.0",
853 } as const;
854 const pinnedClient = {
855 status: "available",
856 executablePath: "/managed/pinned/cloudflared",
857 source: "managed",
858 version: RelayClient.CLOUDFLARED_VERSION,
859 } as const;
860 let installed = false;
861 const releaseInstall = yield* Deferred.make<void>();
862 const pruned = yield* Deferred.make<void>();
863 const spawned = yield* Queue.unbounded<string>();
864 const olderStopped = yield* Deferred.make<void>();
865 const output = yield* Queue.unbounded<Uint8Array>();
866 const spawner = ChildProcessSpawner.make((command) =>
867 Effect.gen(function* () {
868 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
869 yield* Queue.offer(spawned, executable);
870 const handle = makeHandle({
871 pid: executable === pinnedClient.executablePath ? 2 : 1,
872 onKill: () => {
873 if (executable === olderClient.executablePath) {
874 Deferred.doneUnsafe(olderStopped, Effect.void);
875 }
876 },
877 ...(executable === pinnedClient.executablePath
878 ? { output: Stream.fromQueue(output) }
879 : {}),
880 });
881 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
882 return handle;
883 }),
884 );
885 const runtime = yield* buildCloudManagedEndpointRuntime(
886 spawner,
887 Layer.succeed(
888 RelayClient.RelayClient,
889 RelayClient.RelayClient.of({
890 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
891 install: Deferred.await(releaseInstall).pipe(
892 Effect.andThen(
893 Effect.sync(() => {
894 installed = true;
895 return pinnedClient;
896 }),
897 ),
898 ),
899 installWithProgress: () => Effect.die("unused"),
900 pruneManagedVersions: Deferred.succeed(pruned, undefined).pipe(Effect.asVoid),
901 }),
902 ),
903 );
904​
905 const status = yield* runtime.applyConfig({
906 providerKind: "cloudflare_tunnel",
907 connectorToken: "token",
908 });
909 expect(status).toMatchObject({ status: "running", pid: 1 });
910 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
911​
912 yield* Deferred.succeed(releaseInstall, undefined);
913 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
914 expect(Option.isNone(yield* Deferred.poll(olderStopped))).toBe(true);
915​
916 yield* Queue.offer(
917 output,
918 new TextEncoder().encode(
919 "2026-10-08T00:00:00Z INF Registered tunnel connection connIndex=0\n",
920 ),
921 );
922 yield* Deferred.await(olderStopped);
923 yield* Deferred.await(pruned);
924 }),
925 );
926​
927 it.effect("installs a missing relay client in the background and then starts it", () =>
928 Effect.gen(function* () {
929 const pinnedClient = {
930 status: "available",
931 executablePath: "/managed/pinned/cloudflared",
932 source: "managed",
933 version: RelayClient.CLOUDFLARED_VERSION,
934 } as const;
935 let installed = false;
936 const spawned = yield* Deferred.make<string>();
937 const spawner = ChildProcessSpawner.make((command) =>
938 Effect.gen(function* () {
939 yield* Deferred.succeed(
940 spawned,
941 ChildProcess.isStandardCommand(command) ? command.command : "",
942 );
943 const handle = makeHandle({ pid: 3, onKill: () => {} });
944 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
945 return handle;
946 }),
947 );
948 const runtime = yield* buildCloudManagedEndpointRuntime(
949 spawner,
950 Layer.succeed(
951 RelayClient.RelayClient,
952 RelayClient.RelayClient.of({
953 resolve: Effect.sync(() =>
954 installed
955 ? pinnedClient
956 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
957 ),
958 install: Effect.sync(() => {
959 installed = true;
960 return pinnedClient;
961 }),
962 installWithProgress: () => Effect.die("unused"),
963 pruneManagedVersions: Effect.void,
964 }),
965 ),
966 );
967​
968 const status = yield* runtime.applyConfig({
969 providerKind: "cloudflare_tunnel",
970 connectorToken: "token",
971 });
972 expect(status).toMatchObject({ status: "failed", failure: "not-installed" });
973 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
974 }),
975 );
976​
977 it.effect("keeps the older connector when the updated relay client fails to start", () =>
978 Effect.gen(function* () {
979 const olderClient = {
980 status: "available",
981 executablePath: "/managed/2025.9.0/cloudflared",
982 source: "managed",
983 version: "2025.9.0",
984 } as const;
985 const pinnedClient = {
986 status: "available",
987 executablePath: "/managed/pinned/cloudflared",
988 source: "managed",
989 version: RelayClient.CLOUDFLARED_VERSION,
990 } as const;
991 let installed = false;
992 let olderKilled = false;
993 const releaseInstall = yield* Deferred.make<void>();
994 const pinnedAttempted = yield* Deferred.make<void>();
995 const spawner = ChildProcessSpawner.make((command) =>
996 Effect.gen(function* () {
997 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
998 if (executable === pinnedClient.executablePath) {
999 yield* Deferred.succeed(pinnedAttempted, undefined);
1000 return yield* PlatformError.systemError({
1001 _tag: "PermissionDenied",
1002 module: "ChildProcess",
1003 method: "spawn",
1004 });
1006 const handle = makeHandle({
1007 pid: 6,
1008 onKill: () => {
1009 olderKilled = true;
1010 },
1011 });
1012 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1013 return handle;
1014 }),
1015 );
1016 const runtime = yield* buildCloudManagedEndpointRuntime(
1017 spawner,
1018 Layer.succeed(
1019 RelayClient.RelayClient,
1020 RelayClient.RelayClient.of({
1021 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1022 install: Deferred.await(releaseInstall).pipe(
1023 Effect.andThen(
1024 Effect.sync(() => {
1025 installed = true;
1026 return pinnedClient;
1027 }),
1028 ),
1029 ),
1030 installWithProgress: () => Effect.die("unused"),
1031 pruneManagedVersions: Effect.void,
1032 }),
1033 ),
1034 );
1035 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1036 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1037​
1038 yield* Deferred.succeed(releaseInstall, undefined);
1039 yield* Deferred.await(pinnedAttempted);
1040 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1041 expect(olderKilled).toBe(false);
1042 }),
1043 );
1044​
1045 it.effect("requests recovery when the older connector exited during a failed swap", () =>
1046 Effect.gen(function* () {
1047 const olderClient = {
1048 status: "available",
1049 executablePath: "/managed/2025.9.0/cloudflared",
1050 source: "managed",
1051 version: "2025.9.0",
1052 } as const;
1053 const pinnedClient = {
1054 status: "available",
1055 executablePath: "/managed/pinned/cloudflared",
1056 source: "managed",
1057 version: RelayClient.CLOUDFLARED_VERSION,
1058 } as const;
1059 let installed = false;
1060 const releaseInstall = yield* Deferred.make<void>();
1061 const spawner = ChildProcessSpawner.make((command) =>
1062 Effect.gen(function* () {
1063 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1064 if (executable === pinnedClient.executablePath) {
1065 return yield* PlatformError.systemError({
1066 _tag: "PermissionDenied",
1067 module: "ChildProcess",
1068 method: "spawn",
1069 });
1071 const handle = makeHandle({ pid: 12, onKill: () => {}, isRunning: () => !installed });
1072 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1073 return handle;
1074 }),
1075 );
1076 const runtime = yield* buildCloudManagedEndpointRuntime(
1077 spawner,
1078 Layer.succeed(
1079 RelayClient.RelayClient,
1080 RelayClient.RelayClient.of({
1081 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1082 install: Deferred.await(releaseInstall).pipe(
1083 Effect.andThen(
1084 Effect.sync(() => {
1085 installed = true;
1086 return pinnedClient;
1087 }),
1088 ),
1089 ),
1090 installWithProgress: () => Effect.die("unused"),
1091 pruneManagedVersions: Effect.void,
1092 }),
1093 ),
1094 );
1095 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1096 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 12 });
1097​
1098 yield* Deferred.succeed(releaseInstall, undefined);
1099 expect(Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
1100 }),
1101 );
1102​
1103 it.effect("restarts a self-updated pinned-folder connector once the pin is reinstalled", () =>
1104 Effect.gen(function* () {
1105 const executablePath = "/managed/pinned/cloudflared";
1106 let version = "2026.9.3";
1107 const releaseInstall = yield* Deferred.make<void>();
1108 const spawned = yield* Queue.unbounded<string>();
1109 const spawner = ChildProcessSpawner.make(() =>
1110 Effect.gen(function* () {
1111 yield* Queue.offer(spawned, version);
1112 const handle = makeHandle({ pid: 7, onKill: () => {} });
1113 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1114 return handle;
1115 }),
1116 );
1117 const current = () =>
1118 ({ status: "available", executablePath, source: "managed", version }) as const;
1119 const runtime = yield* buildCloudManagedEndpointRuntime(
1120 spawner,
1121 Layer.succeed(
1122 RelayClient.RelayClient,
1123 RelayClient.RelayClient.of({
1124 resolve: Effect.sync(current),
1125 install: Deferred.await(releaseInstall).pipe(
1126 Effect.andThen(
1127 Effect.sync(() => {
1128 version = RelayClient.CLOUDFLARED_VERSION;
1129 return current();
1130 }),
1131 ),
1132 ),
1133 installWithProgress: () => Effect.die("unused"),
1134 pruneManagedVersions: Effect.void,
1135 }),
1136 ),
1137 );
1138​
1139 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1140 expect(yield* Queue.take(spawned)).toBe("2026.9.3");
1141 yield* Deferred.succeed(releaseInstall, undefined);
1142 expect(yield* Queue.take(spawned)).toBe(RelayClient.CLOUDFLARED_VERSION);
1143 }),
1144 );
1145});