Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import { vi } from "vite-plus/test";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
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 type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
16import * as RelayClient from "@t3tools/shared/relayClient";
17
18import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
19import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
20
21const layerRelayClientAvailable = Layer.succeed(
22 RelayClient.RelayClient,
23 RelayClient.RelayClient.of({
24 resolve: Effect.succeed({
25 status: "available",
26 executablePath: "cloudflared",
27 source: "path",
28 version: RelayClient.CLOUDFLARED_VERSION,
29 }),
30 install: Effect.die("unused"),
31 installWithProgress: () => Effect.die("unused"),
32 pruneManagedVersions: Effect.void,
33 }),
34);
35
36const runtimeDependencies = (
37 spawner: ReturnType<typeof ChildProcessSpawner.make>,
38 relayClientLayer = layerRelayClientAvailable,
39) =>
40 Layer.mergeAll(
41 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
42 relayClientLayer,
43 Layer.mock(ServerSecretStore.ServerSecretStore)({
44 get: () => Effect.succeedNone,
45 }),
46 );
47
48const buildCloudManagedEndpointRuntime = (
49 spawner: ReturnType<typeof ChildProcessSpawner.make>,
50 relayClientLayer = layerRelayClientAvailable,
51) =>
52 Effect.gen(function* () {
53 const context = yield* Layer.build(
54 ManagedEndpointRuntime.layer.pipe(
55 Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
56 ),
57 );
58 return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
59 Effect.provide(context),
60 );
61 });
62
63function makeHandle(input: {
64 readonly pid: number;
65 readonly onKill: () => void;
66 readonly isRunning?: () => boolean;
67 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
68 readonly output?: Stream.Stream<Uint8Array>;
69}) {
70 return ChildProcessSpawner.makeHandle({
71 pid: ChildProcessSpawner.ProcessId(input.pid),
72 exitCode: input.exitCode ?? Effect.never,
73 isRunning: Effect.sync(() => input.isRunning?.() ?? true),
74 kill: () =>
75 Effect.sync(() => {
76 input.onKill();
77 }),
78 unref: Effect.succeed(Effect.void),
79 stdin: Sink.drain,
80 stdout: Stream.empty,
81 stderr: Stream.empty,
82 all: input.output ?? Stream.empty,
83 getInputFd: () => Sink.drain,
84 getOutputFd: () => Stream.empty,
85 });
86}
87
88describe("CloudManagedEndpointRuntime", () => {
89 it("retries connector startup failures but stops for unsupported runtimes", () => {
90 expect(
91 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({
92 status: "failed",
93 failure: "not-installed",
94 reason: "The relay client is not installed.",
95 }),
96 ).toBe(true);
97 expect(
98 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({
99 status: "failed",
100 failure: "spawn-failed",
101 reason: "spawn failed",
102 }),
103 ).toBe(true);
104 expect(
105 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({
106 status: "failed",
107 failure: "unsupported-platform",
108 reason: "Relay client is unsupported on linux-arm.",
109 }),
110 ).toBe(false);
111 expect(
112 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({ status: "unsupported" }),
113 ).toBe(false);
114 });
115
116 it.effect("serializes updates to persisted cloud link state", () =>
117 Effect.gen(function* () {
118 const firstEntered = yield* Deferred.make<void>();
119 const releaseFirst = yield* Deferred.make<void>();
120 const secondEntered = yield* Deferred.make<void>();
121 const runtime = yield* buildCloudManagedEndpointRuntime(
122 ChildProcessSpawner.make(() => Effect.die("unused")),
123 );
124
125 const first = yield* runtime
126 .withLinkStateLock(
127 Deferred.succeed(firstEntered, undefined).pipe(
128 Effect.andThen(Deferred.await(releaseFirst)),
129 ),
130 )
131 .pipe(Effect.forkChild);
132 yield* Deferred.await(firstEntered);
133
134 const second = yield* runtime
135 .withLinkStateLock(Deferred.succeed(secondEntered, undefined))
136 .pipe(Effect.forkChild);
137 expect(yield* Deferred.isDone(secondEntered)).toBe(false);
138
139 yield* Deferred.succeed(releaseFirst, undefined);
140 yield* Fiber.join(first);
141 yield* Fiber.join(second);
142 expect(yield* Deferred.isDone(secondEntered)).toBe(true);
143 }),
144 );
145
146 it("classifies Cloudflare connection and warning output", () => {
147 expect(
148 ManagedEndpointRuntime.classifyRelayClientOutput(
149 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
150 ),
151 ).toBe("connected");
152 expect(
153 ManagedEndpointRuntime.classifyRelayClientOutput(
154 "2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
155 ),
156 ).toBe("warning");
157 expect(
158 ManagedEndpointRuntime.classifyRelayClientOutput(
159 "2026-06-17T02:00:00Z INF Starting metrics server",
160 ),
161 ).toBe("debug");
162 // FTL (fatal) and PNC (panic) are more severe than ERR and must surface.
163 expect(
164 ManagedEndpointRuntime.classifyRelayClientOutput(
165 "2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",
166 ),
167 ).toBe("warning");
168 expect(
169 ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),
170 ).toBe("warning");
171 });
172
173 it("recognizes tunnel authorization failures without matching ordinary transport errors", () => {
174 expect(
175 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
176 '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',
177 ),
178 ).toBe(true);
179 expect(
180 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
181 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="Unauthorized: Record for tunnel not found" connIndex=0',
182 ),
183 ).toBe(true);
184 expect(
185 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
186 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="Unauthorized: Invalid tunnel secret" connIndex=0',
187 ),
188 ).toBe(true);
189 // Seen in production on 2026-10-06 after the relay deleted an idle tunnel.
190 expect(
191 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
192 '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',
193 ),
194 ).toBe(true);
195 expect(
196 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
197 '2026-10-06T12:00:00Z ERR Register tunnel error from server side error="Tunnel not found" connIndex=0',
198 ),
199 ).toBe(true);
200 expect(
201 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
202 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="connection timed out" connIndex=0',
203 ),
204 ).toBe(false);
205 expect(
206 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
207 '2026-06-17T02:00:00Z ERR Failed to serve tunnel connection error="Unauthorized: Tunnel not found" connIndex=0',
208 ),
209 ).toBe(false);
210 });
211
212 it.effect("keeps recovery requests sent before the server starts consuming them", () =>
213 Effect.gen(function* () {
214 const runtime = yield* buildCloudManagedEndpointRuntime(
215 ChildProcessSpawner.make(() => Effect.die("unused")),
216 );
217 const config = {
218 providerKind: "cloudflare_tunnel" as const,
219 connectorToken: "token",
220 tunnelId: "tunnel-1",
221 };
222
223 yield* runtime.requestRecovery(config);
224
225 expect(Option.getOrNull(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
226 }),
227 );
228
229 it.effect("signals each registered tunnel connection", () =>
230 Effect.gen(function* () {
231 const output = yield* Queue.unbounded<Uint8Array>();
232 const spawner = ChildProcessSpawner.make(() =>
233 Effect.gen(function* () {
234 const handle = makeHandle({
235 pid: 700,
236 onKill: () => {},
237 output: Stream.fromQueue(output),
238 });
239 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
240 return handle;
241 }),
242 );
243 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
244 yield* runtime.applyConfig({
245 providerKind: "cloudflare_tunnel",
246 connectorToken: "token",
247 tunnelId: "tunnel-1",
248 });
249 yield* Queue.offer(
250 output,
251 new TextEncoder().encode(
252 "2026-10-04T06:30:43Z INF Registered tunnel connection connIndex=0 event=0\n",
253 ),
254 );
255 expect(Option.isSome(yield* Stream.runHead(runtime.tunnelConnected))).toBe(true);
256 }),
257 );
258
259 it.effect("recovers a rejected tunnel without waiting for the connector to exit", () =>
260 Effect.gen(function* () {
261 const output = yield* Queue.unbounded<Uint8Array>();
262 const firstBatchObserved = yield* Deferred.make<void>();
263 const secondBatchObserved = yield* Deferred.make<void>();
264 const recoveryRequested = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
265 const recoveryRetried = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
266 let recoveryRequestCount = 0;
267 const spawned: Array<number> = [];
268 const encoder = new TextEncoder();
269 const connectorOutput = Stream.fromQueue(output).pipe(
270 Stream.tap((chunk) => {
271 const line = new TextDecoder().decode(chunk);
272 if (line === "first checkpoint\n") {
273 return Deferred.succeed(firstBatchObserved, undefined).pipe(Effect.asVoid);
274 }
275 if (line === "second checkpoint\n") {
276 return Deferred.succeed(secondBatchObserved, undefined).pipe(Effect.asVoid);
277 }
278 return Effect.void;
279 }),
280 );
281 const spawner = ChildProcessSpawner.make(() =>
282 Effect.gen(function* () {
283 const pid = 600;
284 spawned.push(pid);
285 const handle = makeHandle({ pid, onKill: () => {}, output: connectorOutput });
286 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
287 return handle;
288 }),
289 );
290 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
291 const config = {
292 providerKind: "cloudflare_tunnel" as const,
293 connectorToken: "token",
294 tunnelId: "deleted-tunnel",
295 };
296 const rejectedLine =
297 '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';
298
299 yield* runtime.recoveryRequests.pipe(
300 Stream.runForEach((requested) => {
301 recoveryRequestCount += 1;
302 return Deferred.succeed(
303 recoveryRequestCount === 1 ? recoveryRequested : recoveryRetried,
304 requested,
305 ).pipe(Effect.asVoid);
306 }),
307 Effect.forkChild,
308 );
309 yield* runtime.applyConfig(config);
310
311 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(3)));
312 yield* Queue.offer(output, encoder.encode("first checkpoint\n"));
313 yield* Deferred.await(firstBatchObserved);
314 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
315
316 yield* Queue.offer(
317 output,
318 encoder.encode(
319 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0\n" +
320 rejectedLine.repeat(3),
321 ),
322 );
323 yield* Queue.offer(output, encoder.encode("second checkpoint\n"));
324 yield* Deferred.await(secondBatchObserved);
325 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
326
327 yield* Queue.offer(output, encoder.encode(rejectedLine));
328
329 expect(yield* Deferred.await(recoveryRequested)).toEqual(config);
330
331 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(4)));
332
333 expect(yield* Deferred.await(recoveryRetried)).toEqual(config);
334 expect(spawned).toEqual([600]);
335 }),
336 );
337
338 it.effect("requests recovery while the connector never registers a connection", () =>
339 Effect.gen(function* () {
340 const output = yield* Queue.unbounded<Uint8Array>();
341 const spawner = ChildProcessSpawner.make(() =>
342 Effect.gen(function* () {
343 const handle = makeHandle({
344 pid: 800,
345 onKill: () => {},
346 output: Stream.fromQueue(output),
347 });
348 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
349 return handle;
350 }),
351 );
352 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
353 const requests = yield* Queue.unbounded<RelayManagedEndpointRuntimeConfig>();
354 yield* runtime.recoveryRequests.pipe(
355 Stream.runForEach((config) => Queue.offer(requests, config)),
356 Effect.forkChild,
357 );
358 const config = {
359 providerKind: "cloudflare_tunnel" as const,
360 connectorToken: "token",
361 tunnelId: "silently-deleted",
362 };
363 yield* runtime.applyConfig(config);
364
365 yield* TestClock.adjust(Duration.minutes(2));
366 expect(yield* Queue.size(requests)).toBe(0);
367 yield* TestClock.adjust(Duration.minutes(1));
368 expect(yield* Queue.take(requests)).toEqual(config);
369 // Still unconnected, so it asks again.
370 yield* TestClock.adjust(Duration.minutes(3));
371 expect(yield* Queue.take(requests)).toEqual(config);
372 }).pipe(Effect.provide(TestClock.layer())),
373 );
374
375 it.effect("does not request recovery once the connector has connected", () =>
376 Effect.gen(function* () {
377 const output = yield* Queue.unbounded<Uint8Array>();
378 const spawner = ChildProcessSpawner.make(() =>
379 Effect.gen(function* () {
380 const handle = makeHandle({
381 pid: 801,
382 onKill: () => {},
383 output: Stream.fromQueue(output),
384 });
385 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
386 return handle;
387 }),
388 );
389 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
390 const requests = yield* Queue.unbounded<RelayManagedEndpointRuntimeConfig>();
391 yield* runtime.recoveryRequests.pipe(
392 Stream.runForEach((config) => Queue.offer(requests, config)),
393 Effect.forkChild,
394 );
395 yield* runtime.applyConfig({
396 providerKind: "cloudflare_tunnel",
397 connectorToken: "token",
398 tunnelId: "tunnel-1",
399 });
400 yield* Queue.offer(
401 output,
402 new TextEncoder().encode(
403 "2026-10-06T00:00:00Z INF Registered tunnel connection connIndex=0\n",
404 ),
405 );
406 yield* Stream.runHead(runtime.tunnelConnected);
407
408 yield* TestClock.adjust(Duration.minutes(10));
409 expect(yield* Queue.size(requests)).toBe(0);
410 }).pipe(Effect.provide(TestClock.layer())),
411 );
412
413 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
414 Effect.gen(function* () {
415 const spawned: Array<ChildProcess.StandardCommand> = [];
416 const killed: Array<number> = [];
417 let nextPid = 100;
418 const spawner = ChildProcessSpawner.make((command) =>
419 Effect.gen(function* () {
420 if (!ChildProcess.isStandardCommand(command)) {
421 throw new Error("Expected standard command.");
422 }
423 spawned.push(command);
424 const pid = nextPid;
425 nextPid += 1;
426 const handle = makeHandle({
427 pid,
428 onKill: () => {
429 killed.push(pid);
430 },
431 });
432 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
433 return handle;
434 }),
435 );
436 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
437
438 yield* runtime.applyConfig({
439 providerKind: "cloudflare_tunnel",
440 connectorToken: "token-1",
441 tunnelId: "tunnel-1",
442 tunnelName: "t3-code-env-1",
443 });
444 yield* runtime.applyConfig({
445 providerKind: "cloudflare_tunnel",
446 connectorToken: "token-1",
447 tunnelId: "tunnel-1",
448 tunnelName: "t3-code-env-1",
449 });
450 yield* runtime.applyConfig({
451 providerKind: "cloudflare_tunnel",
452 connectorToken: "token-2",
453 tunnelId: "tunnel-1",
454 tunnelName: "t3-code-env-1",
455 });
456 const stopped = yield* runtime.applyConfig(null);
457
458 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
459 expect(spawned.map((command) => command.args)).toEqual([
460 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
461 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
462 ]);
463 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
464 "token-1",
465 "token-2",
466 ]);
467 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
468 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
469 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
470 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
471 expect(killed).toEqual([100, 101]);
472 expect(stopped).toEqual({ status: "disabled" });
473 }),
474 );
475
476 it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>
477 Effect.gen(function* () {
478 const killed: Array<number> = [];
479 const spawner = ChildProcessSpawner.make(() =>
480 Effect.gen(function* () {
481 const handle = makeHandle({
482 pid: 200,
483 onKill: () => {
484 killed.push(200);
485 },
486 });
487 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
488 return handle;
489 }),
490 );
491 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
492
493 const started = yield* runtime.applyConfig({
494 providerKind: "cloudflare_tunnel",
495 connectorToken: "token",
496 });
497 const unsupported = yield* runtime.applyConfig({
498 providerKind: "manual",
499 connectorToken: "manual-token",
500 });
501
502 expect(started.status).toBe("running");
503 expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
504 expect(killed).toEqual([200]);
505 }),
506 );
507
508 it.effect("restarts the connector when the active process has exited", () =>
509 Effect.gen(function* () {
510 const spawned: Array<number> = [];
511 const killed: Array<number> = [];
512 let firstRunning = true;
513 const spawner = ChildProcessSpawner.make(() =>
514 Effect.gen(function* () {
515 const pid = spawned.length === 0 ? 300 : 301;
516 spawned.push(pid);
517 const handle = makeHandle({
518 pid,
519 isRunning: () => (pid === 300 ? firstRunning : true),
520 onKill: () => {
521 killed.push(pid);
522 },
523 });
524 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
525 return handle;
526 }),
527 );
528 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
529 const config = {
530 providerKind: "cloudflare_tunnel" as const,
531 connectorToken: "token",
532 tunnelId: "tunnel-1",
533 };
534
535 const first = yield* runtime.applyConfig(config);
536 firstRunning = false;
537 const second = yield* runtime.applyConfig(config);
538
539 expect(first).toMatchObject({ status: "running", pid: 300 });
540 expect(second).toMatchObject({ status: "running", pid: 301 });
541 expect(spawned).toEqual([300, 301]);
542 expect(killed).toEqual([300]);
543 }),
544 );
545
546 it.effect("supervises the active connector and restarts it after process exit", () =>
547 Effect.gen(function* () {
548 const spawned: Array<number> = [];
549 const killed: Array<number> = [];
550 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
551 const secondSpawned = yield* Deferred.make<void>();
552 const spawner = ChildProcessSpawner.make(() =>
553 Effect.gen(function* () {
554 const pid = spawned.length === 0 ? 400 : 401;
555 spawned.push(pid);
556 if (pid === 401) {
557 yield* Deferred.succeed(secondSpawned, undefined);
558 }
559 const handle = makeHandle({
560 pid,
561 exitCode:
562 pid === 400
563 ? Deferred.await(firstExit)
564 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
565 onKill: () => {
566 killed.push(pid);
567 },
568 });
569 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
570 return handle;
571 }),
572 );
573 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
574
575 const started = yield* runtime.applyConfig({
576 providerKind: "cloudflare_tunnel",
577 connectorToken: "token",
578 tunnelId: "tunnel-1",
579 });
580 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
581 yield* Deferred.await(secondSpawned);
582
583 expect(started).toMatchObject({ status: "running", pid: 400 });
584 expect(spawned).toEqual([400, 401]);
585 expect(killed).toEqual([400]);
586 }),
587 );
588
589 const makeCrashLoopSpawner = (basePid: number, slots: number) =>
590 Effect.gen(function* () {
591 const spawned: Array<number> = [];
592 const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];
593 const spawnSignals: Array<Deferred.Deferred<void>> = [];
594 for (let index = 0; index < slots; index += 1) {
595 exits.push(yield* Deferred.make<ChildProcessSpawner.ExitCode>());
596 spawnSignals.push(yield* Deferred.make<void>());
597 }
598 const spawner = ChildProcessSpawner.make(() =>
599 Effect.gen(function* () {
600 const index = spawned.length;
601 spawned.push(basePid + index);
602 yield* Deferred.succeed(spawnSignals[index]!, undefined);
603 const handle = makeHandle({
604 pid: basePid + index,
605 exitCode: Deferred.await(exits[index]!),
606 onKill: () => {},
607 });
608 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
609 return handle;
610 }),
611 );
612 return { spawner, spawned, exits, spawnSignals };
613 });
614
615 it.effect("backs off restarts while the connector crash-loops", () =>
616 Effect.gen(function* () {
617 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(600, 4);
618 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
619
620 yield* runtime.applyConfig({
621 providerKind: "cloudflare_tunnel",
622 connectorToken: "token",
623 tunnelId: "tunnel-1",
624 });
625 expect(spawned).toEqual([600]);
626
627 // The first crash restarts immediately.
628 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
629 yield* Deferred.await(spawnSignals[1]!);
630 expect(spawned).toEqual([600, 601]);
631
632 // The second rapid crash waits out the base delay before restarting.
633 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
634 yield* TestClock.adjust(Duration.millis(999));
635 expect(spawned).toEqual([600, 601]);
636 yield* TestClock.adjust(Duration.millis(1));
637 yield* Deferred.await(spawnSignals[2]!);
638 expect(spawned).toEqual([600, 601, 602]);
639
640 // The third rapid crash doubles the delay.
641 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
642 yield* TestClock.adjust(Duration.millis(1999));
643 expect(spawned).toEqual([600, 601, 602]);
644 yield* TestClock.adjust(Duration.millis(1));
645 yield* Deferred.await(spawnSignals[3]!);
646 expect(spawned).toEqual([600, 601, 602, 603]);
647 }).pipe(Effect.provide(TestClock.layer())),
648 );
649
650 it.effect("resets the backoff after the connector runs stably", () =>
651 Effect.gen(function* () {
652 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(700, 5);
653 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
654
655 yield* runtime.applyConfig({
656 providerKind: "cloudflare_tunnel",
657 connectorToken: "token",
658 });
659
660 // One rapid crash arms the backoff.
661 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
662 yield* Deferred.await(spawnSignals[1]!);
663
664 // The replacement stays up past the stable-uptime window, so its exit
665 // restarts immediately and the backoff starts over.
666 yield* TestClock.adjust(Duration.millis(30_000));
667 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
668 yield* Deferred.await(spawnSignals[2]!);
669 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
670 yield* Deferred.await(spawnSignals[3]!);
671
672 // The next rapid crash waits the base delay again, not a doubled one.
673 yield* Deferred.succeed(exits[3]!, ChildProcessSpawner.ExitCode(1));
674 yield* TestClock.adjust(Duration.millis(999));
675 expect(spawned).toEqual([700, 701, 702, 703]);
676 yield* TestClock.adjust(Duration.millis(1));
677 yield* Deferred.await(spawnSignals[4]!);
678 expect(spawned).toEqual([700, 701, 702, 703, 704]);
679 }).pipe(Effect.provide(TestClock.layer())),
680 );
681
682 it.effect("a recovery that returns the same config keeps the crash backoff", () =>
683 Effect.gen(function* () {
684 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(900, 4);
685 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
686 const config = {
687 providerKind: "cloudflare_tunnel" as const,
688 connectorToken: "same-token",
689 tunnelId: "same-tunnel",
690 };
691 // The startup consumer re-applies whatever the relay hands back. When the
692 // relay confirms the current tunnel, that must not look like a config change.
693 yield* runtime.recoveryRequests.pipe(
694 Stream.runForEach((requested) => runtime.applyConfig(requested).pipe(Effect.asVoid)),
695 Effect.forkChild,
696 );
697
698 yield* runtime.applyConfig(config);
699 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
700 yield* Deferred.await(spawnSignals[1]!);
701 expect(spawned).toEqual([900, 901]);
702
703 // Second rapid crash still waits out the base delay.
704 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
705 yield* TestClock.adjust(Duration.millis(999));
706 expect(spawned).toEqual([900, 901]);
707 yield* TestClock.adjust(Duration.millis(1));
708 yield* Deferred.await(spawnSignals[2]!);
709 expect(spawned).toEqual([900, 901, 902]);
710 }).pipe(Effect.provide(TestClock.layer())),
711 );
712
713 it.effect("an explicit config change clears the backoff and preempts a delayed restart", () =>
714 Effect.gen(function* () {
715 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(800, 3);
716 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
717
718 yield* runtime.applyConfig({
719 providerKind: "cloudflare_tunnel",
720 connectorToken: "token-1",
721 });
722 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
723 yield* Deferred.await(spawnSignals[1]!);
724
725 // Leave the supervisor sleeping on the base delay, then change config.
726 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
727 const status = yield* runtime.applyConfig({
728 providerKind: "cloudflare_tunnel",
729 connectorToken: "token-2",
730 });
731 expect(status).toMatchObject({ status: "running", pid: 802 });
732 expect(spawned).toEqual([800, 801, 802]);
733
734 // The preempted supervisor wakes later and must not spawn a duplicate.
735 yield* TestClock.adjust(Duration.millis(60_000));
736 expect(spawned).toEqual([800, 801, 802]);
737 }).pipe(Effect.provide(TestClock.layer())),
738 );
739
740 it.effect("serializes concurrent connector config changes", () =>
741 Effect.gen(function* () {
742 const spawned: Array<number> = [];
743 const killed: Array<number> = [];
744 const firstSpawnEntered = yield* Deferred.make<void>();
745 const releaseFirstSpawn = yield* Deferred.make<void>();
746 const spawner = ChildProcessSpawner.make(() =>
747 Effect.gen(function* () {
748 const pid = 500 + spawned.length;
749 spawned.push(pid);
750 if (pid === 500) {
751 yield* Deferred.succeed(firstSpawnEntered, undefined);
752 yield* Deferred.await(releaseFirstSpawn);
753 }
754 const handle = makeHandle({
755 pid,
756 onKill: () => {
757 killed.push(pid);
758 },
759 });
760 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
761 return handle;
762 }),
763 );
764 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
765
766 const first = yield* runtime
767 .applyConfig({
768 providerKind: "cloudflare_tunnel",
769 connectorToken: "token-1",
770 })
771 .pipe(Effect.forkChild);
772 yield* Deferred.await(firstSpawnEntered);
773 const second = yield* runtime
774 .applyConfig({
775 providerKind: "cloudflare_tunnel",
776 connectorToken: "token-2",
777 })
778 .pipe(Effect.forkChild);
779 yield* Deferred.succeed(releaseFirstSpawn, undefined);
780
781 yield* Fiber.join(first);
782 const status = yield* Fiber.join(second);
783
784 expect(status).toMatchObject({ status: "running", pid: 501 });
785 expect(spawned).toEqual([500, 501]);
786 expect(killed).toEqual([500]);
787 }),
788 );
789
790 it.effect("reports connector spawn failures", () =>
791 Effect.gen(function* () {
792 const spawner = ChildProcessSpawner.make(() =>
793 Effect.fail(
794 PlatformError.systemError({
795 _tag: "NotFound",
796 module: "ChildProcess",
797 method: "spawn",
798 description: "cloudflared missing",
799 }),
800 ),
801 );
802 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
803
804 const status = yield* runtime.applyConfig({
805 providerKind: "cloudflare_tunnel",
806 connectorToken: "token",
807 tunnelId: "tunnel-1",
808 });
809
810 expect(status).toMatchObject({
811 status: "failed",
812 providerKind: "cloudflare_tunnel",
813 tunnelId: "tunnel-1",
814 });
815 }),
816 );
817
818 it.effect("reports a missing relay client executable without spawning", () =>
819 Effect.gen(function* () {
820 const spawn = vi.fn();
821 const spawner = ChildProcessSpawner.make(spawn);
822 const runtime = yield* buildCloudManagedEndpointRuntime(
823 spawner,
824 Layer.succeed(
825 RelayClient.RelayClient,
826 RelayClient.RelayClient.of({
827 resolve: Effect.succeed({
828 status: "missing",
829 version: RelayClient.CLOUDFLARED_VERSION,
830 }),
831 install: Effect.die("unused"),
832 installWithProgress: () => Effect.die("unused"),
833 pruneManagedVersions: Effect.void,
834 }),
835 ),
836 );
837
838 const status = yield* runtime.applyConfig({
839 providerKind: "cloudflare_tunnel",
840 connectorToken: "token",
841 });
842
843 expect(status).toEqual({
844 status: "failed",
845 providerKind: "cloudflare_tunnel",
846 failure: "not-installed",
847 reason: "The relay client is not installed.",
848 });
849 expect(spawn).not.toHaveBeenCalled();
850 }),
851 );
852
853 it.effect(
854 "runs an older relay client while the pinned one installs, then hands off to it and prunes",
855 () =>
856 Effect.gen(function* () {
857 const olderClient = {
858 status: "available",
859 executablePath: "/managed/2025.9.0/cloudflared",
860 source: "managed",
861 version: "2025.9.0",
862 } as const;
863 const pinnedClient = {
864 status: "available",
865 executablePath: "/managed/pinned/cloudflared",
866 source: "managed",
867 version: RelayClient.CLOUDFLARED_VERSION,
868 } as const;
869 let installed = false;
870 const releaseInstall = yield* Deferred.make<void>();
871 const pruned = yield* Deferred.make<void>();
872 const spawned = yield* Queue.unbounded<string>();
873 const olderStopped = yield* Deferred.make<void>();
874 const output = yield* Queue.unbounded<Uint8Array>();
875 const spawner = ChildProcessSpawner.make((command) =>
876 Effect.gen(function* () {
877 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
878 yield* Queue.offer(spawned, executable);
879 const handle = makeHandle({
880 pid: executable === pinnedClient.executablePath ? 2 : 1,
881 onKill: () => {
882 if (executable === olderClient.executablePath) {
883 Deferred.doneUnsafe(olderStopped, Effect.void);
884 }
885 },
886 ...(executable === pinnedClient.executablePath
887 ? { output: Stream.fromQueue(output) }
888 : {}),
889 });
890 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
891 return handle;
892 }),
893 );
894 const runtime = yield* buildCloudManagedEndpointRuntime(
895 spawner,
896 Layer.succeed(
897 RelayClient.RelayClient,
898 RelayClient.RelayClient.of({
899 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
900 install: Deferred.await(releaseInstall).pipe(
901 Effect.andThen(
902 Effect.sync(() => {
903 installed = true;
904 return pinnedClient;
905 }),
906 ),
907 ),
908 installWithProgress: () => Effect.die("unused"),
909 pruneManagedVersions: Deferred.succeed(pruned, undefined).pipe(Effect.asVoid),
910 }),
911 ),
912 );
913
914 const status = yield* runtime.applyConfig({
915 providerKind: "cloudflare_tunnel",
916 connectorToken: "token",
917 });
918 expect(status).toMatchObject({ status: "running", pid: 1 });
919 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
920
921 yield* Deferred.succeed(releaseInstall, undefined);
922 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
923 // The older connector keeps serving until the pinned one registers.
924 expect(Option.isNone(yield* Deferred.poll(olderStopped))).toBe(true);
925
926 yield* Queue.offer(
927 output,
928 new TextEncoder().encode(
929 "2026-10-08T00:00:00Z INF Registered tunnel connection connIndex=0\n",
930 ),
931 );
932 yield* Deferred.await(olderStopped);
933 yield* Deferred.await(pruned);
934 }),
935 );
936
937 it.effect("installs a missing relay client in the background and then starts it", () =>
938 Effect.gen(function* () {
939 const pinnedClient = {
940 status: "available",
941 executablePath: "/managed/pinned/cloudflared",
942 source: "managed",
943 version: RelayClient.CLOUDFLARED_VERSION,
944 } as const;
945 let installed = false;
946 const spawned = yield* Deferred.make<string>();
947 const spawner = ChildProcessSpawner.make((command) =>
948 Effect.gen(function* () {
949 yield* Deferred.succeed(
950 spawned,
951 ChildProcess.isStandardCommand(command) ? command.command : "",
952 );
953 const handle = makeHandle({ pid: 3, onKill: () => {} });
954 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
955 return handle;
956 }),
957 );
958 const runtime = yield* buildCloudManagedEndpointRuntime(
959 spawner,
960 Layer.succeed(
961 RelayClient.RelayClient,
962 RelayClient.RelayClient.of({
963 resolve: Effect.sync(() =>
964 installed
965 ? pinnedClient
966 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
967 ),
968 install: Effect.sync(() => {
969 installed = true;
970 return pinnedClient;
971 }),
972 installWithProgress: () => Effect.die("unused"),
973 pruneManagedVersions: Effect.void,
974 }),
975 ),
976 );
977
978 const status = yield* runtime.applyConfig({
979 providerKind: "cloudflare_tunnel",
980 connectorToken: "token",
981 });
982 // The first attempt reports the gap; the install then starts the connector itself.
983 expect(status).toMatchObject({ status: "failed", failure: "not-installed" });
984 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
985 }),
986 );
987
988 it.effect("leaves a PATH relay client alone", () =>
989 Effect.gen(function* () {
990 const install = vi.fn(() => Effect.die("unexpected install"));
991 const spawner = ChildProcessSpawner.make(() =>
992 Effect.gen(function* () {
993 const handle = makeHandle({ pid: 8, onKill: () => {} });
994 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
995 return handle;
996 }),
997 );
998 const runtime = yield* buildCloudManagedEndpointRuntime(
999 spawner,
1000 Layer.succeed(
1001 RelayClient.RelayClient,
1002 RelayClient.RelayClient.of({
1003 resolve: Effect.succeed({
1004 status: "available",
1005 executablePath: "/opt/homebrew/bin/cloudflared",
1006 source: "path",
1007 version: "2026.10.0",
1008 }),
1009 install: Effect.suspend(install),
1010 installWithProgress: () => Effect.die("unused"),
1011 pruneManagedVersions: Effect.void,
1012 }),
1013 ),
1014 );
1015 expect(
1016 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1017 ).toMatchObject({ status: "running", pid: 8 });
1018 yield* TestClock.adjust(Duration.minutes(30));
1019 expect(install).not.toHaveBeenCalled();
1020 }),
1021 );
1022
1023 it.effect("leaves an override relay client alone", () =>
1024 Effect.gen(function* () {
1025 const install = vi.fn(() => Effect.die("unexpected install"));
1026 const spawner = ChildProcessSpawner.make(() =>
1027 Effect.gen(function* () {
1028 const handle = makeHandle({ pid: 4, onKill: () => {} });
1029 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1030 return handle;
1031 }),
1032 );
1033 const runtime = yield* buildCloudManagedEndpointRuntime(
1034 spawner,
1035 Layer.succeed(
1036 RelayClient.RelayClient,
1037 RelayClient.RelayClient.of({
1038 resolve: Effect.succeed({
1039 status: "available",
1040 executablePath: "/opt/cloudflared",
1041 source: "override",
1042 version: "2025.10.0",
1043 }),
1044 install: Effect.suspend(install),
1045 installWithProgress: () => Effect.die("unused"),
1046 pruneManagedVersions: Effect.void,
1047 }),
1048 ),
1049 );
1050 expect(
1051 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1052 ).toMatchObject({ status: "running", pid: 4 });
1053 yield* Effect.yieldNow;
1054 expect(install).not.toHaveBeenCalled();
1055 }),
1056 );
1057
1058 it.effect("retries a failed background install while the older connector keeps running", () =>
1059 Effect.gen(function* () {
1060 const olderClient = {
1061 status: "available",
1062 executablePath: "/managed/2025.9.0/cloudflared",
1063 source: "managed",
1064 version: "2025.9.0",
1065 } as const;
1066 const pinnedClient = {
1067 status: "available",
1068 executablePath: "/managed/pinned/cloudflared",
1069 source: "managed",
1070 version: RelayClient.CLOUDFLARED_VERSION,
1071 } as const;
1072 let installed = false;
1073 let installAttempts = 0;
1074 const spawned = yield* Queue.unbounded<string>();
1075 const spawner = ChildProcessSpawner.make((command) =>
1076 Effect.gen(function* () {
1077 yield* Queue.offer(
1078 spawned,
1079 ChildProcess.isStandardCommand(command) ? command.command : "",
1080 );
1081 const handle = makeHandle({ pid: 5, onKill: () => {} });
1082 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1083 return handle;
1084 }),
1085 );
1086 const runtime = yield* buildCloudManagedEndpointRuntime(
1087 spawner,
1088 Layer.succeed(
1089 RelayClient.RelayClient,
1090 RelayClient.RelayClient.of({
1091 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1092 install: Effect.suspend(() => {
1093 installAttempts += 1;
1094 if (installAttempts === 1) {
1095 // A real download fails some time after it starts.
1096 return Effect.sleep(Duration.seconds(30)).pipe(
1097 Effect.andThen(
1098 Effect.fail(
1099 new RelayClient.RelayClientInstallError({
1100 reason: "download_failed",
1101 message: "offline",
1102 }),
1103 ),
1104 ),
1105 );
1106 }
1107 installed = true;
1108 return Effect.succeed(pinnedClient);
1109 }),
1110 installWithProgress: () => Effect.die("unused"),
1111 pruneManagedVersions: Effect.void,
1112 }),
1113 ),
1114 );
1115
1116 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1117 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
1118 yield* TestClock.adjust(Duration.seconds(30));
1119 expect(installAttempts).toBe(1);
1120
1121 yield* TestClock.adjust(Duration.minutes(10));
1122 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
1123 expect(installAttempts).toBe(2);
1124 }),
1125 );
1126
1127 it.effect("keeps the older connector when the updated relay client fails to start", () =>
1128 Effect.gen(function* () {
1129 const olderClient = {
1130 status: "available",
1131 executablePath: "/managed/2025.9.0/cloudflared",
1132 source: "managed",
1133 version: "2025.9.0",
1134 } as const;
1135 const pinnedClient = {
1136 status: "available",
1137 executablePath: "/managed/pinned/cloudflared",
1138 source: "managed",
1139 version: RelayClient.CLOUDFLARED_VERSION,
1140 } as const;
1141 let installed = false;
1142 let olderKilled = false;
1143 const releaseInstall = yield* Deferred.make<void>();
1144 const pinnedAttempted = yield* Deferred.make<void>();
1145 const spawner = ChildProcessSpawner.make((command) =>
1146 Effect.gen(function* () {
1147 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1148 if (executable === pinnedClient.executablePath) {
1149 yield* Deferred.succeed(pinnedAttempted, undefined);
1150 return yield* PlatformError.systemError({
1151 _tag: "PermissionDenied",
1152 module: "ChildProcess",
1153 method: "spawn",
1154 });
1155 }
1156 const handle = makeHandle({
1157 pid: 6,
1158 onKill: () => {
1159 olderKilled = true;
1160 },
1161 });
1162 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1163 return handle;
1164 }),
1165 );
1166 const runtime = yield* buildCloudManagedEndpointRuntime(
1167 spawner,
1168 Layer.succeed(
1169 RelayClient.RelayClient,
1170 RelayClient.RelayClient.of({
1171 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1172 install: Deferred.await(releaseInstall).pipe(
1173 Effect.andThen(
1174 Effect.sync(() => {
1175 installed = true;
1176 return pinnedClient;
1177 }),
1178 ),
1179 ),
1180 installWithProgress: () => Effect.die("unused"),
1181 pruneManagedVersions: Effect.void,
1182 }),
1183 ),
1184 );
1185 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1186 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1187
1188 yield* Deferred.succeed(releaseInstall, undefined);
1189 yield* Deferred.await(pinnedAttempted);
1190 // The failed swap leaves the older connector active and running.
1191 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1192 expect(olderKilled).toBe(false);
1193 }),
1194 );
1195
1196 it.effect("requests recovery when the older connector exited during a failed swap", () =>
1197 Effect.gen(function* () {
1198 const olderClient = {
1199 status: "available",
1200 executablePath: "/managed/2025.9.0/cloudflared",
1201 source: "managed",
1202 version: "2025.9.0",
1203 } as const;
1204 const pinnedClient = {
1205 status: "available",
1206 executablePath: "/managed/pinned/cloudflared",
1207 source: "managed",
1208 version: RelayClient.CLOUDFLARED_VERSION,
1209 } as const;
1210 let installed = false;
1211 const releaseInstall = yield* Deferred.make<void>();
1212 const spawner = ChildProcessSpawner.make((command) =>
1213 Effect.gen(function* () {
1214 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1215 if (executable === pinnedClient.executablePath) {
1216 return yield* PlatformError.systemError({
1217 _tag: "PermissionDenied",
1218 module: "ChildProcess",
1219 method: "spawn",
1220 });
1221 }
1222 // The older connector has exited by the time the swap fails.
1223 const handle = makeHandle({ pid: 12, onKill: () => {}, isRunning: () => !installed });
1224 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1225 return handle;
1226 }),
1227 );
1228 const runtime = yield* buildCloudManagedEndpointRuntime(
1229 spawner,
1230 Layer.succeed(
1231 RelayClient.RelayClient,
1232 RelayClient.RelayClient.of({
1233 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1234 install: Deferred.await(releaseInstall).pipe(
1235 Effect.andThen(
1236 Effect.sync(() => {
1237 installed = true;
1238 return pinnedClient;
1239 }),
1240 ),
1241 ),
1242 installWithProgress: () => Effect.die("unused"),
1243 pruneManagedVersions: Effect.void,
1244 }),
1245 ),
1246 );
1247 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1248 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 12 });
1249
1250 yield* Deferred.succeed(releaseInstall, undefined);
1251 expect(Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
1252 }),
1253 );
1254
1255 it.effect("restarts a self-updated pinned-folder connector once the pin is reinstalled", () =>
1256 Effect.gen(function* () {
1257 const executablePath = "/managed/pinned/cloudflared";
1258 let version = "2026.9.3";
1259 const releaseInstall = yield* Deferred.make<void>();
1260 const spawned = yield* Queue.unbounded<string>();
1261 const spawner = ChildProcessSpawner.make(() =>
1262 Effect.gen(function* () {
1263 yield* Queue.offer(spawned, version);
1264 const handle = makeHandle({ pid: 7, onKill: () => {} });
1265 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1266 return handle;
1267 }),
1268 );
1269 const current = () =>
1270 ({ status: "available", executablePath, source: "managed", version }) as const;
1271 const runtime = yield* buildCloudManagedEndpointRuntime(
1272 spawner,
1273 Layer.succeed(
1274 RelayClient.RelayClient,
1275 RelayClient.RelayClient.of({
1276 resolve: Effect.sync(current),
1277 install: Deferred.await(releaseInstall).pipe(
1278 Effect.andThen(
1279 Effect.sync(() => {
1280 version = RelayClient.CLOUDFLARED_VERSION;
1281 return current();
1282 }),
1283 ),
1284 ),
1285 installWithProgress: () => Effect.die("unused"),
1286 pruneManagedVersions: Effect.void,
1287 }),
1288 ),
1289 );
1290
1291 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1292 expect(yield* Queue.take(spawned)).toBe("2026.9.3");
1293 yield* Deferred.succeed(releaseInstall, undefined);
1294 expect(yield* Queue.take(spawned)).toBe(RelayClient.CLOUDFLARED_VERSION);
1295 }),
1296 );
1297
1298 it.effect("retries a failed install when no relay client is installed", () =>
1299 Effect.gen(function* () {
1300 const pinnedClient = {
1301 status: "available",
1302 executablePath: "/managed/pinned/cloudflared",
1303 source: "managed",
1304 version: RelayClient.CLOUDFLARED_VERSION,
1305 } as const;
1306 let installed = false;
1307 let installAttempts = 0;
1308 const spawned = yield* Deferred.make<string>();
1309 const spawner = ChildProcessSpawner.make((command) =>
1310 Effect.gen(function* () {
1311 yield* Deferred.succeed(
1312 spawned,
1313 ChildProcess.isStandardCommand(command) ? command.command : "",
1314 );
1315 const handle = makeHandle({ pid: 9, onKill: () => {} });
1316 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1317 return handle;
1318 }),
1319 );
1320 const runtime = yield* buildCloudManagedEndpointRuntime(
1321 spawner,
1322 Layer.succeed(
1323 RelayClient.RelayClient,
1324 RelayClient.RelayClient.of({
1325 resolve: Effect.sync(() =>
1326 installed
1327 ? pinnedClient
1328 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
1329 ),
1330 install: Effect.suspend(() => {
1331 installAttempts += 1;
1332 if (installAttempts === 1) {
1333 return Effect.fail(
1334 new RelayClient.RelayClientInstallError({
1335 reason: "download_failed",
1336 message: "offline",
1337 }),
1338 );
1339 }
1340 installed = true;
1341 return Effect.succeed(pinnedClient);
1342 }),
1343 installWithProgress: () => Effect.die("unused"),
1344 pruneManagedVersions: Effect.void,
1345 }),
1346 ),
1347 );
1348
1349 expect(
1350 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1351 ).toMatchObject({ status: "failed", failure: "not-installed" });
1352 yield* Effect.yieldNow;
1353 expect(installAttempts).toBe(1);
1354
1355 yield* TestClock.adjust(Duration.minutes(10));
1356 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
1357 expect(installAttempts).toBe(2);
1358 }),
1359 );
1360
1361 it.effect("restarts on the pin when the first post-install probe failed", () =>
1362 Effect.gen(function* () {
1363 const olderClient = {
1364 status: "available",
1365 executablePath: "/managed/2025.9.0/cloudflared",
1366 source: "managed",
1367 version: "2025.9.0",
1368 } as const;
1369 const pinnedClient = {
1370 status: "available",
1371 executablePath: "/managed/pinned/cloudflared",
1372 source: "managed",
1373 version: RelayClient.CLOUDFLARED_VERSION,
1374 } as const;
1375 let installed = false;
1376 // The first resolve after the install misses the new binary, as when a
1377 // scanner briefly holds it; later resolves see it.
1378 let missedProbes = 0;
1379 const spawned = yield* Queue.unbounded<string>();
1380 const spawner = ChildProcessSpawner.make((command) =>
1381 Effect.gen(function* () {
1382 yield* Queue.offer(
1383 spawned,
1384 ChildProcess.isStandardCommand(command) ? command.command : "",
1385 );
1386 const handle = makeHandle({ pid: 10, onKill: () => {} });
1387 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1388 return handle;
1389 }),
1390 );
1391 const runtime = yield* buildCloudManagedEndpointRuntime(
1392 spawner,
1393 Layer.succeed(
1394 RelayClient.RelayClient,
1395 RelayClient.RelayClient.of({
1396 resolve: Effect.sync(() => {
1397 if (installed && missedProbes === 0) {
1398 missedProbes += 1;
1399 return olderClient;
1400 }
1401 return installed ? pinnedClient : olderClient;
1402 }),
1403 install: Effect.sync(() => {
1404 installed = true;
1405 return pinnedClient;
1406 }),
1407 installWithProgress: () => Effect.die("unused"),
1408 pruneManagedVersions: Effect.void,
1409 }),
1410 ),
1411 );
1412
1413 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1414 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
1415 yield* Effect.yieldNow;
1416 // The missed probe kept the older connector running.
1417 expect(Option.isNone(yield* Queue.poll(spawned))).toBe(true);
1418
1419 yield* TestClock.adjust(Duration.minutes(10));
1420 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
1421 }),
1422 );
1423
1424 it.effect("starts the connector when the pin landed but its first probe failed", () =>
1425 Effect.gen(function* () {
1426 const pinnedClient = {
1427 status: "available",
1428 executablePath: "/managed/pinned/cloudflared",
1429 source: "managed",
1430 version: RelayClient.CLOUDFLARED_VERSION,
1431 } as const;
1432 const missing = { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION };
1433 let installed = false;
1434 // The resolve right after the install misses the new binary.
1435 let missedProbes = 0;
1436 const spawned = yield* Deferred.make<string>();
1437 const spawner = ChildProcessSpawner.make((command) =>
1438 Effect.gen(function* () {
1439 yield* Deferred.succeed(
1440 spawned,
1441 ChildProcess.isStandardCommand(command) ? command.command : "",
1442 );
1443 const handle = makeHandle({ pid: 11, onKill: () => {} });
1444 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1445 return handle;
1446 }),
1447 );
1448 const runtime = yield* buildCloudManagedEndpointRuntime(
1449 spawner,
1450 Layer.succeed(
1451 RelayClient.RelayClient,
1452 RelayClient.RelayClient.of({
1453 resolve: Effect.sync(() => {
1454 if (!installed) return missing;
1455 if (missedProbes === 0) {
1456 missedProbes += 1;
1457 return missing;
1458 }
1459 return pinnedClient;
1460 }),
1461 install: Effect.sync(() => {
1462 installed = true;
1463 return pinnedClient;
1464 }),
1465 installWithProgress: () => Effect.die("unused"),
1466 pruneManagedVersions: Effect.void,
1467 }),
1468 ),
1469 );
1470
1471 expect(
1472 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1473 ).toMatchObject({ status: "failed", failure: "not-installed" });
1474 yield* Effect.yieldNow;
1475 expect(Option.isNone(yield* Deferred.poll(spawned))).toBe(true);
1476
1477 yield* TestClock.adjust(Duration.minutes(10));
1478 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
1479 }),
1480 );
1481});