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 restarts on 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 killed: Array<string> = [];
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: () => killed.push(executable),
882 ...(executable === pinnedClient.executablePath
883 ? { output: Stream.fromQueue(output) }
884 : {}),
885 });
886 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
887 return handle;
888 }),
889 );
890 const runtime = yield* buildCloudManagedEndpointRuntime(
891 spawner,
892 Layer.succeed(
893 RelayClient.RelayClient,
894 RelayClient.RelayClient.of({
895 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
896 install: Deferred.await(releaseInstall).pipe(
897 Effect.andThen(
898 Effect.sync(() => {
899 installed = true;
900 return pinnedClient;
901 }),
902 ),
903 ),
904 installWithProgress: () => Effect.die("unused"),
905 pruneManagedVersions: Deferred.succeed(pruned, undefined).pipe(Effect.asVoid),
906 }),
907 ),
908 );
909
910 const status = yield* runtime.applyConfig({
911 providerKind: "cloudflare_tunnel",
912 connectorToken: "token",
913 });
914 expect(status).toMatchObject({ status: "running", pid: 1 });
915 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
916
917 yield* Deferred.succeed(releaseInstall, undefined);
918 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
919 expect(killed).toEqual([olderClient.executablePath]);
920
921 yield* Queue.offer(
922 output,
923 new TextEncoder().encode(
924 "2026-10-08T00:00:00Z INF Registered tunnel connection connIndex=0\n",
925 ),
926 );
927 yield* Deferred.await(pruned);
928 }),
929 );
930
931 it.effect("installs a missing relay client in the background and then starts it", () =>
932 Effect.gen(function* () {
933 const pinnedClient = {
934 status: "available",
935 executablePath: "/managed/pinned/cloudflared",
936 source: "managed",
937 version: RelayClient.CLOUDFLARED_VERSION,
938 } as const;
939 let installed = false;
940 const spawned = yield* Deferred.make<string>();
941 const spawner = ChildProcessSpawner.make((command) =>
942 Effect.gen(function* () {
943 yield* Deferred.succeed(
944 spawned,
945 ChildProcess.isStandardCommand(command) ? command.command : "",
946 );
947 const handle = makeHandle({ pid: 3, onKill: () => {} });
948 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
949 return handle;
950 }),
951 );
952 const runtime = yield* buildCloudManagedEndpointRuntime(
953 spawner,
954 Layer.succeed(
955 RelayClient.RelayClient,
956 RelayClient.RelayClient.of({
957 resolve: Effect.sync(() =>
958 installed
959 ? pinnedClient
960 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
961 ),
962 install: Effect.sync(() => {
963 installed = true;
964 return pinnedClient;
965 }),
966 installWithProgress: () => Effect.die("unused"),
967 pruneManagedVersions: Effect.void,
968 }),
969 ),
970 );
971
972 const status = yield* runtime.applyConfig({
973 providerKind: "cloudflare_tunnel",
974 connectorToken: "token",
975 });
976 // The first attempt reports the gap; the install then starts the connector itself.
977 expect(status).toMatchObject({ status: "failed", failure: "not-installed" });
978 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
979 }),
980 );
981
982 it.effect("leaves a PATH relay client alone", () =>
983 Effect.gen(function* () {
984 const install = vi.fn(() => Effect.die("unexpected install"));
985 const spawner = ChildProcessSpawner.make(() =>
986 Effect.gen(function* () {
987 const handle = makeHandle({ pid: 8, onKill: () => {} });
988 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
989 return handle;
990 }),
991 );
992 const runtime = yield* buildCloudManagedEndpointRuntime(
993 spawner,
994 Layer.succeed(
995 RelayClient.RelayClient,
996 RelayClient.RelayClient.of({
997 resolve: Effect.succeed({
998 status: "available",
999 executablePath: "/opt/homebrew/bin/cloudflared",
1000 source: "path",
1001 version: "2026.10.0",
1002 }),
1003 install: Effect.suspend(install),
1004 installWithProgress: () => Effect.die("unused"),
1005 pruneManagedVersions: Effect.void,
1006 }),
1007 ),
1008 );
1009 expect(
1010 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1011 ).toMatchObject({ status: "running", pid: 8 });
1012 yield* TestClock.adjust(Duration.minutes(30));
1013 expect(install).not.toHaveBeenCalled();
1014 }),
1015 );
1016
1017 it.effect("leaves an override relay client alone", () =>
1018 Effect.gen(function* () {
1019 const install = vi.fn(() => Effect.die("unexpected install"));
1020 const spawner = ChildProcessSpawner.make(() =>
1021 Effect.gen(function* () {
1022 const handle = makeHandle({ pid: 4, onKill: () => {} });
1023 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1024 return handle;
1025 }),
1026 );
1027 const runtime = yield* buildCloudManagedEndpointRuntime(
1028 spawner,
1029 Layer.succeed(
1030 RelayClient.RelayClient,
1031 RelayClient.RelayClient.of({
1032 resolve: Effect.succeed({
1033 status: "available",
1034 executablePath: "/opt/cloudflared",
1035 source: "override",
1036 version: "2025.10.0",
1037 }),
1038 install: Effect.suspend(install),
1039 installWithProgress: () => Effect.die("unused"),
1040 pruneManagedVersions: Effect.void,
1041 }),
1042 ),
1043 );
1044 expect(
1045 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1046 ).toMatchObject({ status: "running", pid: 4 });
1047 yield* Effect.yieldNow;
1048 expect(install).not.toHaveBeenCalled();
1049 }),
1050 );
1051
1052 it.effect("retries a failed background install while the older connector keeps running", () =>
1053 Effect.gen(function* () {
1054 const olderClient = {
1055 status: "available",
1056 executablePath: "/managed/2025.9.0/cloudflared",
1057 source: "managed",
1058 version: "2025.9.0",
1059 } as const;
1060 const pinnedClient = {
1061 status: "available",
1062 executablePath: "/managed/pinned/cloudflared",
1063 source: "managed",
1064 version: RelayClient.CLOUDFLARED_VERSION,
1065 } as const;
1066 let installed = false;
1067 let installAttempts = 0;
1068 const spawned = yield* Queue.unbounded<string>();
1069 const spawner = ChildProcessSpawner.make((command) =>
1070 Effect.gen(function* () {
1071 yield* Queue.offer(
1072 spawned,
1073 ChildProcess.isStandardCommand(command) ? command.command : "",
1074 );
1075 const handle = makeHandle({ pid: 5, onKill: () => {} });
1076 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1077 return handle;
1078 }),
1079 );
1080 const runtime = yield* buildCloudManagedEndpointRuntime(
1081 spawner,
1082 Layer.succeed(
1083 RelayClient.RelayClient,
1084 RelayClient.RelayClient.of({
1085 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1086 install: Effect.suspend(() => {
1087 installAttempts += 1;
1088 if (installAttempts === 1) {
1089 // A real download fails some time after it starts.
1090 return Effect.sleep(Duration.seconds(30)).pipe(
1091 Effect.andThen(
1092 Effect.fail(
1093 new RelayClient.RelayClientInstallError({
1094 reason: "download_failed",
1095 message: "offline",
1096 }),
1097 ),
1098 ),
1099 );
1100 }
1101 installed = true;
1102 return Effect.succeed(pinnedClient);
1103 }),
1104 installWithProgress: () => Effect.die("unused"),
1105 pruneManagedVersions: Effect.void,
1106 }),
1107 ),
1108 );
1109
1110 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1111 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
1112 yield* TestClock.adjust(Duration.seconds(30));
1113 expect(installAttempts).toBe(1);
1114
1115 yield* TestClock.adjust(Duration.minutes(10));
1116 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
1117 expect(installAttempts).toBe(2);
1118 }),
1119 );
1120
1121 it.effect("requests recovery when the updated relay client fails to start", () =>
1122 Effect.gen(function* () {
1123 const olderClient = {
1124 status: "available",
1125 executablePath: "/managed/2025.9.0/cloudflared",
1126 source: "managed",
1127 version: "2025.9.0",
1128 } as const;
1129 const pinnedClient = {
1130 status: "available",
1131 executablePath: "/managed/pinned/cloudflared",
1132 source: "managed",
1133 version: RelayClient.CLOUDFLARED_VERSION,
1134 } as const;
1135 let installed = false;
1136 const releaseInstall = yield* Deferred.make<void>();
1137 const spawner = ChildProcessSpawner.make((command) =>
1138 Effect.gen(function* () {
1139 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1140 if (executable === pinnedClient.executablePath) {
1141 return yield* PlatformError.systemError({
1142 _tag: "PermissionDenied",
1143 module: "ChildProcess",
1144 method: "spawn",
1145 });
1146 }
1147 const handle = makeHandle({ pid: 6, onKill: () => {} });
1148 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1149 return handle;
1150 }),
1151 );
1152 const runtime = yield* buildCloudManagedEndpointRuntime(
1153 spawner,
1154 Layer.succeed(
1155 RelayClient.RelayClient,
1156 RelayClient.RelayClient.of({
1157 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1158 install: Deferred.await(releaseInstall).pipe(
1159 Effect.andThen(
1160 Effect.sync(() => {
1161 installed = true;
1162 return pinnedClient;
1163 }),
1164 ),
1165 ),
1166 installWithProgress: () => Effect.die("unused"),
1167 pruneManagedVersions: Effect.void,
1168 }),
1169 ),
1170 );
1171 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1172 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1173
1174 yield* Deferred.succeed(releaseInstall, undefined);
1175 expect(Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
1176 }),
1177 );
1178
1179 it.effect("restarts a self-updated pinned-folder connector once the pin is reinstalled", () =>
1180 Effect.gen(function* () {
1181 const executablePath = "/managed/pinned/cloudflared";
1182 let version = "2026.9.3";
1183 const releaseInstall = yield* Deferred.make<void>();
1184 const spawned = yield* Queue.unbounded<string>();
1185 const spawner = ChildProcessSpawner.make(() =>
1186 Effect.gen(function* () {
1187 yield* Queue.offer(spawned, version);
1188 const handle = makeHandle({ pid: 7, onKill: () => {} });
1189 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1190 return handle;
1191 }),
1192 );
1193 const current = () =>
1194 ({ status: "available", executablePath, source: "managed", version }) as const;
1195 const runtime = yield* buildCloudManagedEndpointRuntime(
1196 spawner,
1197 Layer.succeed(
1198 RelayClient.RelayClient,
1199 RelayClient.RelayClient.of({
1200 resolve: Effect.sync(current),
1201 install: Deferred.await(releaseInstall).pipe(
1202 Effect.andThen(
1203 Effect.sync(() => {
1204 version = RelayClient.CLOUDFLARED_VERSION;
1205 return current();
1206 }),
1207 ),
1208 ),
1209 installWithProgress: () => Effect.die("unused"),
1210 pruneManagedVersions: Effect.void,
1211 }),
1212 ),
1213 );
1214
1215 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1216 expect(yield* Queue.take(spawned)).toBe("2026.9.3");
1217 yield* Deferred.succeed(releaseInstall, undefined);
1218 expect(yield* Queue.take(spawned)).toBe(RelayClient.CLOUDFLARED_VERSION);
1219 }),
1220 );
1221
1222 it.effect("retries a failed install when no relay client is installed", () =>
1223 Effect.gen(function* () {
1224 const pinnedClient = {
1225 status: "available",
1226 executablePath: "/managed/pinned/cloudflared",
1227 source: "managed",
1228 version: RelayClient.CLOUDFLARED_VERSION,
1229 } as const;
1230 let installed = false;
1231 let installAttempts = 0;
1232 const spawned = yield* Deferred.make<string>();
1233 const spawner = ChildProcessSpawner.make((command) =>
1234 Effect.gen(function* () {
1235 yield* Deferred.succeed(
1236 spawned,
1237 ChildProcess.isStandardCommand(command) ? command.command : "",
1238 );
1239 const handle = makeHandle({ pid: 9, onKill: () => {} });
1240 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1241 return handle;
1242 }),
1243 );
1244 const runtime = yield* buildCloudManagedEndpointRuntime(
1245 spawner,
1246 Layer.succeed(
1247 RelayClient.RelayClient,
1248 RelayClient.RelayClient.of({
1249 resolve: Effect.sync(() =>
1250 installed
1251 ? pinnedClient
1252 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
1253 ),
1254 install: Effect.suspend(() => {
1255 installAttempts += 1;
1256 if (installAttempts === 1) {
1257 return Effect.fail(
1258 new RelayClient.RelayClientInstallError({
1259 reason: "download_failed",
1260 message: "offline",
1261 }),
1262 );
1263 }
1264 installed = true;
1265 return Effect.succeed(pinnedClient);
1266 }),
1267 installWithProgress: () => Effect.die("unused"),
1268 pruneManagedVersions: Effect.void,
1269 }),
1270 ),
1271 );
1272
1273 expect(
1274 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1275 ).toMatchObject({ status: "failed", failure: "not-installed" });
1276 yield* Effect.yieldNow;
1277 expect(installAttempts).toBe(1);
1278
1279 yield* TestClock.adjust(Duration.minutes(10));
1280 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
1281 expect(installAttempts).toBe(2);
1282 }),
1283 );
1284
1285 it.effect("restarts on the pin when the first post-install probe failed", () =>
1286 Effect.gen(function* () {
1287 const olderClient = {
1288 status: "available",
1289 executablePath: "/managed/2025.9.0/cloudflared",
1290 source: "managed",
1291 version: "2025.9.0",
1292 } as const;
1293 const pinnedClient = {
1294 status: "available",
1295 executablePath: "/managed/pinned/cloudflared",
1296 source: "managed",
1297 version: RelayClient.CLOUDFLARED_VERSION,
1298 } as const;
1299 let installed = false;
1300 // The first resolve after the install misses the new binary, as when a
1301 // scanner briefly holds it; later resolves see it.
1302 let missedProbes = 0;
1303 const spawned = yield* Queue.unbounded<string>();
1304 const spawner = ChildProcessSpawner.make((command) =>
1305 Effect.gen(function* () {
1306 yield* Queue.offer(
1307 spawned,
1308 ChildProcess.isStandardCommand(command) ? command.command : "",
1309 );
1310 const handle = makeHandle({ pid: 10, onKill: () => {} });
1311 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1312 return handle;
1313 }),
1314 );
1315 const runtime = yield* buildCloudManagedEndpointRuntime(
1316 spawner,
1317 Layer.succeed(
1318 RelayClient.RelayClient,
1319 RelayClient.RelayClient.of({
1320 resolve: Effect.sync(() => {
1321 if (installed && missedProbes === 0) {
1322 missedProbes += 1;
1323 return olderClient;
1324 }
1325 return installed ? pinnedClient : olderClient;
1326 }),
1327 install: Effect.sync(() => {
1328 installed = true;
1329 return pinnedClient;
1330 }),
1331 installWithProgress: () => Effect.die("unused"),
1332 pruneManagedVersions: Effect.void,
1333 }),
1334 ),
1335 );
1336
1337 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1338 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
1339 yield* Effect.yieldNow;
1340 // The missed probe kept the older connector running.
1341 expect(Option.isNone(yield* Queue.poll(spawned))).toBe(true);
1342
1343 yield* TestClock.adjust(Duration.minutes(10));
1344 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
1345 }),
1346 );
1347
1348 it.effect("starts the connector when the pin landed but its first probe failed", () =>
1349 Effect.gen(function* () {
1350 const pinnedClient = {
1351 status: "available",
1352 executablePath: "/managed/pinned/cloudflared",
1353 source: "managed",
1354 version: RelayClient.CLOUDFLARED_VERSION,
1355 } as const;
1356 const missing = { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION };
1357 let installed = false;
1358 // The resolve right after the install misses the new binary.
1359 let missedProbes = 0;
1360 const spawned = yield* Deferred.make<string>();
1361 const spawner = ChildProcessSpawner.make((command) =>
1362 Effect.gen(function* () {
1363 yield* Deferred.succeed(
1364 spawned,
1365 ChildProcess.isStandardCommand(command) ? command.command : "",
1366 );
1367 const handle = makeHandle({ pid: 11, onKill: () => {} });
1368 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1369 return handle;
1370 }),
1371 );
1372 const runtime = yield* buildCloudManagedEndpointRuntime(
1373 spawner,
1374 Layer.succeed(
1375 RelayClient.RelayClient,
1376 RelayClient.RelayClient.of({
1377 resolve: Effect.sync(() => {
1378 if (!installed) return missing;
1379 if (missedProbes === 0) {
1380 missedProbes += 1;
1381 return missing;
1382 }
1383 return pinnedClient;
1384 }),
1385 install: Effect.sync(() => {
1386 installed = true;
1387 return pinnedClient;
1388 }),
1389 installWithProgress: () => Effect.die("unused"),
1390 pruneManagedVersions: Effect.void,
1391 }),
1392 ),
1393 );
1394
1395 expect(
1396 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" }),
1397 ).toMatchObject({ status: "failed", failure: "not-installed" });
1398 yield* Effect.yieldNow;
1399 expect(Option.isNone(yield* Deferred.poll(spawned))).toBe(true);
1400
1401 yield* TestClock.adjust(Duration.minutes(10));
1402 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
1403 }),
1404 );
1405});