Open History to see the last commit
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 });
124}
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.each(["SIGINT", "SIGTERM"] as const)(
959 "does not restart a connector that exits after the server receives %s",
960 (signal) =>
961 Effect.gen(function* () {
962 const spawned: Array<number> = [];
963 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
964 const firstKilled = yield* Deferred.make<void>();
965 const spawner = ChildProcessSpawner.make(() =>
966 Effect.gen(function* () {
967 const pid = 400 + spawned.length;
968 spawned.push(pid);
969 const handle = makeHandle({
970 pid,
971 exitCode:
972 pid === 400
973 ? Deferred.await(firstExit)
974 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
975 onKill: () => {
976 if (pid === 400) Deferred.doneUnsafe(firstKilled, Exit.void);
977 },
978 });
979 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
980 return handle;
981 }),
982 );
983 // Invoke only the runtime's own listeners; emitting would reach the test worker's too.
984 const listenersBefore = new Set(process.listeners(signal));
985 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
986 const runtimeListeners = process
987 .listeners(signal)
988 .filter((listener) => !listenersBefore.has(listener));
989
990 yield* runtime.applyConfig({
991 providerKind: "cloudflare_tunnel",
992 connectorToken: "token",
993 tunnelId: "tunnel-1",
994 });
995 for (const listener of runtimeListeners) listener(signal);
996 // The process group receives the signal too, so the connector exits cleanly.
997 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(0));
998 yield* Deferred.await(firstKilled);
999 // Holding the reconcile lock waits out the supervisor's restart decision.
1000 yield* runtime.restartConnector(400, Effect.succeed(true));
1001
1002 expect(spawned).toEqual([400]);
1003 }),
1004 );
1005
1006 it.effect("serializes concurrent connector config changes", () =>
1007 Effect.gen(function* () {
1008 const spawned: Array<number> = [];
1009 const killed: Array<number> = [];
1010 const firstSpawnEntered = yield* Deferred.make<void>();
1011 const releaseFirstSpawn = yield* Deferred.make<void>();
1012 const spawner = ChildProcessSpawner.make(() =>
1013 Effect.gen(function* () {
1014 const pid = 500 + spawned.length;
1015 spawned.push(pid);
1016 if (pid === 500) {
1017 yield* Deferred.succeed(firstSpawnEntered, undefined);
1018 yield* Deferred.await(releaseFirstSpawn);
1019 }
1020 const handle = makeHandle({
1021 pid,
1022 onKill: () => {
1023 killed.push(pid);
1024 },
1025 });
1026 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1027 return handle;
1028 }),
1029 );
1030 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
1031
1032 const first = yield* runtime
1033 .applyConfig({
1034 providerKind: "cloudflare_tunnel",
1035 connectorToken: "token-1",
1036 })
1037 .pipe(Effect.forkChild);
1038 yield* Deferred.await(firstSpawnEntered);
1039 const second = yield* runtime
1040 .applyConfig({
1041 providerKind: "cloudflare_tunnel",
1042 connectorToken: "token-2",
1043 })
1044 .pipe(Effect.forkChild);
1045 yield* Deferred.succeed(releaseFirstSpawn, undefined);
1046
1047 yield* Fiber.join(first);
1048 const status = yield* Fiber.join(second);
1049
1050 expect(status).toMatchObject({ status: "running", pid: 501 });
1051 expect(spawned).toEqual([500, 501]);
1052 expect(killed).toEqual([500]);
1053 }),
1054 );
1055
1056 it.effect(
1057 "runs an older relay client while the pinned one installs, then hands off to it and prunes",
1058 () =>
1059 Effect.gen(function* () {
1060 const olderClient = {
1061 status: "available",
1062 executablePath: "/managed/2025.9.0/cloudflared",
1063 source: "managed",
1064 version: "2025.9.0",
1065 } as const;
1066 const pinnedClient = {
1067 status: "available",
1068 executablePath: "/managed/pinned/cloudflared",
1069 source: "managed",
1070 version: RelayClient.CLOUDFLARED_VERSION,
1071 } as const;
1072 let installed = false;
1073 const releaseInstall = yield* Deferred.make<void>();
1074 const pruned = yield* Deferred.make<void>();
1075 const spawned = yield* Queue.unbounded<string>();
1076 const olderStopped = yield* Deferred.make<void>();
1077 const output = yield* Queue.unbounded<Uint8Array>();
1078 const spawner = ChildProcessSpawner.make((command) =>
1079 Effect.gen(function* () {
1080 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1081 yield* Queue.offer(spawned, executable);
1082 const handle = makeHandle({
1083 pid: executable === pinnedClient.executablePath ? 2 : 1,
1084 onKill: () => {
1085 if (executable === olderClient.executablePath) {
1086 Deferred.doneUnsafe(olderStopped, Effect.void);
1087 }
1088 },
1089 ...(executable === pinnedClient.executablePath
1090 ? { output: Stream.fromQueue(output) }
1091 : {}),
1092 });
1093 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1094 return handle;
1095 }),
1096 );
1097 const runtime = yield* buildCloudManagedEndpointRuntime(
1098 spawner,
1099 Layer.succeed(
1100 RelayClient.RelayClient,
1101 RelayClient.RelayClient.of({
1102 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1103 install: Deferred.await(releaseInstall).pipe(
1104 Effect.andThen(
1105 Effect.sync(() => {
1106 installed = true;
1107 return pinnedClient;
1108 }),
1109 ),
1110 ),
1111 installWithProgress: () => Effect.die("unused"),
1112 pruneManagedVersions: Deferred.succeed(pruned, undefined).pipe(Effect.asVoid),
1113 }),
1114 ),
1115 );
1116
1117 const status = yield* runtime.applyConfig({
1118 providerKind: "cloudflare_tunnel",
1119 connectorToken: "token",
1120 });
1121 expect(status).toMatchObject({ status: "running", pid: 1 });
1122 expect(yield* Queue.take(spawned)).toBe(olderClient.executablePath);
1123
1124 yield* Deferred.succeed(releaseInstall, undefined);
1125 expect(yield* Queue.take(spawned)).toBe(pinnedClient.executablePath);
1126 expect(Option.isNone(yield* Deferred.poll(olderStopped))).toBe(true);
1127
1128 yield* Queue.offer(
1129 output,
1130 new TextEncoder().encode(
1131 "2026-10-08T00:00:00Z INF Registered tunnel connection connIndex=0\n",
1132 ),
1133 );
1134 yield* Deferred.await(olderStopped);
1135 yield* Deferred.await(pruned);
1136 }),
1137 );
1138
1139 it.effect("installs a missing relay client in the background and then starts it", () =>
1140 Effect.gen(function* () {
1141 const pinnedClient = {
1142 status: "available",
1143 executablePath: "/managed/pinned/cloudflared",
1144 source: "managed",
1145 version: RelayClient.CLOUDFLARED_VERSION,
1146 } as const;
1147 let installed = false;
1148 const spawned = yield* Deferred.make<string>();
1149 const spawner = ChildProcessSpawner.make((command) =>
1150 Effect.gen(function* () {
1151 yield* Deferred.succeed(
1152 spawned,
1153 ChildProcess.isStandardCommand(command) ? command.command : "",
1154 );
1155 const handle = makeHandle({ pid: 3, onKill: () => {} });
1156 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1157 return handle;
1158 }),
1159 );
1160 const runtime = yield* buildCloudManagedEndpointRuntime(
1161 spawner,
1162 Layer.succeed(
1163 RelayClient.RelayClient,
1164 RelayClient.RelayClient.of({
1165 resolve: Effect.sync(() =>
1166 installed
1167 ? pinnedClient
1168 : { status: "missing" as const, version: RelayClient.CLOUDFLARED_VERSION },
1169 ),
1170 install: Effect.sync(() => {
1171 installed = true;
1172 return pinnedClient;
1173 }),
1174 installWithProgress: () => Effect.die("unused"),
1175 pruneManagedVersions: Effect.void,
1176 }),
1177 ),
1178 );
1179
1180 const status = yield* runtime.applyConfig({
1181 providerKind: "cloudflare_tunnel",
1182 connectorToken: "token",
1183 });
1184 expect(status).toMatchObject({ status: "failed", failure: "not-installed" });
1185 expect(yield* Deferred.await(spawned)).toBe(pinnedClient.executablePath);
1186 }),
1187 );
1188
1189 it.effect("keeps the older connector when the updated relay client fails to start", () =>
1190 Effect.gen(function* () {
1191 const olderClient = {
1192 status: "available",
1193 executablePath: "/managed/2025.9.0/cloudflared",
1194 source: "managed",
1195 version: "2025.9.0",
1196 } as const;
1197 const pinnedClient = {
1198 status: "available",
1199 executablePath: "/managed/pinned/cloudflared",
1200 source: "managed",
1201 version: RelayClient.CLOUDFLARED_VERSION,
1202 } as const;
1203 let installed = false;
1204 let olderKilled = false;
1205 const releaseInstall = yield* Deferred.make<void>();
1206 const pinnedAttempted = yield* Deferred.make<void>();
1207 const spawner = ChildProcessSpawner.make((command) =>
1208 Effect.gen(function* () {
1209 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1210 if (executable === pinnedClient.executablePath) {
1211 yield* Deferred.succeed(pinnedAttempted, undefined);
1212 return yield* PlatformError.systemError({
1213 _tag: "PermissionDenied",
1214 module: "ChildProcess",
1215 method: "spawn",
1216 });
1217 }
1218 const handle = makeHandle({
1219 pid: 6,
1220 onKill: () => {
1221 olderKilled = true;
1222 },
1223 });
1224 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1225 return handle;
1226 }),
1227 );
1228 const runtime = yield* buildCloudManagedEndpointRuntime(
1229 spawner,
1230 Layer.succeed(
1231 RelayClient.RelayClient,
1232 RelayClient.RelayClient.of({
1233 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1234 install: Deferred.await(releaseInstall).pipe(
1235 Effect.andThen(
1236 Effect.sync(() => {
1237 installed = true;
1238 return pinnedClient;
1239 }),
1240 ),
1241 ),
1242 installWithProgress: () => Effect.die("unused"),
1243 pruneManagedVersions: Effect.void,
1244 }),
1245 ),
1246 );
1247 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1248 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1249
1250 yield* Deferred.succeed(releaseInstall, undefined);
1251 yield* Deferred.await(pinnedAttempted);
1252 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 6 });
1253 expect(olderKilled).toBe(false);
1254 }),
1255 );
1256
1257 it.effect("requests recovery when the older connector exited during a failed swap", () =>
1258 Effect.gen(function* () {
1259 const olderClient = {
1260 status: "available",
1261 executablePath: "/managed/2025.9.0/cloudflared",
1262 source: "managed",
1263 version: "2025.9.0",
1264 } as const;
1265 const pinnedClient = {
1266 status: "available",
1267 executablePath: "/managed/pinned/cloudflared",
1268 source: "managed",
1269 version: RelayClient.CLOUDFLARED_VERSION,
1270 } as const;
1271 let installed = false;
1272 const releaseInstall = yield* Deferred.make<void>();
1273 const spawner = ChildProcessSpawner.make((command) =>
1274 Effect.gen(function* () {
1275 const executable = ChildProcess.isStandardCommand(command) ? command.command : "";
1276 if (executable === pinnedClient.executablePath) {
1277 return yield* PlatformError.systemError({
1278 _tag: "PermissionDenied",
1279 module: "ChildProcess",
1280 method: "spawn",
1281 });
1282 }
1283 const handle = makeHandle({ pid: 12, onKill: () => {}, isRunning: () => !installed });
1284 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1285 return handle;
1286 }),
1287 );
1288 const runtime = yield* buildCloudManagedEndpointRuntime(
1289 spawner,
1290 Layer.succeed(
1291 RelayClient.RelayClient,
1292 RelayClient.RelayClient.of({
1293 resolve: Effect.sync(() => (installed ? pinnedClient : olderClient)),
1294 install: Deferred.await(releaseInstall).pipe(
1295 Effect.andThen(
1296 Effect.sync(() => {
1297 installed = true;
1298 return pinnedClient;
1299 }),
1300 ),
1301 ),
1302 installWithProgress: () => Effect.die("unused"),
1303 pruneManagedVersions: Effect.void,
1304 }),
1305 ),
1306 );
1307 const config = { providerKind: "cloudflare_tunnel", connectorToken: "token" } as const;
1308 expect(yield* runtime.applyConfig(config)).toMatchObject({ status: "running", pid: 12 });
1309
1310 yield* Deferred.succeed(releaseInstall, undefined);
1311 expect(Option.getOrThrow(yield* Stream.runHead(runtime.recoveryRequests))).toEqual(config);
1312 }),
1313 );
1314
1315 it.effect("restarts a self-updated pinned-folder connector once the pin is reinstalled", () =>
1316 Effect.gen(function* () {
1317 const executablePath = "/managed/pinned/cloudflared";
1318 let version = "2026.9.3";
1319 const releaseInstall = yield* Deferred.make<void>();
1320 const spawned = yield* Queue.unbounded<string>();
1321 const spawner = ChildProcessSpawner.make(() =>
1322 Effect.gen(function* () {
1323 yield* Queue.offer(spawned, version);
1324 const handle = makeHandle({ pid: 7, onKill: () => {} });
1325 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
1326 return handle;
1327 }),
1328 );
1329 const current = () =>
1330 ({ status: "available", executablePath, source: "managed", version }) as const;
1331 const runtime = yield* buildCloudManagedEndpointRuntime(
1332 spawner,
1333 Layer.succeed(
1334 RelayClient.RelayClient,
1335 RelayClient.RelayClient.of({
1336 resolve: Effect.sync(current),
1337 install: Deferred.await(releaseInstall).pipe(
1338 Effect.andThen(
1339 Effect.sync(() => {
1340 version = RelayClient.CLOUDFLARED_VERSION;
1341 return current();
1342 }),
1343 ),
1344 ),
1345 installWithProgress: () => Effect.die("unused"),
1346 pruneManagedVersions: Effect.void,
1347 }),
1348 ),
1349 );
1350
1351 yield* runtime.applyConfig({ providerKind: "cloudflare_tunnel", connectorToken: "token" });
1352 expect(yield* Queue.take(spawned)).toBe("2026.9.3");
1353 yield* Deferred.succeed(releaseInstall, undefined);
1354 expect(yield* Queue.take(spawned)).toBe(RelayClient.CLOUDFLARED_VERSION);
1355 }),
1356 );
1357});