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

ManagedEndpointRuntime.test.ts

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