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