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

ManagedEndpointRuntime.test.ts

518 lines18.3 KB

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 Sink from "effect/Sink";
11import * as Stream from "effect/Stream";
12import * as TestClock from "effect/testing/TestClock";
13import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14import * as RelayClient from "@t3tools/shared/relayClient";
15​
16import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
17import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
18​
19const relayClientAvailableLayer = Layer.succeed(
20 RelayClient.RelayClient,
21 RelayClient.RelayClient.of({
22 resolve: Effect.succeed({
23 status: "available",
24 executablePath: "cloudflared",
25 source: "path",
26 version: RelayClient.CLOUDFLARED_VERSION,
27 }),
28 install: Effect.die("unused"),
29 installWithProgress: () => Effect.die("unused"),
30 }),
31);
32​
33const runtimeDependencies = (
34 spawner: ReturnType<typeof ChildProcessSpawner.make>,
35 relayClientLayer = relayClientAvailableLayer,
36) =>
37 Layer.mergeAll(
38 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
39 relayClientLayer,
40 Layer.mock(ServerSecretStore.ServerSecretStore)({
41 get: () => Effect.succeed(Option.none()),
42 }),
43 );
44​
45const buildCloudManagedEndpointRuntime = (
46 spawner: ReturnType<typeof ChildProcessSpawner.make>,
47 relayClientLayer = relayClientAvailableLayer,
48) =>
49 Effect.gen(function* () {
50 const context = yield* Layer.build(
51 ManagedEndpointRuntime.layer.pipe(
52 Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
53 ),
54 );
55 return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
56 Effect.provide(context),
57 );
58 });
59​
60function makeHandle(input: {
61 readonly pid: number;
62 readonly onKill: () => void;
63 readonly isRunning?: () => boolean;
64 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
65}) {
66 return ChildProcessSpawner.makeHandle({
67 pid: ChildProcessSpawner.ProcessId(input.pid),
68 exitCode: input.exitCode ?? Effect.never,
69 isRunning: Effect.sync(() => input.isRunning?.() ?? true),
70 kill: () =>
71 Effect.sync(() => {
72 input.onKill();
73 }),
74 unref: Effect.succeed(Effect.void),
75 stdin: Sink.drain,
76 stdout: Stream.empty,
77 stderr: Stream.empty,
78 all: Stream.empty,
79 getInputFd: () => Sink.drain,
80 getOutputFd: () => Stream.empty,
81 });
83​
84describe("CloudManagedEndpointRuntime", () => {
85 it("classifies Cloudflare connection and warning output", () => {
86 expect(
87 ManagedEndpointRuntime.classifyRelayClientOutput(
88 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
89 ),
90 ).toBe("connected");
91 expect(
92 ManagedEndpointRuntime.classifyRelayClientOutput(
93 "2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
94 ),
95 ).toBe("warning");
96 expect(
97 ManagedEndpointRuntime.classifyRelayClientOutput(
98 "2026-06-17T02:00:00Z INF Starting metrics server",
99 ),
100 ).toBe("debug");
101 // FTL (fatal) and PNC (panic) are more severe than ERR and must surface.
102 expect(
103 ManagedEndpointRuntime.classifyRelayClientOutput(
104 "2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",
105 ),
106 ).toBe("warning");
107 expect(
108 ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),
109 ).toBe("warning");
110 });
111​
112 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
113 Effect.gen(function* () {
114 const spawned: Array<ChildProcess.StandardCommand> = [];
115 const killed: Array<number> = [];
116 let nextPid = 100;
117 const spawner = ChildProcessSpawner.make((command) =>
118 Effect.gen(function* () {
119 if (!ChildProcess.isStandardCommand(command)) {
120 throw new Error("Expected standard command.");
121 }
122 spawned.push(command);
123 const pid = nextPid;
124 nextPid += 1;
125 const handle = makeHandle({
126 pid,
127 onKill: () => {
128 killed.push(pid);
129 },
130 });
131 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
132 return handle;
133 }),
134 );
135 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
136​
137 yield* runtime.applyConfig({
138 providerKind: "cloudflare_tunnel",
139 connectorToken: "token-1",
140 tunnelId: "tunnel-1",
141 tunnelName: "t3-code-env-1",
142 });
143 yield* runtime.applyConfig({
144 providerKind: "cloudflare_tunnel",
145 connectorToken: "token-1",
146 tunnelId: "tunnel-1",
147 tunnelName: "t3-code-env-1",
148 });
149 yield* runtime.applyConfig({
150 providerKind: "cloudflare_tunnel",
151 connectorToken: "token-2",
152 tunnelId: "tunnel-1",
153 tunnelName: "t3-code-env-1",
154 });
155 const stopped = yield* runtime.applyConfig(null);
156​
157 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
158 expect(spawned.map((command) => command.args)).toEqual([
159 ["tunnel", "run"],
160 ["tunnel", "run"],
161 ]);
162 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
163 "token-1",
164 "token-2",
165 ]);
166 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
167 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
168 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
169 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
170 expect(killed).toEqual([100, 101]);
171 expect(stopped).toEqual({ status: "disabled" });
172 }),
173 );
174​
175 it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>
176 Effect.gen(function* () {
177 const killed: Array<number> = [];
178 const spawner = ChildProcessSpawner.make(() =>
179 Effect.gen(function* () {
180 const handle = makeHandle({
181 pid: 200,
182 onKill: () => {
183 killed.push(200);
184 },
185 });
186 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
187 return handle;
188 }),
189 );
190 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
191​
192 const started = yield* runtime.applyConfig({
193 providerKind: "cloudflare_tunnel",
194 connectorToken: "token",
195 });
196 const unsupported = yield* runtime.applyConfig({
197 providerKind: "manual",
198 connectorToken: "manual-token",
199 });
200​
201 expect(started.status).toBe("running");
202 expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
203 expect(killed).toEqual([200]);
204 }),
205 );
206​
207 it.effect("restarts the connector when the active process has exited", () =>
208 Effect.gen(function* () {
209 const spawned: Array<number> = [];
210 const killed: Array<number> = [];
211 let firstRunning = true;
212 const spawner = ChildProcessSpawner.make(() =>
213 Effect.gen(function* () {
214 const pid = spawned.length === 0 ? 300 : 301;
215 spawned.push(pid);
216 const handle = makeHandle({
217 pid,
218 isRunning: () => (pid === 300 ? firstRunning : true),
219 onKill: () => {
220 killed.push(pid);
221 },
222 });
223 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
224 return handle;
225 }),
226 );
227 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
228 const config = {
229 providerKind: "cloudflare_tunnel" as const,
230 connectorToken: "token",
231 tunnelId: "tunnel-1",
232 };
233​
234 const first = yield* runtime.applyConfig(config);
235 firstRunning = false;
236 const second = yield* runtime.applyConfig(config);
237​
238 expect(first).toMatchObject({ status: "running", pid: 300 });
239 expect(second).toMatchObject({ status: "running", pid: 301 });
240 expect(spawned).toEqual([300, 301]);
241 expect(killed).toEqual([300]);
242 }),
243 );
244​
245 it.effect("supervises the active connector and restarts it after process exit", () =>
246 Effect.gen(function* () {
247 const spawned: Array<number> = [];
248 const killed: Array<number> = [];
249 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
250 const secondSpawned = yield* Deferred.make<void>();
251 const spawner = ChildProcessSpawner.make(() =>
252 Effect.gen(function* () {
253 const pid = spawned.length === 0 ? 400 : 401;
254 spawned.push(pid);
255 if (pid === 401) {
256 yield* Deferred.succeed(secondSpawned, undefined);
257 }
258 const handle = makeHandle({
259 pid,
260 exitCode:
261 pid === 400
262 ? Deferred.await(firstExit)
263 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
264 onKill: () => {
265 killed.push(pid);
266 },
267 });
268 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
269 return handle;
270 }),
271 );
272 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
273​
274 const started = yield* runtime.applyConfig({
275 providerKind: "cloudflare_tunnel",
276 connectorToken: "token",
277 tunnelId: "tunnel-1",
278 });
279 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
280 yield* Deferred.await(secondSpawned);
281​
282 expect(started).toMatchObject({ status: "running", pid: 400 });
283 expect(spawned).toEqual([400, 401]);
284 expect(killed).toEqual([400]);
285 }),
286 );
287​
288 const makeCrashLoopSpawner = (basePid: number, slots: number) =>
289 Effect.gen(function* () {
290 const spawned: Array<number> = [];
291 const exits: Array<Deferred.Deferred<ChildProcessSpawner.ExitCode>> = [];
292 const spawnSignals: Array<Deferred.Deferred<void>> = [];
293 for (let index = 0; index < slots; index += 1) {
294 exits.push(yield* Deferred.make<ChildProcessSpawner.ExitCode>());
295 spawnSignals.push(yield* Deferred.make<void>());
296 }
297 const spawner = ChildProcessSpawner.make(() =>
298 Effect.gen(function* () {
299 const index = spawned.length;
300 spawned.push(basePid + index);
301 yield* Deferred.succeed(spawnSignals[index]!, undefined);
302 const handle = makeHandle({
303 pid: basePid + index,
304 exitCode: Deferred.await(exits[index]!),
305 onKill: () => {},
306 });
307 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
308 return handle;
309 }),
310 );
311 return { spawner, spawned, exits, spawnSignals };
312 });
313​
314 it.effect("backs off restarts while the connector crash-loops", () =>
315 Effect.gen(function* () {
316 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(600, 4);
317 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
318​
319 yield* runtime.applyConfig({
320 providerKind: "cloudflare_tunnel",
321 connectorToken: "token",
322 tunnelId: "tunnel-1",
323 });
324 expect(spawned).toEqual([600]);
325​
326 // The first crash restarts immediately.
327 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
328 yield* Deferred.await(spawnSignals[1]!);
329 expect(spawned).toEqual([600, 601]);
330​
331 // The second rapid crash waits out the base delay before restarting.
332 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
333 yield* TestClock.adjust(Duration.millis(999));
334 expect(spawned).toEqual([600, 601]);
335 yield* TestClock.adjust(Duration.millis(1));
336 yield* Deferred.await(spawnSignals[2]!);
337 expect(spawned).toEqual([600, 601, 602]);
338​
339 // The third rapid crash doubles the delay.
340 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
341 yield* TestClock.adjust(Duration.millis(1999));
342 expect(spawned).toEqual([600, 601, 602]);
343 yield* TestClock.adjust(Duration.millis(1));
344 yield* Deferred.await(spawnSignals[3]!);
345 expect(spawned).toEqual([600, 601, 602, 603]);
346 }).pipe(Effect.provide(TestClock.layer())),
347 );
348​
349 it.effect("resets the backoff after the connector runs stably", () =>
350 Effect.gen(function* () {
351 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(700, 5);
352 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
353​
354 yield* runtime.applyConfig({
355 providerKind: "cloudflare_tunnel",
356 connectorToken: "token",
357 });
358​
359 // One rapid crash arms the backoff.
360 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
361 yield* Deferred.await(spawnSignals[1]!);
362​
363 // The replacement stays up past the stable-uptime window, so its exit
364 // restarts immediately and the backoff starts over.
365 yield* TestClock.adjust(Duration.millis(30_000));
366 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
367 yield* Deferred.await(spawnSignals[2]!);
368 yield* Deferred.succeed(exits[2]!, ChildProcessSpawner.ExitCode(1));
369 yield* Deferred.await(spawnSignals[3]!);
370​
371 // The next rapid crash waits the base delay again, not a doubled one.
372 yield* Deferred.succeed(exits[3]!, ChildProcessSpawner.ExitCode(1));
373 yield* TestClock.adjust(Duration.millis(999));
374 expect(spawned).toEqual([700, 701, 702, 703]);
375 yield* TestClock.adjust(Duration.millis(1));
376 yield* Deferred.await(spawnSignals[4]!);
377 expect(spawned).toEqual([700, 701, 702, 703, 704]);
378 }).pipe(Effect.provide(TestClock.layer())),
379 );
380​
381 it.effect("an explicit config change clears the backoff and preempts a delayed restart", () =>
382 Effect.gen(function* () {
383 const { spawner, spawned, exits, spawnSignals } = yield* makeCrashLoopSpawner(800, 3);
384 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
385​
386 yield* runtime.applyConfig({
387 providerKind: "cloudflare_tunnel",
388 connectorToken: "token-1",
389 });
390 yield* Deferred.succeed(exits[0]!, ChildProcessSpawner.ExitCode(1));
391 yield* Deferred.await(spawnSignals[1]!);
392​
393 // Leave the supervisor sleeping on the base delay, then change config.
394 yield* Deferred.succeed(exits[1]!, ChildProcessSpawner.ExitCode(1));
395 const status = yield* runtime.applyConfig({
396 providerKind: "cloudflare_tunnel",
397 connectorToken: "token-2",
398 });
399 expect(status).toMatchObject({ status: "running", pid: 802 });
400 expect(spawned).toEqual([800, 801, 802]);
401​
402 // The preempted supervisor wakes later and must not spawn a duplicate.
403 yield* TestClock.adjust(Duration.millis(60_000));
404 expect(spawned).toEqual([800, 801, 802]);
405 }).pipe(Effect.provide(TestClock.layer())),
406 );
407​
408 it.effect("serializes concurrent connector config changes", () =>
409 Effect.gen(function* () {
410 const spawned: Array<number> = [];
411 const killed: Array<number> = [];
412 const firstSpawnEntered = yield* Deferred.make<void>();
413 const releaseFirstSpawn = yield* Deferred.make<void>();
414 const spawner = ChildProcessSpawner.make(() =>
415 Effect.gen(function* () {
416 const pid = 500 + spawned.length;
417 spawned.push(pid);
418 if (pid === 500) {
419 yield* Deferred.succeed(firstSpawnEntered, undefined);
420 yield* Deferred.await(releaseFirstSpawn);
421 }
422 const handle = makeHandle({
423 pid,
424 onKill: () => {
425 killed.push(pid);
426 },
427 });
428 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
429 return handle;
430 }),
431 );
432 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
433​
434 const first = yield* runtime
435 .applyConfig({
436 providerKind: "cloudflare_tunnel",
437 connectorToken: "token-1",
438 })
439 .pipe(Effect.forkChild);
440 yield* Deferred.await(firstSpawnEntered);
441 const second = yield* runtime
442 .applyConfig({
443 providerKind: "cloudflare_tunnel",
444 connectorToken: "token-2",
445 })
446 .pipe(Effect.forkChild);
447 yield* Deferred.succeed(releaseFirstSpawn, undefined);
448​
449 yield* Fiber.join(first);
450 const status = yield* Fiber.join(second);
451​
452 expect(status).toMatchObject({ status: "running", pid: 501 });
453 expect(spawned).toEqual([500, 501]);
454 expect(killed).toEqual([500]);
455 }),
456 );
457​
458 it.effect("reports connector spawn failures", () =>
459 Effect.gen(function* () {
460 const spawner = ChildProcessSpawner.make(() =>
461 Effect.fail(
462 PlatformError.systemError({
463 _tag: "NotFound",
464 module: "ChildProcess",
465 method: "spawn",
466 description: "cloudflared missing",
467 }),
468 ),
469 );
470 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
471​
472 const status = yield* runtime.applyConfig({
473 providerKind: "cloudflare_tunnel",
474 connectorToken: "token",
475 tunnelId: "tunnel-1",
476 });
477​
478 expect(status).toMatchObject({
479 status: "failed",
480 providerKind: "cloudflare_tunnel",
481 tunnelId: "tunnel-1",
482 });
483 }),
484 );
485​
486 it.effect("reports a missing relay client executable without spawning", () =>
487 Effect.gen(function* () {
488 const spawn = vi.fn();
489 const spawner = ChildProcessSpawner.make(spawn);
490 const runtime = yield* buildCloudManagedEndpointRuntime(
491 spawner,
492 Layer.succeed(
493 RelayClient.RelayClient,
494 RelayClient.RelayClient.of({
495 resolve: Effect.succeed({
496 status: "missing",
497 version: RelayClient.CLOUDFLARED_VERSION,
498 }),
499 install: Effect.die("unused"),
500 installWithProgress: () => Effect.die("unused"),
501 }),
502 ),
503 );
504​
505 const status = yield* runtime.applyConfig({
506 providerKind: "cloudflare_tunnel",
507 connectorToken: "token",
508 });
509​
510 expect(status).toEqual({
511 status: "failed",
512 providerKind: "cloudflare_tunnel",
513 reason: "The relay client is not installed.",
514 });
515 expect(spawn).not.toHaveBeenCalled();
516 }),
517 );
518});