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 }),
33);
34
35const runtimeDependencies = (
36 spawner: ReturnType<typeof ChildProcessSpawner.make>,
37 relayClientLayer = layerRelayClientAvailable,
38) =>
39 Layer.mergeAll(
40 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
41 relayClientLayer,
42 Layer.mock(ServerSecretStore.ServerSecretStore)({
43 get: () => Effect.succeedNone,
44 }),
45 );
46
47const buildCloudManagedEndpointRuntime = (
48 spawner: ReturnType<typeof ChildProcessSpawner.make>,
49 relayClientLayer = layerRelayClientAvailable,
50) =>
51 Effect.gen(function* () {
52 const context = yield* Layer.build(
53 ManagedEndpointRuntime.layer.pipe(
54 Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
55 ),
56 );
57 return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
58 Effect.provide(context),
59 );
60 });
61
62function makeHandle(input: {
63 readonly pid: number;
64 readonly onKill: () => void;
65 readonly isRunning?: () => boolean;
66 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
67 readonly output?: Stream.Stream<Uint8Array>;
68}) {
69 return ChildProcessSpawner.makeHandle({
70 pid: ChildProcessSpawner.ProcessId(input.pid),
71 exitCode: input.exitCode ?? Effect.never,
72 isRunning: Effect.sync(() => input.isRunning?.() ?? true),
73 kill: () =>
74 Effect.sync(() => {
75 input.onKill();
76 }),
77 unref: Effect.succeed(Effect.void),
78 stdin: Sink.drain,
79 stdout: Stream.empty,
80 stderr: Stream.empty,
81 all: input.output ?? Stream.empty,
82 getInputFd: () => Sink.drain,
83 getOutputFd: () => Stream.empty,
84 });
85}
86
87describe("CloudManagedEndpointRuntime", () => {
88 it("retries connector startup failures but stops for unsupported runtimes", () => {
89 expect(
90 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({
91 status: "failed",
92 failure: "not-installed",
93 reason: "The relay client is not installed.",
94 }),
95 ).toBe(true);
96 expect(
97 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({
98 status: "failed",
99 failure: "spawn-failed",
100 reason: "spawn failed",
101 }),
102 ).toBe(true);
103 expect(
104 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({
105 status: "failed",
106 failure: "unsupported-platform",
107 reason: "Relay client is unsupported on linux-arm.",
108 }),
109 ).toBe(false);
110 expect(
111 ManagedEndpointRuntime.isRetryableManagedEndpointRuntimeStatus({ status: "unsupported" }),
112 ).toBe(false);
113 });
114
115 it.effect("serializes updates to persisted cloud link state", () =>
116 Effect.gen(function* () {
117 const firstEntered = yield* Deferred.make<void>();
118 const releaseFirst = yield* Deferred.make<void>();
119 const secondEntered = yield* Deferred.make<void>();
120 const runtime = yield* buildCloudManagedEndpointRuntime(
121 ChildProcessSpawner.make(() => Effect.die("unused")),
122 );
123
124 const first = yield* runtime
125 .withLinkStateLock(
126 Deferred.succeed(firstEntered, undefined).pipe(
127 Effect.andThen(Deferred.await(releaseFirst)),
128 ),
129 )
130 .pipe(Effect.forkChild);
131 yield* Deferred.await(firstEntered);
132
133 const second = yield* runtime
134 .withLinkStateLock(Deferred.succeed(secondEntered, undefined))
135 .pipe(Effect.forkChild);
136 expect(yield* Deferred.isDone(secondEntered)).toBe(false);
137
138 yield* Deferred.succeed(releaseFirst, undefined);
139 yield* Fiber.join(first);
140 yield* Fiber.join(second);
141 expect(yield* Deferred.isDone(secondEntered)).toBe(true);
142 }),
143 );
144
145 it("classifies Cloudflare connection and warning output", () => {
146 expect(
147 ManagedEndpointRuntime.classifyRelayClientOutput(
148 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
149 ),
150 ).toBe("connected");
151 expect(
152 ManagedEndpointRuntime.classifyRelayClientOutput(
153 "2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
154 ),
155 ).toBe("warning");
156 expect(
157 ManagedEndpointRuntime.classifyRelayClientOutput(
158 "2026-06-17T02:00:00Z INF Starting metrics server",
159 ),
160 ).toBe("debug");
161 // FTL (fatal) and PNC (panic) are more severe than ERR and must surface.
162 expect(
163 ManagedEndpointRuntime.classifyRelayClientOutput(
164 "2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",
165 ),
166 ).toBe("warning");
167 expect(
168 ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),
169 ).toBe("warning");
170 });
171
172 it("recognizes tunnel authorization failures without matching ordinary transport errors", () => {
173 expect(
174 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
175 '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',
176 ),
177 ).toBe(true);
178 expect(
179 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
180 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="Unauthorized: Record for tunnel not found" connIndex=0',
181 ),
182 ).toBe(true);
183 expect(
184 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
185 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="Unauthorized: Invalid tunnel secret" connIndex=0',
186 ),
187 ).toBe(true);
188 // Seen in production on 2026-10-06 after the relay deleted an idle tunnel.
189 expect(
190 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
191 '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',
192 ),
193 ).toBe(true);
194 expect(
195 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
196 '2026-10-06T12:00:00Z ERR Register tunnel error from server side error="Tunnel not found" connIndex=0',
197 ),
198 ).toBe(true);
199 expect(
200 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
201 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="connection timed out" connIndex=0',
202 ),
203 ).toBe(false);
204 expect(
205 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
206 '2026-06-17T02:00:00Z ERR Failed to serve tunnel connection error="Unauthorized: Tunnel not found" connIndex=0',
207 ),
208 ).toBe(false);
209 });
210
211 it.effect("keeps recovery requests sent before the server starts consuming them", () =>
212 Effect.gen(function* () {
213 const runtime = yield* buildCloudManagedEndpointRuntime(
214 ChildProcessSpawner.make(() => Effect.die("unused")),
215 );
216 const config = {
217 providerKind: "cloudflare_tunnel" as const,
218 connectorToken: "token",
219 tunnelId: "tunnel-1",
220 };
221
222 yield* runtime.requestRecovery(config);
223
224 expect(Option.getOrNull(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
225 }),
226 );
227
228 it.effect("signals each registered tunnel connection", () =>
229 Effect.gen(function* () {
230 const output = yield* Queue.unbounded<Uint8Array>();
231 const spawner = ChildProcessSpawner.make(() =>
232 Effect.gen(function* () {
233 const handle = makeHandle({
234 pid: 700,
235 onKill: () => {},
236 output: Stream.fromQueue(output),
237 });
238 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
239 return handle;
240 }),
241 );
242 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
243 yield* runtime.applyConfig({
244 providerKind: "cloudflare_tunnel",
245 connectorToken: "token",
246 tunnelId: "tunnel-1",
247 });
248 yield* Queue.offer(
249 output,
250 new TextEncoder().encode(
251 "2026-10-04T06:30:43Z INF Registered tunnel connection connIndex=0 event=0\n",
252 ),
253 );
254 expect(Option.isSome(yield* Stream.runHead(runtime.tunnelConnected))).toBe(true);
255 }),
256 );
257
258 it.effect("recovers a rejected tunnel without waiting for the connector to exit", () =>
259 Effect.gen(function* () {
260 const output = yield* Queue.unbounded<Uint8Array>();
261 const firstBatchObserved = yield* Deferred.make<void>();
262 const secondBatchObserved = yield* Deferred.make<void>();
263 const recoveryRequested = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
264 const recoveryRetried = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
265 let recoveryRequestCount = 0;
266 const spawned: Array<number> = [];
267 const encoder = new TextEncoder();
268 const connectorOutput = Stream.fromQueue(output).pipe(
269 Stream.tap((chunk) => {
270 const line = new TextDecoder().decode(chunk);
271 if (line === "first checkpoint\n") {
272 return Deferred.succeed(firstBatchObserved, undefined).pipe(Effect.asVoid);
273 }
274 if (line === "second checkpoint\n") {
275 return Deferred.succeed(secondBatchObserved, undefined).pipe(Effect.asVoid);
276 }
277 return Effect.void;
278 }),
279 );
280 const spawner = ChildProcessSpawner.make(() =>
281 Effect.gen(function* () {
282 const pid = 600;
283 spawned.push(pid);
284 const handle = makeHandle({ pid, onKill: () => {}, output: connectorOutput });
285 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
286 return handle;
287 }),
288 );
289 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
290 const config = {
291 providerKind: "cloudflare_tunnel" as const,
292 connectorToken: "token",
293 tunnelId: "deleted-tunnel",
294 };
295 const rejectedLine =
296 '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';
297
298 yield* runtime.recoveryRequests.pipe(
299 Stream.runForEach((requested) => {
300 recoveryRequestCount += 1;
301 return Deferred.succeed(
302 recoveryRequestCount === 1 ? recoveryRequested : recoveryRetried,
303 requested,
304 ).pipe(Effect.asVoid);
305 }),
306 Effect.forkChild,
307 );
308 yield* runtime.applyConfig(config);
309
310 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(3)));
311 yield* Queue.offer(output, encoder.encode("first checkpoint\n"));
312 yield* Deferred.await(firstBatchObserved);
313 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
314
315 yield* Queue.offer(
316 output,
317 encoder.encode(
318 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0\n" +
319 rejectedLine.repeat(3),
320 ),
321 );
322 yield* Queue.offer(output, encoder.encode("second checkpoint\n"));
323 yield* Deferred.await(secondBatchObserved);
324 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
325
326 yield* Queue.offer(output, encoder.encode(rejectedLine));
327
328 expect(yield* Deferred.await(recoveryRequested)).toEqual(config);
329
330 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(4)));
331
332 expect(yield* Deferred.await(recoveryRetried)).toEqual(config);
333 expect(spawned).toEqual([600]);
334 }),
335 );
336
337 it.effect("requests recovery while the connector never registers a connection", () =>
338 Effect.gen(function* () {
339 const output = yield* Queue.unbounded<Uint8Array>();
340 const spawner = ChildProcessSpawner.make(() =>
341 Effect.gen(function* () {
342 const handle = makeHandle({
343 pid: 800,
344 onKill: () => {},
345 output: Stream.fromQueue(output),
346 });
347 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
348 return handle;
349 }),
350 );
351 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
352 const requests = yield* Queue.unbounded<RelayManagedEndpointRuntimeConfig>();
353 yield* runtime.recoveryRequests.pipe(
354 Stream.runForEach((config) => Queue.offer(requests, config)),
355 Effect.forkChild,
356 );
357 const config = {
358 providerKind: "cloudflare_tunnel" as const,
359 connectorToken: "token",
360 tunnelId: "silently-deleted",
361 };
362 yield* runtime.applyConfig(config);
363
364 yield* TestClock.adjust(Duration.minutes(2));
365 expect(yield* Queue.size(requests)).toBe(0);
366 yield* TestClock.adjust(Duration.minutes(1));
367 expect(yield* Queue.take(requests)).toEqual(config);
368 // Still unconnected, so it asks again.
369 yield* TestClock.adjust(Duration.minutes(3));
370 expect(yield* Queue.take(requests)).toEqual(config);
371 }).pipe(Effect.provide(TestClock.layer())),
372 );
373
374 it.effect("does not request recovery once the connector has connected", () =>
375 Effect.gen(function* () {
376 const output = yield* Queue.unbounded<Uint8Array>();
377 const spawner = ChildProcessSpawner.make(() =>
378 Effect.gen(function* () {
379 const handle = makeHandle({
380 pid: 801,
381 onKill: () => {},
382 output: Stream.fromQueue(output),
383 });
384 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
385 return handle;
386 }),
387 );
388 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
389 const requests = yield* Queue.unbounded<RelayManagedEndpointRuntimeConfig>();
390 yield* runtime.recoveryRequests.pipe(
391 Stream.runForEach((config) => Queue.offer(requests, config)),
392 Effect.forkChild,
393 );
394 yield* runtime.applyConfig({
395 providerKind: "cloudflare_tunnel",
396 connectorToken: "token",
397 tunnelId: "tunnel-1",
398 });
399 yield* Queue.offer(
400 output,
401 new TextEncoder().encode(
402 "2026-10-06T00:00:00Z INF Registered tunnel connection connIndex=0\n",
403 ),
404 );
405 yield* Stream.runHead(runtime.tunnelConnected);
406
407 yield* TestClock.adjust(Duration.minutes(10));
408 expect(yield* Queue.size(requests)).toBe(0);
409 }).pipe(Effect.provide(TestClock.layer())),
410 );
411
412 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
413 Effect.gen(function* () {
414 const spawned: Array<ChildProcess.StandardCommand> = [];
415 const killed: Array<number> = [];
416 let nextPid = 100;
417 const spawner = ChildProcessSpawner.make((command) =>
418 Effect.gen(function* () {
419 if (!ChildProcess.isStandardCommand(command)) {
420 throw new Error("Expected standard command.");
421 }
422 spawned.push(command);
423 const pid = nextPid;
424 nextPid += 1;
425 const handle = makeHandle({
426 pid,
427 onKill: () => {
428 killed.push(pid);
429 },
430 });
431 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
432 return handle;
433 }),
434 );
435 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
436
437 yield* runtime.applyConfig({
438 providerKind: "cloudflare_tunnel",
439 connectorToken: "token-1",
440 tunnelId: "tunnel-1",
441 tunnelName: "t3-code-env-1",
442 });
443 yield* runtime.applyConfig({
444 providerKind: "cloudflare_tunnel",
445 connectorToken: "token-1",
446 tunnelId: "tunnel-1",
447 tunnelName: "t3-code-env-1",
448 });
449 yield* runtime.applyConfig({
450 providerKind: "cloudflare_tunnel",
451 connectorToken: "token-2",
452 tunnelId: "tunnel-1",
453 tunnelName: "t3-code-env-1",
454 });
455 const stopped = yield* runtime.applyConfig(null);
456
457 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
458 expect(spawned.map((command) => command.args)).toEqual([
459 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
460 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
461 ]);
462 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
463 "token-1",
464 "token-2",
465 ]);
466 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
467 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
468 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
469 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
470 expect(killed).toEqual([100, 101]);
471 expect(stopped).toEqual({ status: "disabled" });
472 }),
473 );
474
475 it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>
476 Effect.gen(function* () {
477 const killed: Array<number> = [];
478 const spawner = ChildProcessSpawner.make(() =>
479 Effect.gen(function* () {
480 const handle = makeHandle({
481 pid: 200,
482 onKill: () => {
483 killed.push(200);
484 },
485 });
486 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
487 return handle;
488 }),
489 );
490 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
491
492 const started = yield* runtime.applyConfig({
493 providerKind: "cloudflare_tunnel",
494 connectorToken: "token",
495 });
496 const unsupported = yield* runtime.applyConfig({
497 providerKind: "manual",
498 connectorToken: "manual-token",
499 });
500
501 expect(started.status).toBe("running");
502 expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
503 expect(killed).toEqual([200]);
504 }),
505 );
506
507 it.effect("restarts the connector when the active process has exited", () =>
508 Effect.gen(function* () {
509 const spawned: Array<number> = [];
510 const killed: Array<number> = [];
511 let firstRunning = true;
512 const spawner = ChildProcessSpawner.make(() =>
513 Effect.gen(function* () {
514 const pid = spawned.length === 0 ? 300 : 301;
515 spawned.push(pid);
516 const handle = makeHandle({
517 pid,
518 isRunning: () => (pid === 300 ? firstRunning : true),
519 onKill: () => {
520 killed.push(pid);
521 },
522 });
523 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
524 return handle;
525 }),
526 );
527 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
528 const config = {
529 providerKind: "cloudflare_tunnel" as const,
530 connectorToken: "token",
531 tunnelId: "tunnel-1",
532 };
533
534 const first = yield* runtime.applyConfig(config);
535 firstRunning = false;
536 const second = yield* runtime.applyConfig(config);
537
538 expect(first).toMatchObject({ status: "running", pid: 300 });
539 expect(second).toMatchObject({ status: "running", pid: 301 });
540 expect(spawned).toEqual([300, 301]);
541 expect(killed).toEqual([300]);
542 }),
543 );
544
545 it.effect("supervises the active connector and restarts it after process exit", () =>
546 Effect.gen(function* () {
547 const spawned: Array<number> = [];
548 const killed: Array<number> = [];
549 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
550 const secondSpawned = yield* Deferred.make<void>();
551 const spawner = ChildProcessSpawner.make(() =>
552 Effect.gen(function* () {
553 const pid = spawned.length === 0 ? 400 : 401;
554 spawned.push(pid);
555 if (pid === 401) {
556 yield* Deferred.succeed(secondSpawned, undefined);
557 }
558 const handle = makeHandle({
559 pid,
560 exitCode:
561 pid === 400
562 ? Deferred.await(firstExit)
563 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
564 onKill: () => {
565 killed.push(pid);
566 },
567 });
568 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
569 return handle;
570 }),
571 );
572 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
573
574 const started = yield* runtime.applyConfig({
575 providerKind: "cloudflare_tunnel",
576 connectorToken: "token",
577 tunnelId: "tunnel-1",
578 });
579 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
580 yield* Deferred.await(secondSpawned);
581
582 expect(started).toMatchObject({ status: "running", pid: 400 });
583 expect(spawned).toEqual([400, 401]);
584 expect(killed).toEqual([400]);
585 }),
586 );
587
588 const makeCrashLoopSpawner = (basePid: number, slots: number) =>
589 Effect.gen(function* () {
590 const spawned: Array<number> = [];
591 const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];
592 const spawnSignals: Array<Deferred.Deferred<void>> = [];
593 for (let index = 0; index < slots; index += 1) {
594 exits.push(yield* Deferred.make<ChildProcessSpawner.ExitCode>());
595 spawnSignals.push(yield* Deferred.make<void>());
596 }
597 const spawner = ChildProcessSpawner.make(() =>
598 Effect.gen(function* () {
599 const index = spawned.length;
600 spawned.push(basePid + index);
601 yield* Deferred.succeed(spawnSignals[index]!, undefined);
602 const handle = makeHandle({
603 pid: basePid + index,
604 exitCode: Deferred.await(exits[index]!),
605 onKill: () => {},
606 });
607 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
608 return handle;
609 }),
610 );
611 return { spawner, spawned, exits, spawnSignals };
612 });
613
614 it.effect("backs off restarts while the connector crash-loops", () =>
615 Effect.gen(function* () {
616 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(600, 4);
617 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
618
619 yield* runtime.applyConfig({
620 providerKind: "cloudflare_tunnel",
621 connectorToken: "token",
622 tunnelId: "tunnel-1",
623 });
624 expect(spawned).toEqual([600]);
625
626 // The first crash restarts immediately.
627 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
628 yield* Deferred.await(spawnSignals[1]!);
629 expect(spawned).toEqual([600, 601]);
630
631 // The second rapid crash waits out the base delay before restarting.
632 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
633 yield* TestClock.adjust(Duration.millis(999));
634 expect(spawned).toEqual([600, 601]);
635 yield* TestClock.adjust(Duration.millis(1));
636 yield* Deferred.await(spawnSignals[2]!);
637 expect(spawned).toEqual([600, 601, 602]);
638
639 // The third rapid crash doubles the delay.
640 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
641 yield* TestClock.adjust(Duration.millis(1999));
642 expect(spawned).toEqual([600, 601, 602]);
643 yield* TestClock.adjust(Duration.millis(1));
644 yield* Deferred.await(spawnSignals[3]!);
645 expect(spawned).toEqual([600, 601, 602, 603]);
646 }).pipe(Effect.provide(TestClock.layer())),
647 );
648
649 it.effect("resets the backoff after the connector runs stably", () =>
650 Effect.gen(function* () {
651 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(700, 5);
652 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
653
654 yield* runtime.applyConfig({
655 providerKind: "cloudflare_tunnel",
656 connectorToken: "token",
657 });
658
659 // One rapid crash arms the backoff.
660 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
661 yield* Deferred.await(spawnSignals[1]!);
662
663 // The replacement stays up past the stable-uptime window, so its exit
664 // restarts immediately and the backoff starts over.
665 yield* TestClock.adjust(Duration.millis(30_000));
666 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
667 yield* Deferred.await(spawnSignals[2]!);
668 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
669 yield* Deferred.await(spawnSignals[3]!);
670
671 // The next rapid crash waits the base delay again, not a doubled one.
672 yield* Deferred.succeed(exits[3]!, ChildProcessSpawner.ExitCode(1));
673 yield* TestClock.adjust(Duration.millis(999));
674 expect(spawned).toEqual([700, 701, 702, 703]);
675 yield* TestClock.adjust(Duration.millis(1));
676 yield* Deferred.await(spawnSignals[4]!);
677 expect(spawned).toEqual([700, 701, 702, 703, 704]);
678 }).pipe(Effect.provide(TestClock.layer())),
679 );
680
681 it.effect("a recovery that returns the same config keeps the crash backoff", () =>
682 Effect.gen(function* () {
683 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(900, 4);
684 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
685 const config = {
686 providerKind: "cloudflare_tunnel" as const,
687 connectorToken: "same-token",
688 tunnelId: "same-tunnel",
689 };
690 // The startup consumer re-applies whatever the relay hands back. When the
691 // relay confirms the current tunnel, that must not look like a config change.
692 yield* runtime.recoveryRequests.pipe(
693 Stream.runForEach((requested) => runtime.applyConfig(requested).pipe(Effect.asVoid)),
694 Effect.forkChild,
695 );
696
697 yield* runtime.applyConfig(config);
698 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
699 yield* Deferred.await(spawnSignals[1]!);
700 expect(spawned).toEqual([900, 901]);
701
702 // Second rapid crash still waits out the base delay.
703 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
704 yield* TestClock.adjust(Duration.millis(999));
705 expect(spawned).toEqual([900, 901]);
706 yield* TestClock.adjust(Duration.millis(1));
707 yield* Deferred.await(spawnSignals[2]!);
708 expect(spawned).toEqual([900, 901, 902]);
709 }).pipe(Effect.provide(TestClock.layer())),
710 );
711
712 it.effect("an explicit config change clears the backoff and preempts a delayed restart", () =>
713 Effect.gen(function* () {
714 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(800, 3);
715 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
716
717 yield* runtime.applyConfig({
718 providerKind: "cloudflare_tunnel",
719 connectorToken: "token-1",
720 });
721 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
722 yield* Deferred.await(spawnSignals[1]!);
723
724 // Leave the supervisor sleeping on the base delay, then change config.
725 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
726 const status = yield* runtime.applyConfig({
727 providerKind: "cloudflare_tunnel",
728 connectorToken: "token-2",
729 });
730 expect(status).toMatchObject({ status: "running", pid: 802 });
731 expect(spawned).toEqual([800, 801, 802]);
732
733 // The preempted supervisor wakes later and must not spawn a duplicate.
734 yield* TestClock.adjust(Duration.millis(60_000));
735 expect(spawned).toEqual([800, 801, 802]);
736 }).pipe(Effect.provide(TestClock.layer())),
737 );
738
739 it.effect("serializes concurrent connector config changes", () =>
740 Effect.gen(function* () {
741 const spawned: Array<number> = [];
742 const killed: Array<number> = [];
743 const firstSpawnEntered = yield* Deferred.make<void>();
744 const releaseFirstSpawn = yield* Deferred.make<void>();
745 const spawner = ChildProcessSpawner.make(() =>
746 Effect.gen(function* () {
747 const pid = 500 + spawned.length;
748 spawned.push(pid);
749 if (pid === 500) {
750 yield* Deferred.succeed(firstSpawnEntered, undefined);
751 yield* Deferred.await(releaseFirstSpawn);
752 }
753 const handle = makeHandle({
754 pid,
755 onKill: () => {
756 killed.push(pid);
757 },
758 });
759 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
760 return handle;
761 }),
762 );
763 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
764
765 const first = yield* runtime
766 .applyConfig({
767 providerKind: "cloudflare_tunnel",
768 connectorToken: "token-1",
769 })
770 .pipe(Effect.forkChild);
771 yield* Deferred.await(firstSpawnEntered);
772 const second = yield* runtime
773 .applyConfig({
774 providerKind: "cloudflare_tunnel",
775 connectorToken: "token-2",
776 })
777 .pipe(Effect.forkChild);
778 yield* Deferred.succeed(releaseFirstSpawn, undefined);
779
780 yield* Fiber.join(first);
781 const status = yield* Fiber.join(second);
782
783 expect(status).toMatchObject({ status: "running", pid: 501 });
784 expect(spawned).toEqual([500, 501]);
785 expect(killed).toEqual([500]);
786 }),
787 );
788
789 it.effect("reports connector spawn failures", () =>
790 Effect.gen(function* () {
791 const spawner = ChildProcessSpawner.make(() =>
792 Effect.fail(
793 PlatformError.systemError({
794 _tag: "NotFound",
795 module: "ChildProcess",
796 method: "spawn",
797 description: "cloudflared missing",
798 }),
799 ),
800 );
801 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
802
803 const status = yield* runtime.applyConfig({
804 providerKind: "cloudflare_tunnel",
805 connectorToken: "token",
806 tunnelId: "tunnel-1",
807 });
808
809 expect(status).toMatchObject({
810 status: "failed",
811 providerKind: "cloudflare_tunnel",
812 tunnelId: "tunnel-1",
813 });
814 }),
815 );
816
817 it.effect("reports a missing relay client executable without spawning", () =>
818 Effect.gen(function* () {
819 const spawn = vi.fn();
820 const spawner = ChildProcessSpawner.make(spawn);
821 const runtime = yield* buildCloudManagedEndpointRuntime(
822 spawner,
823 Layer.succeed(
824 RelayClient.RelayClient,
825 RelayClient.RelayClient.of({
826 resolve: Effect.succeed({
827 status: "missing",
828 version: RelayClient.CLOUDFLARED_VERSION,
829 }),
830 install: Effect.die("unused"),
831 installWithProgress: () => Effect.die("unused"),
832 }),
833 ),
834 );
835
836 const status = yield* runtime.applyConfig({
837 providerKind: "cloudflare_tunnel",
838 connectorToken: "token",
839 });
840
841 expect(status).toEqual({
842 status: "failed",
843 providerKind: "cloudflare_tunnel",
844 failure: "not-installed",
845 reason: "The relay client is not installed.",
846 });
847 expect(spawn).not.toHaveBeenCalled();
848 }),
849 );
850});