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

ManagedEndpointRuntime.test.ts

1,455 lines57.5 KB

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