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

ManagedEndpointRuntime.test.ts

1,306 lines51.1 KB

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