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

ManagedEndpointRuntime.test.ts

1,026 lines39.0 KB

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