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

ManagedEndpointRuntime.test.ts

1,251 lines48.6 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("preserves an explicit transport choice despite repeated QUIC stalls", () =>
416 Effect.gen(function* () {
417 const fixture = yield* makeTransportSpawner({ transport: "quic" });
418 const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);
419 yield* runtime.applyConfig(tunnelConfig);
420 yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30));
421 yield* fixture.observe(runtime, 0, quicDatagramWarning.repeat(30));
422 expect(fixture.spawned).toHaveLength(1);
423 expect(fixture.killed).toEqual([]);
424 expect(fixture.spawned[0]!.args).not.toContain("--protocol");
425 expect(fixture.spawned[0]!.options.env?.TUNNEL_TRANSPORT_PROTOCOL).toBe("quic");
426 }),
427 );
428​
429 it.effect(
430 "retains automatic HTTP/2 fallback across restarts until expiry and respects overrides",
431 () =>
432 Effect.gen(function* () {
433 const context = yield* Layer.build(
434 ServerSecretStore.layer.pipe(
435 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-transport-test-" })),
436 Layer.provide(NodeServices.layer),
437 ),
438 );
439 const secretStoreLayer = Layer.succeed(
440 ServerSecretStore.ServerSecretStore,
441 context.pipe(Context.get(ServerSecretStore.ServerSecretStore)),
442 );
443 const fixture = yield* makeTransportSpawner();
444 const start = (spawner = fixture.spawner) =>
445 buildCloudManagedEndpointRuntime(
446 spawner,
447 layerRelayClientAvailable,
448 unusedHttpClient,
449 secretStoreLayer,
450 );
451 yield* Effect.gen(function* () {
452 const runtime = yield* start();
453 yield* runtime.applyConfig(tunnelConfig);
454 expect(yield* Queue.take(fixture.started)).toBe(0);
455 expect(fixture.spawned[0]!.args).not.toContain("--protocol");
456 yield* fixture.emit(0, quicDialWarning.repeat(30));
457 expect(yield* Queue.take(fixture.started)).toBe(1);
458 yield* fixture.observe(runtime, 1);
459 expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
460 }).pipe(Effect.scoped);
461​
462 yield* TestClock.adjust(Duration.hours(1));
463 for (const transport of [undefined, "quic", "http2", "auto", undefined]) {
464 yield* Effect.gen(function* () {
465 const next = yield* makeTransportSpawner(transport ? { transport } : {});
466 const restarted = yield* start(next.spawner);
467 yield* restarted.applyConfig(tunnelConfig);
468 if (transport === undefined) {
469 expect(next.spawned[0]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
470 } else {
471 expect(next.spawned[0]!.args).not.toContain("--protocol");
472 expect(next.spawned[0]!.options.env?.TUNNEL_TRANSPORT_PROTOCOL).toBe(transport);
473 yield* next.observe(restarted, 0, quicDialWarning.repeat(30));
474 expect(next.spawned).toHaveLength(1);
475 }
476 }).pipe(Effect.scoped);
477 }
478​
479 // Reusing the hint one hour later must not extend its original lifetime.
480 yield* TestClock.adjust(Duration.hours(23));
481 yield* Effect.gen(function* () {
482 const next = yield* makeTransportSpawner();
483 const restarted = yield* start(next.spawner);
484 yield* restarted.applyConfig(tunnelConfig);
485 expect(next.spawned[0]!.args).not.toContain("--protocol");
486 expect(yield* Queue.take(next.started)).toBe(0);
487 yield* next.emit(0, quicDatagramWarning.repeat(30));
488 expect(yield* Queue.take(next.started)).toBe(1);
489 expect(next.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
490 }).pipe(Effect.scoped);
491 }),
492 );
493​
494 it.effect(
495 "ignores invalid or unreadable fallback state and still falls back if persistence fails",
496 () =>
497 Effect.gen(function* () {
498 for (const cached of [
499 "not json",
500 '{"fellBackAt":"invalid"}',
501 '{"fellBackAt":9007199254740991}',
502 null,
503 ]) {
504 yield* Effect.gen(function* () {
505 const fixture = yield* makeTransportSpawner();
506 const runtime = yield* buildCloudManagedEndpointRuntime(
507 fixture.spawner,
508 layerRelayClientAvailable,
509 unusedHttpClient,
510 Layer.mock(ServerSecretStore.ServerSecretStore)({
511 get: () =>
512 cached === null
513 ? Effect.fail(
514 new ServerSecretStore.SecretStoreReadError({
515 resource: "test",
516 cause: "unreadable",
517 }),
518 )
519 : Effect.succeedSome(new TextEncoder().encode(cached)),
520 set: () =>
521 Effect.fail(
522 new ServerSecretStore.SecretStorePersistError({
523 resource: "test",
524 cause: "read-only",
525 }),
526 ),
527 }),
528 );
529 yield* runtime.applyConfig(tunnelConfig);
530 expect(yield* Queue.take(fixture.started)).toBe(0);
531 expect(fixture.spawned[0]!.args).not.toContain("--protocol");
532 yield* fixture.emit(0, quicDialWarning.repeat(30));
533 expect(yield* Queue.take(fixture.started)).toBe(1);
534 expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
535 }).pipe(Effect.scoped);
536 }
537 }),
538 );
539​
540 it.effect("requests recovery after a failed HTTP/2 spawn and retries with HTTP/2", () =>
541 Effect.gen(function* () {
542 const fixture = yield* makeTransportSpawner({ failSpawn: 1 });
543 const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);
544 yield* runtime.applyConfig(tunnelConfig);
545 expect(yield* Queue.take(fixture.started)).toBe(0);
546 yield* fixture.emit(0, quicDialWarning.repeat(30));
547​
548 const requested = Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests));
549 expect(requested).toEqual(tunnelConfig);
550 expect(fixture.killed).toEqual([800]);
551 expect(fixture.spawned).toHaveLength(2);
552 expect(fixture.spawned[1]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
553 expect(yield* runtime.applyConfig(requested)).toMatchObject({ status: "running", pid: 802 });
554 yield* fixture.observe(runtime, 2);
555 expect(fixture.spawned[2]!.args.slice(-3)).toEqual(["--protocol", "http2", "run"]);
556 }),
557 );
558​
559 it.effect("keeps redacted connector logs bounded even when rotation fails", () =>
560 Effect.gen(function* () {
561 const fs = yield* FileSystem.FileSystem;
562 const path = yield* Path.Path;
563 for (const rotationBlocked of [false, true]) {
564 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-relay-client-log-" });
565 const logPath = path.join(baseDir, "userdata", "logs", "relay-client.ndjson");
566 const existingLog = "x".repeat(1024 * 1024);
567 if (rotationBlocked) {
568 yield* fs.makeDirectory(`${logPath}.2`, { recursive: true });
569 yield* fs.writeFileString(`${logPath}.2/blocked`, "blocks rotation");
570 yield* fs.writeFileString(logPath, existingLog);
571 }
572 const warnings: unknown[] = [];
573 const logger = Logger.make(({ message }) => {
574 if (Array.isArray(message) && message[0] === "Relay client log unavailable") {
575 warnings.push(message);
576 }
577 });
578 const fixture = yield* makeTransportSpawner();
579 yield* Effect.gen(function* () {
580 const context = yield* Layer.build(
581 ManagedEndpointRuntime.layer.pipe(
582 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
583 Layer.provide(runtimeDependencies(fixture.spawner)),
584 ),
585 );
586 const runtime = yield* Effect.service(
587 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
588 ).pipe(Effect.provide(context));
589 yield* runtime.applyConfig({ ...tunnelConfig, connectorToken: "connector-secret" });
590 yield* fixture.observe(
591 runtime,
592 0,
593 '2026-10-16T20:29:40Z ERR Failed to serve tunnel connection error="rejected connector-secret" connIndex=0\n',
594 );
595 }).pipe(Effect.scoped, Effect.withLogger(logger));
596​
597 const log = yield* fs.readFileString(logPath);
598 if (rotationBlocked) {
599 expect(log.length).toBe(existingLog.length);
600 expect(warnings).toHaveLength(1);
601 continue;
602 }
603 const entries = log
604 .trim()
605 .split("\n")
606 .map((line) => decodeLogEntry(line));
607 expect(entries.map((entry) => [entry.level, entry.message[0]])).toEqual([
608 ["INFO", "Relay client process started; waiting for tunnel connection"],
609 ["WARN", "Relay client reported a transport warning"],
610 ["INFO", "Relay client tunnel connection registered"],
611 ["INFO", "Relay client stopped"],
612 ]);
613 expect(log).toContain("rejected <redacted>");
614 expect(log).not.toContain("connector-secret");
615 const oversizedFixture = yield* makeTransportSpawner();
616 yield* Effect.gen(function* () {
617 const context = yield* Layer.build(
618 ManagedEndpointRuntime.layer.pipe(
619 Layer.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
620 Layer.provide(runtimeDependencies(oversizedFixture.spawner)),
621 ),
622 );
623 const runtime = yield* Effect.service(
624 ManagedEndpointRuntime.CloudManagedEndpointRuntime,
625 ).pipe(Effect.provide(context));
626 yield* runtime.applyConfig(tunnelConfig);
627 yield* oversizedFixture.observe(runtime, 0, "ERR " + "界".repeat(1024 * 1024) + "\n");
628 }).pipe(Effect.scoped);
629 const files = yield* fs.readDirectory(path.dirname(logPath));
630 const allEntries = [];
631 for (const file of files.filter((name) => name.startsWith("relay-client.ndjson"))) {
632 const contents = yield* fs.readFileString(path.join(path.dirname(logPath), file));
633 expect(Buffer.byteLength(contents)).toBeLessThanOrEqual(1024 * 1024);
634 allEntries.push(
635 ...contents
636 .trim()
637 .split("\n")
638 .map((line) => decodeLogEntry(line)),
639 );
640 }
641 expect(
642 allEntries.some(
643 (entry) => entry.message[0] === "Relay client log entry omitted: exceeds 1 MiB",
644 ),
645 ).toBe(true);
646 }
647 }).pipe(Effect.provide(NodeServices.layer)),
648 );
649​
650 it.effect("discards a pending fallback when its connector is replaced or removed", () =>
651 Effect.gen(function* () {
652 for (const nextConfig of [{ ...tunnelConfig, connectorToken: "replacement" }, null]) {
653 yield* Effect.gen(function* () {
654 const checking = yield* Deferred.make<void>();
655 const releaseCheck = yield* Deferred.make<void>();
656 const fixture = yield* makeTransportSpawner({
657 isRunning: Deferred.succeed(checking, undefined).pipe(
658 Effect.andThen(Deferred.await(releaseCheck)),
659 Effect.as(true),
660 ),
661 });
662 const runtime = yield* buildCloudManagedEndpointRuntime(fixture.spawner);
663 yield* runtime.applyConfig(tunnelConfig);
664 yield* fixture.observe(runtime, 0);
665​
666 // Hold reconciliation in a process probe so config changes queue before fallback.
667 const probe = yield* runtime.applyConfig(tunnelConfig).pipe(Effect.forkChild);
668 yield* Deferred.await(checking);
669 const change = yield* runtime
670 .applyConfig(nextConfig)
671 .pipe(Effect.forkChild({ startImmediately: true }));
672 yield* fixture.observe(runtime, 0, quicDialWarning.repeat(30));
673 yield* Deferred.succeed(releaseCheck, undefined);
674 yield* Fiber.join(probe);
675 yield* Fiber.join(change);
676 yield* TestClock.adjust(Duration.zero);
677​
678 expect(fixture.killed).toEqual([800]);
679 expect(fixture.spawned).toHaveLength(nextConfig ? 2 : 1);
680 if (nextConfig) {
681 expect(fixture.spawned[1]!.options.env?.TUNNEL_TOKEN).toBe("replacement");
682 expect(fixture.spawned[1]!.args).not.toContain("--protocol");
683 }
684 yield* runtime.applyConfig(null);
685 // Buffered output and the old exit cannot revive a removed configuration.
686 yield* fixture.emit(0, quicDialWarning.repeat(30));
687 yield* TestClock.adjust(Duration.minutes(5));
688 expect(fixture.spawned).toHaveLength(nextConfig ? 2 : 1);
689 expect(fixture.killed).toEqual(nextConfig ? [800, 801] : [800]);
690 }).pipe(Effect.scoped);
691 }
692 }).pipe(Effect.provide(TestClock.layer())),
693 );
694​
695 it.effect("recovers a rejected tunnel without waiting for the connector to exit", () =>
696 Effect.gen(function* () {
697 const output = yield* Queue.unbounded<Uint8Array>();
698 const firstBatchObserved = yield* Deferred.make<void>();
699 const secondBatchObserved = yield* Deferred.make<void>();
700 const recoveryRequested = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
701 const recoveryRetried = yield* Deferred.make<RelayManagedEndpointRuntimeConfig>();
702 let recoveryRequestCount = 0;
703 const spawned: Array<number> = [];
704 const encoder = new TextEncoder();
705 const connectorOutput = Stream.fromQueue(output).pipe(
706 Stream.tap((chunk) => {
707 const line = new TextDecoder().decode(chunk);
708 if (line === "first checkpoint\n") {
709 return Deferred.succeed(firstBatchObserved, undefined).pipe(Effect.asVoid);
710 }
711 if (line === "second checkpoint\n") {
712 return Deferred.succeed(secondBatchObserved, undefined).pipe(Effect.asVoid);
713 }
714 return Effect.void;
715 }),
716 );
717 const spawner = ChildProcessSpawner.make(() =>
718 Effect.gen(function* () {
719 const pid = 600;
720 spawned.push(pid);
721 const handle = makeHandle({ pid, onKill: () => {}, output: connectorOutput });
722 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
723 return handle;
724 }),
725 );
726 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
727 const config = {
728 providerKind: "cloudflare_tunnel" as const,
729 connectorToken: "token",
730 tunnelId: "deleted-tunnel",
731 };
732 const rejectedLine =
733 '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';
734​
735 yield* runtime.recoveryRequests.pipe(
736 Stream.runForEach((requested) => {
737 recoveryRequestCount += 1;
738 return Deferred.succeed(
739 recoveryRequestCount === 1 ? recoveryRequested : recoveryRetried,
740 requested,
741 ).pipe(Effect.asVoid);
742 }),
743 Effect.forkChild,
744 );
745 yield* runtime.applyConfig(config);
746​
747 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(3)));
748 yield* Queue.offer(output, encoder.encode("first checkpoint\n"));
749 yield* Deferred.await(firstBatchObserved);
750 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
751​
752 yield* Queue.offer(
753 output,
754 encoder.encode(
755 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0\n" +
756 rejectedLine.repeat(3),
757 ),
758 );
759 yield* Queue.offer(output, encoder.encode("second checkpoint\n"));
760 yield* Deferred.await(secondBatchObserved);
761 expect(yield* Deferred.isDone(recoveryRequested)).toBe(false);
762​
763 yield* Queue.offer(output, encoder.encode(rejectedLine));
764​
765 expect(yield* Deferred.await(recoveryRequested)).toEqual(config);
766​
767 yield* Queue.offer(output, encoder.encode(rejectedLine.repeat(4)));
768​
769 expect(yield* Deferred.await(recoveryRetried)).toEqual(config);
770 expect(spawned).toEqual([600]);
771 }),
772 );
773​
774 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
775 Effect.gen(function* () {
776 const spawned: Array<ChildProcess.StandardCommand> = [];
777 const killed: Array<number> = [];
778 let nextPid = 100;
779 const spawner = ChildProcessSpawner.make((command) =>
780 Effect.gen(function* () {
781 if (!ChildProcess.isStandardCommand(command)) {
782 throw new Error("Expected standard command.");
783 }
784 spawned.push(command);
785 const pid = nextPid;
786 nextPid += 1;
787 const handle = makeHandle({
788 pid,
789 onKill: () => {
790 killed.push(pid);
791 },
792 });
793 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
794 return handle;
795 }),
796 );
797 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
798​
799 yield* runtime.applyConfig({
800 providerKind: "cloudflare_tunnel",
801 connectorToken: "token-1",
802 tunnelId: "tunnel-1",
803 tunnelName: "t3-code-env-1",
804 });
805 yield* runtime.applyConfig({
806 providerKind: "cloudflare_tunnel",
807 connectorToken: "token-1",
808 tunnelId: "tunnel-1",
809 tunnelName: "t3-code-env-1",
810 });
811 yield* runtime.applyConfig({
812 providerKind: "cloudflare_tunnel",
813 connectorToken: "token-2",
814 tunnelId: "tunnel-1",
815 tunnelName: "t3-code-env-1",
816 });
817 const stopped = yield* runtime.applyConfig(null);
818​
819 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
820 expect(spawned.map((command) => command.args)).toEqual([
821 [
822 "tunnel",
823 "--no-autoupdate",
824 "--loglevel",
825 "info",
826 "--output",
827 "default",
828 "--metrics",
829 "127.0.0.1:0",
830 "run",
831 ],
832 [
833 "tunnel",
834 "--no-autoupdate",
835 "--loglevel",
836 "info",
837 "--output",
838 "default",
839 "--metrics",
840 "127.0.0.1:0",
841 "run",
842 ],
843 ]);
844 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
845 "token-1",
846 "token-2",
847 ]);
848 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
849 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
850 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
851 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
852 expect(killed).toEqual([100, 101]);
853 expect(stopped).toEqual({ status: "disabled" });
854 }),
855 );
856​
857 it.effect("supervises the active connector and restarts it after process exit", () =>
858 Effect.gen(function* () {
859 const spawned: Array<number> = [];
860 const killed: Array<number> = [];
861 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
862 const secondSpawned = yield* Deferred.make<void>();
863 const spawner = ChildProcessSpawner.make(() =>
864 Effect.gen(function* () {
865 const pid = spawned.length === 0 ? 400 : 401;
866 spawned.push(pid);
867 if (pid === 401) {
868 yield* Deferred.succeed(secondSpawned, undefined);
869 }
870 const handle = makeHandle({
871 pid,
872 exitCode:
873 pid === 400
874 ? Deferred.await(firstExit)
875 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
876 onKill: () => {
877 killed.push(pid);
878 },
879 });
880 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
881 return handle;
882 }),
883 );
884 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
885​
886 const started = yield* runtime.applyConfig({
887 providerKind: "cloudflare_tunnel",
888 connectorToken: "token",
889 tunnelId: "tunnel-1",
890 });
891 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
892 yield* Deferred.await(secondSpawned);
893​
894 expect(started).toMatchObject({ status: "running", pid: 400 });
895 expect(spawned).toEqual([400, 401]);
896 expect(killed).toEqual([400]);
897 }),
898 );
899​
900 it.effect("serializes concurrent connector config changes", () =>
901 Effect.gen(function* () {
902 const spawned: Array<number> = [];
903 const killed: Array<number> = [];
904 const firstSpawnEntered = yield* Deferred.make<void>();
905 const releaseFirstSpawn = yield* Deferred.make<void>();
906 const spawner = ChildProcessSpawner.make(() =>
907 Effect.gen(function* () {
908 const pid = 500 + spawned.length;
909 spawned.push(pid);
910 if (pid === 500) {
911 yield* Deferred.succeed(firstSpawnEntered, undefined);
912 yield* Deferred.await(releaseFirstSpawn);
913 }
914 const handle = makeHandle({
915 pid,
916 onKill: () => {
917 killed.push(pid);
918 },
919 });
920 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
921 return handle;
922 }),
923 );
924 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
925​
926 const first = yield* runtime
927 .applyConfig({
928 providerKind: "cloudflare_tunnel",
929 connectorToken: "token-1",
930 })
931 .pipe(Effect.forkChild);
932 yield* Deferred.await(firstSpawnEntered);
933 const second = yield* runtime
934 .applyConfig({
935 providerKind: "cloudflare_tunnel",
936 connectorToken: "token-2",
937 })
938 .pipe(Effect.forkChild);
939 yield* Deferred.succeed(releaseFirstSpawn, undefined);
940​
941 yield* Fiber.join(first);
942 const status = yield* Fiber.join(second);
943​
944 expect(status).toMatchObject({ status: "running", pid: 501 });
945 expect(spawned).toEqual([500, 501]);
946 expect(killed).toEqual([500]);
947 }),
948 );
949​
950 it.effect(
951 "runs an older relay client while the pinned one installs, then hands off to it and prunes",
952 () =>
953 Effect.gen(function* () {
954 const olderClient = {
955 status: "available",
956 executablePath: "/managed/2025.9.0/cloudflared",
957 source: "managed",
958 version: "2025.9.0",
959 } as const;
960 const pinnedClient = {
961 status: "available",
962 executablePath: "/managed/pinned/cloudflared",
963 source: "managed",
964 version: RelayClient.CLOUDFLARED_VERSION,
965 } as const;
966 let installed = false;
967 const releaseInstall = yield* Deferred.make<void>();
968 const pruned = yield* Deferred.make<void>();
969 const spawned = yield* Queue.unbounded<string>();
970 const olderStopped = yield* Deferred.make<void>();
971 const output = yield* Queue.unbounded<Uint8Array>();
972 const spawner = ChildProcessSpawner.make((command) =>
973 Effect.gen(function* () {
974 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
975 yield* Queue.offer(spawned, executable);
976 const handle = makeHandle({
977 pid: executable === pinnedClient.executablePath ? 2 : 1,
978 onKill: () => {
979 if (executable === olderClient.executablePath) {
980 Deferred.doneUnsafe(olderStopped, Effect.void);
981 }
982 },
983 ...(executable === pinnedClient.executablePath
984 ? { output: Stream.fromQueue(output) }
985 : {}),
986 });
987 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
988 return handle;
989 }),
990 );
991 const runtime = yield* buildCloudManagedEndpointRuntime(
992 spawner,
993 Layer.succeed(
994 RelayClient.RelayClient,
995 RelayClient.RelayClient.of({
996 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
997 install: Deferred.await(releaseInstall).pipe(
998 Effect.andThen(
999 Effect.sync(() => {
1000 installed = true;
1001 return pinnedClient;
1002 }),
1003 ),
1004 ),
1005 installWithProgress: () => Effect.die("unused"),
1006 pruneManagedVersions: Deferred.succeed(pruned, undefined).pipe(Effect.asVoid),
1007 }),
1008 ),
1009 );
1010​
1011 const status = yield* runtime.applyConfig({
1012 providerKind: "cloudflare_tunnel",
1013 connectorToken: "token",
1014 });
1015 expect(status).toMatchObject({ status: "running", pid: 1 });
1016 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
1017​
1018 yield* Deferred.succeed(releaseInstall, undefined);
1019 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
1020 expect(Option.isNone(yield* Deferred.poll(olderStopped))).toBe(true);
1021​
1022 yield* Queue.offer(
1023 output,
1024 new TextEncoder().encode(
1025 "2026-10-08T00:00:00Z INF Registered tunnel connection connIndex=0\n",
1026 ),
1027 );
1028 yield* Deferred.await(olderStopped);
1029 yield* Deferred.await(pruned);
1030 }),
1031 );
1032​
1033 it.effect("installs a missing relay client in the background and then starts it", () =>
1034 Effect.gen(function* () {
1035 const pinnedClient = {
1036 status: "available",
1037 executablePath: "/managed/pinned/cloudflared",
1038 source: "managed",
1039 version: RelayClient.CLOUDFLARED_VERSION,
1040 } as const;
1041 let installed = false;
1042 const spawned = yield* Deferred.make<string>();
1043 const spawner = ChildProcessSpawner.make((command) =>
1044 Effect.gen(function* () {
1045 yield* Deferred.succeed(
1046 spawned,
1047 ChildProcess.isStandardCommand(command) ? command.command : "",
1048 );
1049 const handle = makeHandle({ pid: 3, onKill: () => {} });
1050 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1051 return handle;
1052 }),
1053 );
1054 const runtime = yield* buildCloudManagedEndpointRuntime(
1055 spawner,
1056 Layer.succeed(
1057 RelayClient.RelayClient,
1058 RelayClient.RelayClient.of({
1059 resolve: Effect.sync(() =>
1060 installed
1061 ? pinnedClient
1062 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
1063 ),
1064 install: Effect.sync(() => {
1065 installed = true;
1066 return pinnedClient;
1067 }),
1068 installWithProgress: () => Effect.die("unused"),
1069 pruneManagedVersions: Effect.void,
1070 }),
1071 ),
1072 );
1073​
1074 const status = yield* runtime.applyConfig({
1075 providerKind: "cloudflare_tunnel",
1076 connectorToken: "token",
1077 });
1078 expect(status).toMatchObject({ status: "failed", failure: "not-installed" });
1079 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
1080 }),
1081 );
1082​
1083 it.effect("keeps the older connector when the updated relay client fails to start", () =>
1084 Effect.gen(function* () {
1085 const olderClient = {
1086 status: "available",
1087 executablePath: "/managed/2025.9.0/cloudflared",
1088 source: "managed",
1089 version: "2025.9.0",
1090 } as const;
1091 const pinnedClient = {
1092 status: "available",
1093 executablePath: "/managed/pinned/cloudflared",
1094 source: "managed",
1095 version: RelayClient.CLOUDFLARED_VERSION,
1096 } as const;
1097 let installed = false;
1098 let olderKilled = false;
1099 const releaseInstall = yield* Deferred.make<void>();
1100 const pinnedAttempted = yield* Deferred.make<void>();
1101 const spawner = ChildProcessSpawner.make((command) =>
1102 Effect.gen(function* () {
1103 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1104 if (executable === pinnedClient.executablePath) {
1105 yield* Deferred.succeed(pinnedAttempted, undefined);
1106 return yield* PlatformError.systemError({
1107 _tag: "PermissionDenied",
1108 module: "ChildProcess",
1109 method: "spawn",
1110 });
1112 const handle = makeHandle({
1113 pid: 6,
1114 onKill: () => {
1115 olderKilled = true;
1116 },
1117 });
1118 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1119 return handle;
1120 }),
1121 );
1122 const runtime = yield* buildCloudManagedEndpointRuntime(
1123 spawner,
1124 Layer.succeed(
1125 RelayClient.RelayClient,
1126 RelayClient.RelayClient.of({
1127 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1128 install: Deferred.await(releaseInstall).pipe(
1129 Effect.andThen(
1130 Effect.sync(() => {
1131 installed = true;
1132 return pinnedClient;
1133 }),
1134 ),
1135 ),
1136 installWithProgress: () => Effect.die("unused"),
1137 pruneManagedVersions: Effect.void,
1138 }),
1139 ),
1140 );
1141 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1142 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1143​
1144 yield* Deferred.succeed(releaseInstall, undefined);
1145 yield* Deferred.await(pinnedAttempted);
1146 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1147 expect(olderKilled).toBe(false);
1148 }),
1149 );
1150​
1151 it.effect("requests recovery when the older connector exited during a failed swap", () =>
1152 Effect.gen(function* () {
1153 const olderClient = {
1154 status: "available",
1155 executablePath: "/managed/2025.9.0/cloudflared",
1156 source: "managed",
1157 version: "2025.9.0",
1158 } as const;
1159 const pinnedClient = {
1160 status: "available",
1161 executablePath: "/managed/pinned/cloudflared",
1162 source: "managed",
1163 version: RelayClient.CLOUDFLARED_VERSION,
1164 } as const;
1165 let installed = false;
1166 const releaseInstall = yield* Deferred.make<void>();
1167 const spawner = ChildProcessSpawner.make((command) =>
1168 Effect.gen(function* () {
1169 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1170 if (executable === pinnedClient.executablePath) {
1171 return yield* PlatformError.systemError({
1172 _tag: "PermissionDenied",
1173 module: "ChildProcess",
1174 method: "spawn",
1175 });
1177 const handle = makeHandle({ pid: 12, onKill: () => {}, isRunning: () => !installed });
1178 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1179 return handle;
1180 }),
1181 );
1182 const runtime = yield* buildCloudManagedEndpointRuntime(
1183 spawner,
1184 Layer.succeed(
1185 RelayClient.RelayClient,
1186 RelayClient.RelayClient.of({
1187 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1188 install: Deferred.await(releaseInstall).pipe(
1189 Effect.andThen(
1190 Effect.sync(() => {
1191 installed = true;
1192 return pinnedClient;
1193 }),
1194 ),
1195 ),
1196 installWithProgress: () => Effect.die("unused"),
1197 pruneManagedVersions: Effect.void,
1198 }),
1199 ),
1200 );
1201 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1202 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 12 });
1203​
1204 yield* Deferred.succeed(releaseInstall, undefined);
1205 expect(Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
1206 }),
1207 );
1208​
1209 it.effect("restarts a self-updated pinned-folder connector once the pin is reinstalled", () =>
1210 Effect.gen(function* () {
1211 const executablePath = "/managed/pinned/cloudflared";
1212 let version = "2026.9.3";
1213 const releaseInstall = yield* Deferred.make<void>();
1214 const spawned = yield* Queue.unbounded<string>();
1215 const spawner = ChildProcessSpawner.make(() =>
1216 Effect.gen(function* () {
1217 yield* Queue.offer(spawned, version);
1218 const handle = makeHandle({ pid: 7, onKill: () => {} });
1219 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1220 return handle;
1221 }),
1222 );
1223 const current = () =>
1224 ({ status: "available", executablePath, source: "managed", version }) as const;
1225 const runtime = yield* buildCloudManagedEndpointRuntime(
1226 spawner,
1227 Layer.succeed(
1228 RelayClient.RelayClient,
1229 RelayClient.RelayClient.of({
1230 resolve: Effect.sync(current),
1231 install: Deferred.await(releaseInstall).pipe(
1232 Effect.andThen(
1233 Effect.sync(() => {
1234 version = RelayClient.CLOUDFLARED_VERSION;
1235 return current();
1236 }),
1237 ),
1238 ),
1239 installWithProgress: () => Effect.die("unused"),
1240 pruneManagedVersions: Effect.void,
1241 }),
1242 ),
1243 );
1244​
1245 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1246 expect(yield* Queue.take(spawned)).toBe("2026.9.3");
1247 yield* Deferred.succeed(releaseInstall, undefined);
1248 expect(yield* Queue.take(spawned)).toBe(RelayClient.CLOUDFLARED_VERSION);
1249 }),
1250 );
1251});