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 expect(
189 ManagedEndpointRuntime.isRejectedRelayClientTunnelOutput(
190 '2026-06-17T02:00:00Z ERR Register tunnel error from server side error="connection timed out" connIndex=0',
191 ),
192 ).toBe(false);
193 });
194
195 it.effect("keeps recovery requests sent before the server starts consuming them", () =>
196 Effect.gen(function* () {
197 const runtime = yield* buildCloudManagedEndpointRuntime(
198 ChildProcessSpawner.make(() => Effect.die("unused")),
199 );
200 const config = {
201 providerKind: "cloudflare_tunnel" as const,
202 connectorToken: "token",
203 tunnelId: "tunnel-1",
204 };
205
206 yield* runtime.requestRecovery(config);
207
208 expect(Option.getOrNull(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
209 }),
210 );
211
212 it.effect("signals each registered tunnel connection", () =>
213 Effect.gen(function* () {
214 const output = yield* Queue.unbounded<Uint8Array>();
215 const spawner = ChildProcessSpawner.make(() =>
216 Effect.gen(function* () {
217 const handle = makeHandle({
218 pid: 700,
219 onKill: () => {},
220 output: Stream.fromQueue(output),
221 });
222 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
223 return handle;
224 }),
225 );
226 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
227 yield* runtime.applyConfig({
228 providerKind: "cloudflare_tunnel",
229 connectorToken: "token",
230 tunnelId: "tunnel-1",
231 });
232 yield* Queue.offer(
233 output,
234 new TextEncoder().encode(
235 "2026-10-04T06:30:43Z INF Registered tunnel connection connIndex=0 event=0\n",
236 ),
237 );
238 expect(Option.isSome(yield* Stream.runHead(runtime.tunnelConnected))).toBe(true);
239 }),
240 );
241
242 it.effect("recovers a rejected tunnel without waiting for the connector to exit", () =>
243 Effect.gen(function* () {
244 const output = yield* Queue.unbounded<Uint8Array>();
245 const firstBatchObserved = yield* Deferred.make<void>();
246 const secondBatchObserved = yield* Deferred.make<void>();
247 const recoveryRequested = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
248 const recoveryRetried = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
249 let recoveryRequestCount = 0;
250 const spawned: Array<number> = [];
251 const encoder = new TextEncoder();
252 const connectorOutput = Stream.fromQueue(output).pipe(
253 Stream.tap((chunk) => {
254 const line = new TextDecoder().decode(chunk);
255 if (line === "first checkpoint\n") {
256 return Deferred.succeed(firstBatchObserved, undefined).pipe(Effect.asVoid);
257 }
258 if (line === "second checkpoint\n") {
259 return Deferred.succeed(secondBatchObserved, undefined).pipe(Effect.asVoid);
260 }
261 return Effect.void;
262 }),
263 );
264 const spawner = ChildProcessSpawner.make(() =>
265 Effect.gen(function* () {
266 const pid = 600;
267 spawned.push(pid);
268 const handle = makeHandle({ pid, onKill: () => {}, output: connectorOutput });
269 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
270 return handle;
271 }),
272 );
273 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
274 const config = {
275 providerKind: "cloudflare_tunnel" as const,
276 connectorToken: "token",
277 tunnelId: "deleted-tunnel",
278 };
279 const rejectedLine =
280 '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';
281
282 yield* runtime.recoveryRequests.pipe(
283 Stream.runForEach((requested) => {
284 recoveryRequestCount += 1;
285 return Deferred.succeed(
286 recoveryRequestCount === 1 ? recoveryRequested : recoveryRetried,
287 requested,
288 ).pipe(Effect.asVoid);
289 }),
290 Effect.forkChild,
291 );
292 yield* runtime.applyConfig(config);
293
294 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(3)));
295 yield* Queue.offer(output, encoder.encode("first checkpoint\n"));
296 yield* Deferred.await(firstBatchObserved);
297 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
298
299 yield* Queue.offer(
300 output,
301 encoder.encode(
302 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0\n" +
303 rejectedLine.repeat(3),
304 ),
305 );
306 yield* Queue.offer(output, encoder.encode("second checkpoint\n"));
307 yield* Deferred.await(secondBatchObserved);
308 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
309
310 yield* Queue.offer(output, encoder.encode(rejectedLine));
311
312 expect(yield* Deferred.await(recoveryRequested)).toEqual(config);
313
314 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(4)));
315
316 expect(yield* Deferred.await(recoveryRetried)).toEqual(config);
317 expect(spawned).toEqual([600]);
318 }),
319 );
320
321 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
322 Effect.gen(function* () {
323 const spawned: Array<ChildProcess.StandardCommand> = [];
324 const killed: Array<number> = [];
325 let nextPid = 100;
326 const spawner = ChildProcessSpawner.make((command) =>
327 Effect.gen(function* () {
328 if (!ChildProcess.isStandardCommand(command)) {
329 throw new Error("Expected standard command.");
330 }
331 spawned.push(command);
332 const pid = nextPid;
333 nextPid += 1;
334 const handle = makeHandle({
335 pid,
336 onKill: () => {
337 killed.push(pid);
338 },
339 });
340 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
341 return handle;
342 }),
343 );
344 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
345
346 yield* runtime.applyConfig({
347 providerKind: "cloudflare_tunnel",
348 connectorToken: "token-1",
349 tunnelId: "tunnel-1",
350 tunnelName: "t3-code-env-1",
351 });
352 yield* runtime.applyConfig({
353 providerKind: "cloudflare_tunnel",
354 connectorToken: "token-1",
355 tunnelId: "tunnel-1",
356 tunnelName: "t3-code-env-1",
357 });
358 yield* runtime.applyConfig({
359 providerKind: "cloudflare_tunnel",
360 connectorToken: "token-2",
361 tunnelId: "tunnel-1",
362 tunnelName: "t3-code-env-1",
363 });
364 const stopped = yield* runtime.applyConfig(null);
365
366 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
367 expect(spawned.map((command) => command.args)).toEqual([
368 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
369 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
370 ]);
371 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
372 "token-1",
373 "token-2",
374 ]);
375 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
376 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
377 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
378 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
379 expect(killed).toEqual([100, 101]);
380 expect(stopped).toEqual({ status: "disabled" });
381 }),
382 );
383
384 it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>
385 Effect.gen(function* () {
386 const killed: Array<number> = [];
387 const spawner = ChildProcessSpawner.make(() =>
388 Effect.gen(function* () {
389 const handle = makeHandle({
390 pid: 200,
391 onKill: () => {
392 killed.push(200);
393 },
394 });
395 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
396 return handle;
397 }),
398 );
399 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
400
401 const started = yield* runtime.applyConfig({
402 providerKind: "cloudflare_tunnel",
403 connectorToken: "token",
404 });
405 const unsupported = yield* runtime.applyConfig({
406 providerKind: "manual",
407 connectorToken: "manual-token",
408 });
409
410 expect(started.status).toBe("running");
411 expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
412 expect(killed).toEqual([200]);
413 }),
414 );
415
416 it.effect("restarts the connector when the active process has exited", () =>
417 Effect.gen(function* () {
418 const spawned: Array<number> = [];
419 const killed: Array<number> = [];
420 let firstRunning = true;
421 const spawner = ChildProcessSpawner.make(() =>
422 Effect.gen(function* () {
423 const pid = spawned.length === 0 ? 300 : 301;
424 spawned.push(pid);
425 const handle = makeHandle({
426 pid,
427 isRunning: () => (pid === 300 ? firstRunning : true),
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 const config = {
438 providerKind: "cloudflare_tunnel" as const,
439 connectorToken: "token",
440 tunnelId: "tunnel-1",
441 };
442
443 const first = yield* runtime.applyConfig(config);
444 firstRunning = false;
445 const second = yield* runtime.applyConfig(config);
446
447 expect(first).toMatchObject({ status: "running", pid: 300 });
448 expect(second).toMatchObject({ status: "running", pid: 301 });
449 expect(spawned).toEqual([300, 301]);
450 expect(killed).toEqual([300]);
451 }),
452 );
453
454 it.effect("supervises the active connector and restarts it after process exit", () =>
455 Effect.gen(function* () {
456 const spawned: Array<number> = [];
457 const killed: Array<number> = [];
458 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
459 const secondSpawned = yield* Deferred.make<void>();
460 const spawner = ChildProcessSpawner.make(() =>
461 Effect.gen(function* () {
462 const pid = spawned.length === 0 ? 400 : 401;
463 spawned.push(pid);
464 if (pid === 401) {
465 yield* Deferred.succeed(secondSpawned, undefined);
466 }
467 const handle = makeHandle({
468 pid,
469 exitCode:
470 pid === 400
471 ? Deferred.await(firstExit)
472 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
473 onKill: () => {
474 killed.push(pid);
475 },
476 });
477 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
478 return handle;
479 }),
480 );
481 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
482
483 const started = yield* runtime.applyConfig({
484 providerKind: "cloudflare_tunnel",
485 connectorToken: "token",
486 tunnelId: "tunnel-1",
487 });
488 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
489 yield* Deferred.await(secondSpawned);
490
491 expect(started).toMatchObject({ status: "running", pid: 400 });
492 expect(spawned).toEqual([400, 401]);
493 expect(killed).toEqual([400]);
494 }),
495 );
496
497 const makeCrashLoopSpawner = (basePid: number, slots: number) =>
498 Effect.gen(function* () {
499 const spawned: Array<number> = [];
500 const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];
501 const spawnSignals: Array<Deferred.Deferred<void>> = [];
502 for (let index = 0; index < slots; index += 1) {
503 exits.push(yield* Deferred.make<ChildProcessSpawner.ExitCode>());
504 spawnSignals.push(yield* Deferred.make<void>());
505 }
506 const spawner = ChildProcessSpawner.make(() =>
507 Effect.gen(function* () {
508 const index = spawned.length;
509 spawned.push(basePid + index);
510 yield* Deferred.succeed(spawnSignals[index]!, undefined);
511 const handle = makeHandle({
512 pid: basePid + index,
513 exitCode: Deferred.await(exits[index]!),
514 onKill: () => {},
515 });
516 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
517 return handle;
518 }),
519 );
520 return { spawner, spawned, exits, spawnSignals };
521 });
522
523 it.effect("backs off restarts while the connector crash-loops", () =>
524 Effect.gen(function* () {
525 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(600, 4);
526 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
527
528 yield* runtime.applyConfig({
529 providerKind: "cloudflare_tunnel",
530 connectorToken: "token",
531 tunnelId: "tunnel-1",
532 });
533 expect(spawned).toEqual([600]);
534
535 // The first crash restarts immediately.
536 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
537 yield* Deferred.await(spawnSignals[1]!);
538 expect(spawned).toEqual([600, 601]);
539
540 // The second rapid crash waits out the base delay before restarting.
541 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
542 yield* TestClock.adjust(Duration.millis(999));
543 expect(spawned).toEqual([600, 601]);
544 yield* TestClock.adjust(Duration.millis(1));
545 yield* Deferred.await(spawnSignals[2]!);
546 expect(spawned).toEqual([600, 601, 602]);
547
548 // The third rapid crash doubles the delay.
549 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
550 yield* TestClock.adjust(Duration.millis(1999));
551 expect(spawned).toEqual([600, 601, 602]);
552 yield* TestClock.adjust(Duration.millis(1));
553 yield* Deferred.await(spawnSignals[3]!);
554 expect(spawned).toEqual([600, 601, 602, 603]);
555 }).pipe(Effect.provide(TestClock.layer())),
556 );
557
558 it.effect("resets the backoff after the connector runs stably", () =>
559 Effect.gen(function* () {
560 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(700, 5);
561 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
562
563 yield* runtime.applyConfig({
564 providerKind: "cloudflare_tunnel",
565 connectorToken: "token",
566 });
567
568 // One rapid crash arms the backoff.
569 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
570 yield* Deferred.await(spawnSignals[1]!);
571
572 // The replacement stays up past the stable-uptime window, so its exit
573 // restarts immediately and the backoff starts over.
574 yield* TestClock.adjust(Duration.millis(30_000));
575 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
576 yield* Deferred.await(spawnSignals[2]!);
577 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
578 yield* Deferred.await(spawnSignals[3]!);
579
580 // The next rapid crash waits the base delay again, not a doubled one.
581 yield* Deferred.succeed(exits[3]!, ChildProcessSpawner.ExitCode(1));
582 yield* TestClock.adjust(Duration.millis(999));
583 expect(spawned).toEqual([700, 701, 702, 703]);
584 yield* TestClock.adjust(Duration.millis(1));
585 yield* Deferred.await(spawnSignals[4]!);
586 expect(spawned).toEqual([700, 701, 702, 703, 704]);
587 }).pipe(Effect.provide(TestClock.layer())),
588 );
589
590 it.effect("a recovery that returns the same config keeps the crash backoff", () =>
591 Effect.gen(function* () {
592 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(900, 4);
593 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
594 const config = {
595 providerKind: "cloudflare_tunnel" as const,
596 connectorToken: "same-token",
597 tunnelId: "same-tunnel",
598 };
599 // The startup consumer re-applies whatever the relay hands back. When the
600 // relay confirms the current tunnel, that must not look like a config change.
601 yield* runtime.recoveryRequests.pipe(
602 Stream.runForEach((requested) => runtime.applyConfig(requested).pipe(Effect.asVoid)),
603 Effect.forkChild,
604 );
605
606 yield* runtime.applyConfig(config);
607 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
608 yield* Deferred.await(spawnSignals[1]!);
609 expect(spawned).toEqual([900, 901]);
610
611 // Second rapid crash still waits out the base delay.
612 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
613 yield* TestClock.adjust(Duration.millis(999));
614 expect(spawned).toEqual([900, 901]);
615 yield* TestClock.adjust(Duration.millis(1));
616 yield* Deferred.await(spawnSignals[2]!);
617 expect(spawned).toEqual([900, 901, 902]);
618 }).pipe(Effect.provide(TestClock.layer())),
619 );
620
621 it.effect("an explicit config change clears the backoff and preempts a delayed restart", () =>
622 Effect.gen(function* () {
623 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(800, 3);
624 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
625
626 yield* runtime.applyConfig({
627 providerKind: "cloudflare_tunnel",
628 connectorToken: "token-1",
629 });
630 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
631 yield* Deferred.await(spawnSignals[1]!);
632
633 // Leave the supervisor sleeping on the base delay, then change config.
634 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
635 const status = yield* runtime.applyConfig({
636 providerKind: "cloudflare_tunnel",
637 connectorToken: "token-2",
638 });
639 expect(status).toMatchObject({ status: "running", pid: 802 });
640 expect(spawned).toEqual([800, 801, 802]);
641
642 // The preempted supervisor wakes later and must not spawn a duplicate.
643 yield* TestClock.adjust(Duration.millis(60_000));
644 expect(spawned).toEqual([800, 801, 802]);
645 }).pipe(Effect.provide(TestClock.layer())),
646 );
647
648 it.effect("serializes concurrent connector config changes", () =>
649 Effect.gen(function* () {
650 const spawned: Array<number> = [];
651 const killed: Array<number> = [];
652 const firstSpawnEntered = yield* Deferred.make<void>();
653 const releaseFirstSpawn = yield* Deferred.make<void>();
654 const spawner = ChildProcessSpawner.make(() =>
655 Effect.gen(function* () {
656 const pid = 500 + spawned.length;
657 spawned.push(pid);
658 if (pid === 500) {
659 yield* Deferred.succeed(firstSpawnEntered, undefined);
660 yield* Deferred.await(releaseFirstSpawn);
661 }
662 const handle = makeHandle({
663 pid,
664 onKill: () => {
665 killed.push(pid);
666 },
667 });
668 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
669 return handle;
670 }),
671 );
672 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
673
674 const first = yield* runtime
675 .applyConfig({
676 providerKind: "cloudflare_tunnel",
677 connectorToken: "token-1",
678 })
679 .pipe(Effect.forkChild);
680 yield* Deferred.await(firstSpawnEntered);
681 const second = yield* runtime
682 .applyConfig({
683 providerKind: "cloudflare_tunnel",
684 connectorToken: "token-2",
685 })
686 .pipe(Effect.forkChild);
687 yield* Deferred.succeed(releaseFirstSpawn, undefined);
688
689 yield* Fiber.join(first);
690 const status = yield* Fiber.join(second);
691
692 expect(status).toMatchObject({ status: "running", pid: 501 });
693 expect(spawned).toEqual([500, 501]);
694 expect(killed).toEqual([500]);
695 }),
696 );
697
698 it.effect("reports connector spawn failures", () =>
699 Effect.gen(function* () {
700 const spawner = ChildProcessSpawner.make(() =>
701 Effect.fail(
702 PlatformError.systemError({
703 _tag: "NotFound",
704 module: "ChildProcess",
705 method: "spawn",
706 description: "cloudflared missing",
707 }),
708 ),
709 );
710 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
711
712 const status = yield* runtime.applyConfig({
713 providerKind: "cloudflare_tunnel",
714 connectorToken: "token",
715 tunnelId: "tunnel-1",
716 });
717
718 expect(status).toMatchObject({
719 status: "failed",
720 providerKind: "cloudflare_tunnel",
721 tunnelId: "tunnel-1",
722 });
723 }),
724 );
725
726 it.effect("reports a missing relay client executable without spawning", () =>
727 Effect.gen(function* () {
728 const spawn = vi.fn();
729 const spawner = ChildProcessSpawner.make(spawn);
730 const runtime = yield* buildCloudManagedEndpointRuntime(
731 spawner,
732 Layer.succeed(
733 RelayClient.RelayClient,
734 RelayClient.RelayClient.of({
735 resolve: Effect.succeed({
736 status: "missing",
737 version: RelayClient.CLOUDFLARED_VERSION,
738 }),
739 install: Effect.die("unused"),
740 installWithProgress: () => Effect.die("unused"),
741 }),
742 ),
743 );
744
745 const status = yield* runtime.applyConfig({
746 providerKind: "cloudflare_tunnel",
747 connectorToken: "token",
748 });
749
750 expect(status).toEqual({
751 status: "failed",
752 providerKind: "cloudflare_tunnel",
753 failure: "not-installed",
754 reason: "The relay client is not installed.",
755 });
756 expect(spawn).not.toHaveBeenCalled();
757 }),
758 );
759});