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

ManagedEndpointRuntime.test.ts

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