Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import { vi } from "vite-plus/test";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as PlatformError from "effect/PlatformError";
9import * as Sink from "effect/Sink";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12import * as RelayClient from "@t3tools/shared/relayClient";
13
14import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
15import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
16
17const relayClientAvailableLayer = Layer.succeed(
18 RelayClient.RelayClient,
19 RelayClient.RelayClient.of({
20 resolve: Effect.succeed({
21 status: "available",
22 executablePath: "cloudflared",
23 source: "path",
24 version: RelayClient.CLOUDFLARED_VERSION,
25 }),
26 install: Effect.die("unused"),
27 installWithProgress: () => Effect.die("unused"),
28 }),
29);
30
31const runtimeDependencies = (
32 spawner: ReturnType<typeof ChildProcessSpawner.make>,
33 relayClientLayer = relayClientAvailableLayer,
34) =>
35 Layer.mergeAll(
36 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
37 relayClientLayer,
38 Layer.mock(ServerSecretStore.ServerSecretStore)({
39 get: () => Effect.succeed(Option.none()),
40 }),
41 );
42
43const buildCloudManagedEndpointRuntime = (
44 spawner: ReturnType<typeof ChildProcessSpawner.make>,
45 relayClientLayer = relayClientAvailableLayer,
46) =>
47 Effect.gen(function* () {
48 const context = yield* Layer.build(
49 ManagedEndpointRuntime.layer.pipe(
50 Layer.provide(runtimeDependencies(spawner, relayClientLayer)),
51 ),
52 );
53 return yield* Effect.service(ManagedEndpointRuntime.CloudManagedEndpointRuntime).pipe(
54 Effect.provide(context),
55 );
56 });
57
58function makeHandle(input: {
59 readonly pid: number;
60 readonly onKill: () => void;
61 readonly isRunning?: () => boolean;
62 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
63}) {
64 return ChildProcessSpawner.makeHandle({
65 pid: ChildProcessSpawner.ProcessId(input.pid),
66 exitCode: input.exitCode ?? Effect.never,
67 isRunning: Effect.sync(() => input.isRunning?.() ?? true),
68 kill: () =>
69 Effect.sync(() => {
70 input.onKill();
71 }),
72 unref: Effect.succeed(Effect.void),
73 stdin: Sink.drain,
74 stdout: Stream.empty,
75 stderr: Stream.empty,
76 all: Stream.empty,
77 getInputFd: () => Sink.drain,
78 getOutputFd: () => Stream.empty,
79 });
80}
81
82describe("CloudManagedEndpointRuntime", () => {
83 it("classifies Cloudflare connection and warning output", () => {
84 expect(
85 ManagedEndpointRuntime.classifyRelayClientOutput(
86 "2026-06-17T02:00:00Z INF Registered tunnel connection connIndex=0",
87 ),
88 ).toBe("connected");
89 expect(
90 ManagedEndpointRuntime.classifyRelayClientOutput(
91 "2026-06-17T02:00:00Z ERR Failed to serve tunnel connection",
92 ),
93 ).toBe("warning");
94 expect(
95 ManagedEndpointRuntime.classifyRelayClientOutput(
96 "2026-06-17T02:00:00Z INF Starting metrics server",
97 ),
98 ).toBe("debug");
99 // FTL (fatal) and PNC (panic) are more severe than ERR and must surface.
100 expect(
101 ManagedEndpointRuntime.classifyRelayClientOutput(
102 "2026-06-17T02:00:00Z FTL Cannot determine default origin certificate path",
103 ),
104 ).toBe("warning");
105 expect(
106 ManagedEndpointRuntime.classifyRelayClientOutput("2026-06-17T02:00:00Z PNC runtime panic"),
107 ).toBe("warning");
108 });
109
110 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
111 Effect.gen(function* () {
112 const spawned: Array<ChildProcess.StandardCommand> = [];
113 const killed: Array<number> = [];
114 let nextPid = 100;
115 const spawner = ChildProcessSpawner.make((command) =>
116 Effect.gen(function* () {
117 if (!ChildProcess.isStandardCommand(command)) {
118 throw new Error("Expected standard command.");
119 }
120 spawned.push(command);
121 const pid = nextPid;
122 nextPid += 1;
123 const handle = makeHandle({
124 pid,
125 onKill: () => {
126 killed.push(pid);
127 },
128 });
129 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
130 return handle;
131 }),
132 );
133 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
134
135 yield* runtime.applyConfig({
136 providerKind: "cloudflare_tunnel",
137 connectorToken: "token-1",
138 tunnelId: "tunnel-1",
139 tunnelName: "t3-code-env-1",
140 });
141 yield* runtime.applyConfig({
142 providerKind: "cloudflare_tunnel",
143 connectorToken: "token-1",
144 tunnelId: "tunnel-1",
145 tunnelName: "t3-code-env-1",
146 });
147 yield* runtime.applyConfig({
148 providerKind: "cloudflare_tunnel",
149 connectorToken: "token-2",
150 tunnelId: "tunnel-1",
151 tunnelName: "t3-code-env-1",
152 });
153 const stopped = yield* runtime.applyConfig(null);
154
155 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
156 expect(spawned.map((command) => command.args)).toEqual([
157 ["tunnel", "run"],
158 ["tunnel", "run"],
159 ]);
160 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
161 "token-1",
162 "token-2",
163 ]);
164 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
165 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
166 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
167 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
168 expect(killed).toEqual([100, 101]);
169 expect(stopped).toEqual({ status: "disabled" });
170 }),
171 );
172
173 it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>
174 Effect.gen(function* () {
175 const killed: Array<number> = [];
176 const spawner = ChildProcessSpawner.make(() =>
177 Effect.gen(function* () {
178 const handle = makeHandle({
179 pid: 200,
180 onKill: () => {
181 killed.push(200);
182 },
183 });
184 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
185 return handle;
186 }),
187 );
188 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
189
190 const started = yield* runtime.applyConfig({
191 providerKind: "cloudflare_tunnel",
192 connectorToken: "token",
193 });
194 const unsupported = yield* runtime.applyConfig({
195 providerKind: "manual",
196 connectorToken: "manual-token",
197 });
198
199 expect(started.status).toBe("running");
200 expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
201 expect(killed).toEqual([200]);
202 }),
203 );
204
205 it.effect("restarts the connector when the active process has exited", () =>
206 Effect.gen(function* () {
207 const spawned: Array<number> = [];
208 const killed: Array<number> = [];
209 let firstRunning = true;
210 const spawner = ChildProcessSpawner.make(() =>
211 Effect.gen(function* () {
212 const pid = spawned.length === 0 ? 300 : 301;
213 spawned.push(pid);
214 const handle = makeHandle({
215 pid,
216 isRunning: () => (pid === 300 ? firstRunning : true),
217 onKill: () => {
218 killed.push(pid);
219 },
220 });
221 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
222 return handle;
223 }),
224 );
225 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
226 const config = {
227 providerKind: "cloudflare_tunnel" as const,
228 connectorToken: "token",
229 tunnelId: "tunnel-1",
230 };
231
232 const first = yield* runtime.applyConfig(config);
233 firstRunning = false;
234 const second = yield* runtime.applyConfig(config);
235
236 expect(first).toMatchObject({ status: "running", pid: 300 });
237 expect(second).toMatchObject({ status: "running", pid: 301 });
238 expect(spawned).toEqual([300, 301]);
239 expect(killed).toEqual([300]);
240 }),
241 );
242
243 it.effect("supervises the active connector and restarts it after process exit", () =>
244 Effect.gen(function* () {
245 const spawned: Array<number> = [];
246 const killed: Array<number> = [];
247 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
248 const secondSpawned = yield* Deferred.make<void>();
249 const spawner = ChildProcessSpawner.make(() =>
250 Effect.gen(function* () {
251 const pid = spawned.length === 0 ? 400 : 401;
252 spawned.push(pid);
253 if (pid === 401) {
254 yield* Deferred.succeed(secondSpawned, undefined);
255 }
256 const handle = makeHandle({
257 pid,
258 exitCode:
259 pid === 400
260 ? Deferred.await(firstExit)
261 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
262 onKill: () => {
263 killed.push(pid);
264 },
265 });
266 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
267 return handle;
268 }),
269 );
270 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
271
272 const started = yield* runtime.applyConfig({
273 providerKind: "cloudflare_tunnel",
274 connectorToken: "token",
275 tunnelId: "tunnel-1",
276 });
277 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
278 yield* Deferred.await(secondSpawned);
279
280 expect(started).toMatchObject({ status: "running", pid: 400 });
281 expect(spawned).toEqual([400, 401]);
282 expect(killed).toEqual([400]);
283 }),
284 );
285
286 it.effect("serializes concurrent connector config changes", () =>
287 Effect.gen(function* () {
288 const spawned: Array<number> = [];
289 const killed: Array<number> = [];
290 const firstSpawnEntered = yield* Deferred.make<void>();
291 const releaseFirstSpawn = yield* Deferred.make<void>();
292 const spawner = ChildProcessSpawner.make(() =>
293 Effect.gen(function* () {
294 const pid = 500 + spawned.length;
295 spawned.push(pid);
296 if (pid === 500) {
297 yield* Deferred.succeed(firstSpawnEntered, undefined);
298 yield* Deferred.await(releaseFirstSpawn);
299 }
300 const handle = makeHandle({
301 pid,
302 onKill: () => {
303 killed.push(pid);
304 },
305 });
306 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
307 return handle;
308 }),
309 );
310 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
311
312 const first = yield* runtime
313 .applyConfig({
314 providerKind: "cloudflare_tunnel",
315 connectorToken: "token-1",
316 })
317 .pipe(Effect.forkChild);
318 yield* Deferred.await(firstSpawnEntered);
319 const second = yield* runtime
320 .applyConfig({
321 providerKind: "cloudflare_tunnel",
322 connectorToken: "token-2",
323 })
324 .pipe(Effect.forkChild);
325 yield* Deferred.succeed(releaseFirstSpawn, undefined);
326
327 yield* Fiber.join(first);
328 const status = yield* Fiber.join(second);
329
330 expect(status).toMatchObject({ status: "running", pid: 501 });
331 expect(spawned).toEqual([500, 501]);
332 expect(killed).toEqual([500]);
333 }),
334 );
335
336 it.effect("reports connector spawn failures", () =>
337 Effect.gen(function* () {
338 const spawner = ChildProcessSpawner.make(() =>
339 Effect.fail(
340 PlatformError.systemError({
341 _tag: "NotFound",
342 module: "ChildProcess",
343 method: "spawn",
344 description: "cloudflared missing",
345 }),
346 ),
347 );
348 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
349
350 const status = yield* runtime.applyConfig({
351 providerKind: "cloudflare_tunnel",
352 connectorToken: "token",
353 tunnelId: "tunnel-1",
354 });
355
356 expect(status).toMatchObject({
357 status: "failed",
358 providerKind: "cloudflare_tunnel",
359 tunnelId: "tunnel-1",
360 });
361 }),
362 );
363
364 it.effect("reports a missing relay client executable without spawning", () =>
365 Effect.gen(function* () {
366 const spawn = vi.fn();
367 const spawner = ChildProcessSpawner.make(spawn);
368 const runtime = yield* buildCloudManagedEndpointRuntime(
369 spawner,
370 Layer.succeed(
371 RelayClient.RelayClient,
372 RelayClient.RelayClient.of({
373 resolve: Effect.succeed({
374 status: "missing",
375 version: RelayClient.CLOUDFLARED_VERSION,
376 }),
377 install: Effect.die("unused"),
378 installWithProgress: () => Effect.die("unused"),
379 }),
380 ),
381 );
382
383 const status = yield* runtime.applyConfig({
384 providerKind: "cloudflare_tunnel",
385 connectorToken: "token",
386 });
387
388 expect(status).toEqual({
389 status: "failed",
390 providerKind: "cloudflare_tunnel",
391 reason: "The relay client is not installed.",
392 });
393 expect(spawn).not.toHaveBeenCalled();
394 }),
395 );
396});