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 });
100
101 it.effect("starts, deduplicates, rotates, and stops the Cloudflare connector", () =>
102 Effect.gen(function* () {
103 const spawned: Array<ChildProcess.StandardCommand> = [];
104 const killed: Array<number> = [];
105 let nextPid = 100;
106 const spawner = ChildProcessSpawner.make((command) =>
107 Effect.gen(function* () {
108 if (!ChildProcess.isStandardCommand(command)) {
109 throw new Error("Expected standard command.");
110 }
111 spawned.push(command);
112 const pid = nextPid;
113 nextPid += 1;
114 const handle = makeHandle({
115 pid,
116 onKill: () => {
117 killed.push(pid);
118 },
119 });
120 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
121 return handle;
122 }),
123 );
124 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
125
126 yield* runtime.applyConfig({
127 providerKind: "cloudflare_tunnel",
128 connectorToken: "token-1",
129 tunnelId: "tunnel-1",
130 tunnelName: "t3-code-env-1",
131 });
132 yield* runtime.applyConfig({
133 providerKind: "cloudflare_tunnel",
134 connectorToken: "token-1",
135 tunnelId: "tunnel-1",
136 tunnelName: "t3-code-env-1",
137 });
138 yield* runtime.applyConfig({
139 providerKind: "cloudflare_tunnel",
140 connectorToken: "token-2",
141 tunnelId: "tunnel-1",
142 tunnelName: "t3-code-env-1",
143 });
144 const stopped = yield* runtime.applyConfig(null);
145
146 expect(spawned.map((command) => command.command)).toEqual(["cloudflared", "cloudflared"]);
147 expect(spawned.map((command) => command.args)).toEqual([
148 ["tunnel", "run"],
149 ["tunnel", "run"],
150 ]);
151 expect(spawned.map((command) => command.options.env?.TUNNEL_TOKEN)).toEqual([
152 "token-1",
153 "token-2",
154 ]);
155 expect(spawned.map((command) => command.options.stdout)).toEqual(["pipe", "pipe"]);
156 expect(spawned.map((command) => command.options.stderr)).toEqual(["pipe", "pipe"]);
157 expect(spawned.map((command) => command.options.detached)).toEqual([false, false]);
158 expect(spawned.map((command) => command.options.shell)).toEqual([false, false]);
159 expect(killed).toEqual([100, 101]);
160 expect(stopped).toEqual({ status: "disabled" });
161 }),
162 );
163
164 it.effect("stops an active connector when a non-Cloudflare runtime config is applied", () =>
165 Effect.gen(function* () {
166 const killed: Array<number> = [];
167 const spawner = ChildProcessSpawner.make(() =>
168 Effect.gen(function* () {
169 const handle = makeHandle({
170 pid: 200,
171 onKill: () => {
172 killed.push(200);
173 },
174 });
175 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
176 return handle;
177 }),
178 );
179 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
180
181 const started = yield* runtime.applyConfig({
182 providerKind: "cloudflare_tunnel",
183 connectorToken: "token",
184 });
185 const unsupported = yield* runtime.applyConfig({
186 providerKind: "manual",
187 connectorToken: "manual-token",
188 });
189
190 expect(started.status).toBe("running");
191 expect(unsupported).toEqual({ status: "unsupported", providerKind: "manual" });
192 expect(killed).toEqual([200]);
193 }),
194 );
195
196 it.effect("restarts the connector when the active process has exited", () =>
197 Effect.gen(function* () {
198 const spawned: Array<number> = [];
199 const killed: Array<number> = [];
200 let firstRunning = true;
201 const spawner = ChildProcessSpawner.make(() =>
202 Effect.gen(function* () {
203 const pid = spawned.length === 0 ? 300 : 301;
204 spawned.push(pid);
205 const handle = makeHandle({
206 pid,
207 isRunning: () => (pid === 300 ? firstRunning : true),
208 onKill: () => {
209 killed.push(pid);
210 },
211 });
212 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
213 return handle;
214 }),
215 );
216 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
217 const config = {
218 providerKind: "cloudflare_tunnel" as const,
219 connectorToken: "token",
220 tunnelId: "tunnel-1",
221 };
222
223 const first = yield* runtime.applyConfig(config);
224 firstRunning = false;
225 const second = yield* runtime.applyConfig(config);
226
227 expect(first).toMatchObject({ status: "running", pid: 300 });
228 expect(second).toMatchObject({ status: "running", pid: 301 });
229 expect(spawned).toEqual([300, 301]);
230 expect(killed).toEqual([300]);
231 }),
232 );
233
234 it.effect("supervises the active connector and restarts it after process exit", () =>
235 Effect.gen(function* () {
236 const spawned: Array<number> = [];
237 const killed: Array<number> = [];
238 const firstExit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
239 const secondSpawned = yield* Deferred.make<void>();
240 const spawner = ChildProcessSpawner.make(() =>
241 Effect.gen(function* () {
242 const pid = spawned.length === 0 ? 400 : 401;
243 spawned.push(pid);
244 if (pid === 401) {
245 yield* Deferred.succeed(secondSpawned, undefined);
246 }
247 const handle = makeHandle({
248 pid,
249 exitCode:
250 pid === 400
251 ? Deferred.await(firstExit)
252 : (Effect.never as Effect.Effect<ChildProcessSpawner.ExitCode>),
253 onKill: () => {
254 killed.push(pid);
255 },
256 });
257 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
258 return handle;
259 }),
260 );
261 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
262
263 const started = yield* runtime.applyConfig({
264 providerKind: "cloudflare_tunnel",
265 connectorToken: "token",
266 tunnelId: "tunnel-1",
267 });
268 yield* Deferred.succeed(firstExit, ChildProcessSpawner.ExitCode(1));
269 yield* Deferred.await(secondSpawned);
270
271 expect(started).toMatchObject({ status: "running", pid: 400 });
272 expect(spawned).toEqual([400, 401]);
273 expect(killed).toEqual([400]);
274 }),
275 );
276
277 it.effect("serializes concurrent connector config changes", () =>
278 Effect.gen(function* () {
279 const spawned: Array<number> = [];
280 const killed: Array<number> = [];
281 const firstSpawnEntered = yield* Deferred.make<void>();
282 const releaseFirstSpawn = yield* Deferred.make<void>();
283 const spawner = ChildProcessSpawner.make(() =>
284 Effect.gen(function* () {
285 const pid = 500 + spawned.length;
286 spawned.push(pid);
287 if (pid === 500) {
288 yield* Deferred.succeed(firstSpawnEntered, undefined);
289 yield* Deferred.await(releaseFirstSpawn);
290 }
291 const handle = makeHandle({
292 pid,
293 onKill: () => {
294 killed.push(pid);
295 },
296 });
297 yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
298 return handle;
299 }),
300 );
301 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
302
303 const first = yield* runtime
304 .applyConfig({
305 providerKind: "cloudflare_tunnel",
306 connectorToken: "token-1",
307 })
308 .pipe(Effect.forkChild);
309 yield* Deferred.await(firstSpawnEntered);
310 const second = yield* runtime
311 .applyConfig({
312 providerKind: "cloudflare_tunnel",
313 connectorToken: "token-2",
314 })
315 .pipe(Effect.forkChild);
316 yield* Deferred.succeed(releaseFirstSpawn, undefined);
317
318 yield* Fiber.join(first);
319 const status = yield* Fiber.join(second);
320
321 expect(status).toMatchObject({ status: "running", pid: 501 });
322 expect(spawned).toEqual([500, 501]);
323 expect(killed).toEqual([500]);
324 }),
325 );
326
327 it.effect("reports connector spawn failures", () =>
328 Effect.gen(function* () {
329 const spawner = ChildProcessSpawner.make(() =>
330 Effect.fail(
331 PlatformError.systemError({
332 _tag: "NotFound",
333 module: "ChildProcess",
334 method: "spawn",
335 description: "cloudflared missing",
336 }),
337 ),
338 );
339 const runtime = yield* buildCloudManagedEndpointRuntime(spawner);
340
341 const status = yield* runtime.applyConfig({
342 providerKind: "cloudflare_tunnel",
343 connectorToken: "token",
344 tunnelId: "tunnel-1",
345 });
346
347 expect(status).toMatchObject({
348 status: "failed",
349 providerKind: "cloudflare_tunnel",
350 tunnelId: "tunnel-1",
351 });
352 }),
353 );
354
355 it.effect("reports a missing relay client executable without spawning", () =>
356 Effect.gen(function* () {
357 const spawn = vi.fn();
358 const spawner = ChildProcessSpawner.make(spawn);
359 const runtime = yield* buildCloudManagedEndpointRuntime(
360 spawner,
361 Layer.succeed(
362 RelayClient.RelayClient,
363 RelayClient.RelayClient.of({
364 resolve: Effect.succeed({
365 status: "missing",
366 version: RelayClient.CLOUDFLARED_VERSION,
367 }),
368 install: Effect.die("unused"),
369 installWithProgress: () => Effect.die("unused"),
370 }),
371 ),
372 );
373
374 const status = yield* runtime.applyConfig({
375 providerKind: "cloudflare_tunnel",
376 connectorToken: "token",
377 });
378
379 expect(status).toEqual({
380 status: "failed",
381 providerKind: "cloudflare_tunnel",
382 reason: "The relay client is not installed.",
383 });
384 expect(spawn).not.toHaveBeenCalled();
385 }),
386 );
387});