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

ManagedEndpointRuntime.test.ts

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