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

relayClient.test.ts

1,018 lines39.2 KB

1import { sha256 } from "@noble/hashes/sha2";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { describe, expect, it } from "@effect/vitest";
5import * as Clock from "effect/Clock";
6import * as ConfigProvider from "effect/ConfigProvider";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Fiber from "effect/Fiber";
10import * as Hex from "effect/encoding/Hex";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as PlatformError from "effect/PlatformError";
15import * as Sink from "effect/Sink";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18import { HttpClient, HttpClientResponse } from "effect/http";
19import { ChildProcess, ChildProcessSpawner } from "effect/process";
20import * as HostProcess from "./HostProcess.ts";
21​
22import * as RelayClient from "./relayClient.ts";
23​
24// POSIX exec-bit checks do not apply on NTFS.
25const windowsHost = HostProcess.Platform.defaultValue() === "win32";
26​
27const layerHostRuntime = (env: Record<string, string> = {}, platform: NodeJS.Platform = "linux") =>
28 Layer.mergeAll(
29 Layer.succeed(HostProcess.Platform, platform),
30 Layer.succeed(HostProcess.Architecture, "x64"),
31 Layer.succeed(HostProcess.Environment, env),
32 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
33 );
34​
35function makeHandle(exitCode = 0, output = "") {
36 const stdout = output ? Stream.make(new TextEncoder().encode(output)) : Stream.empty;
37 return ChildProcessSpawner.makeHandle({
38 pid: ChildProcessSpawner.ProcessId(100),
39 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
40 exitStatus: Effect.succeed({ _tag: "Exited", code: ChildProcessSpawner.ExitCode(exitCode) }),
41 isRunning: Effect.succeed(false),
42 kill: () => Effect.void,
43 unref: Effect.succeed(Effect.void),
44 stdin: Sink.drain,
45 stdout,
46 stderr: Stream.empty,
47 all: stdout,
48 getInputFd: () => Sink.drain,
49 getOutputFd: () => Stream.empty,
50 });
52​
53const layerHttpClient = (bytes: Uint8Array) =>
54 Layer.succeed(
55 HttpClient.HttpClient,
56 HttpClient.make((request) =>
57 Effect.succeed(
58 HttpClientResponse.fromWeb(request, new Response(bytes.buffer as ArrayBuffer)),
59 ),
60 ),
61 );
62​
63const layerSpawner = (commands: Array<string>, versions: Record<string, string> = {}) =>
64 Layer.succeed(
65 ChildProcessSpawner.ChildProcessSpawner,
66 ChildProcessSpawner.make((command) =>
67 Effect.sync(() => {
68 if (!ChildProcess.isStandardCommand(command)) {
69 commands.push("piped-command");
70 return makeHandle();
71 }
72 commands.push(command.command);
73 if (command.args[0] === "version") {
74 const version = versions[command.command] ?? RelayClient.CLOUDFLARED_VERSION;
75 return makeHandle(0, `cloudflared version ${version} (built 2026-01-01-00:00 UTC)\n`);
76 }
77 return makeHandle();
78 }),
79 ),
80 );
81​
82const writeExecutable = (filePath: string, contents = "cloudflared") =>
83 Effect.gen(function* () {
84 const fileSystem = yield* FileSystem.FileSystem;
85 yield* fileSystem.makeDirectory(filePath.slice(0, filePath.lastIndexOf("/")), {
86 recursive: true,
87 });
88 yield* fileSystem.writeFileString(filePath, contents);
89 yield* fileSystem.chmod(filePath, 0o755);
90 });
91​
92type RelayClientTestServices =
93 | Layer.Success<
94 ReturnType<typeof layerHostRuntime> | typeof NodeServices.layer | typeof NodeCrypto.layer
95 >
96 | HttpClient.HttpClient
97 | ChildProcessSpawner.ChildProcessSpawner;
98​
99const managedPathFor = (baseDir: string, version: string) =>
100 `${baseDir}/tools/cloudflared/${version}/linux-x64/cloudflared`;
101​
102const renameError = (code: string, path: string) =>
103 PlatformError.systemError({
104 _tag: code === "EBUSY" ? "Busy" : code === "EACCES" ? "PermissionDenied" : "Unknown",
105 module: "FileSystem",
106 method: "rename",
107 pathOrDescriptor: path,
108 cause: Object.assign(new Error(code), { code }),
109 });
110​
111type InstallRename = "staging" | "activation";
112​
113const makeLockedRenames = (
114 fileSystem: FileSystem.FileSystem,
115 input: { readonly rename: InstallRename; readonly failures: number; readonly code: string },
116) =>
117 Effect.gen(function* () {
118 const firstAttempt = yield* Deferred.make<void>();
119 const renames = { attempts: 0 };
120 const locked = FileSystem.make({
121 ...fileSystem,
122 rename: (from, to) =>
123 Effect.suspend(() => {
124 if ((to.endsWith(".tmp") ? "staging" : "activation") !== input.rename) {
125 return fileSystem.rename(from, to);
126 }
127 renames.attempts += 1;
128 return renames.attempts <= input.failures
129 ? Deferred.succeed(firstAttempt, undefined).pipe(
130 Effect.andThen(Effect.fail(renameError(input.code, to))),
131 )
132 : fileSystem.rename(from, to);
133 }),
134 });
135 return { locked, renames, firstAttempt };
136 });
137​
138const testBinary = new TextEncoder().encode("test-cloudflared-binary");
139const testReleaseAsset = {
140 url: "https://example.test/cloudflared",
141 sha256: Hex.encode(sha256(testBinary)),
142 archive: "binary",
143} as const;
144​
145const layerInstallRuntime = (platform: NodeJS.Platform) =>
146 Layer.mergeAll(
147 NodeServices.layer,
148 NodeCrypto.layer,
149 layerHttpClient(testBinary),
150 layerSpawner([]),
151 layerHostRuntime({ PATH: "" }, platform),
152 );
153​
154describe("RelayClient", () => {
155 it.effect("cancels a contended install without removing the other installer's lock", () =>
156 Effect.gen(function* () {
157 const fileSystem = yield* FileSystem.FileSystem;
158 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
159 const directory = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64`;
160 const lockPath = `${directory}/cloudflared.lock`;
161 yield* fileSystem.makeDirectory(directory, { recursive: true });
162 yield* fileSystem.writeFileString(lockPath, "other-installer");
163 const contended = yield* Deferred.make<void>();
164 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(
165 Effect.provideService(FileSystem.FileSystem, {
166 ...fileSystem,
167 rename: (from, to) =>
168 fileSystem
169 .rename(from, to)
170 .pipe(
171 Effect.tapError(() =>
172 to === lockPath ? Deferred.succeed(contended, undefined) : Effect.void,
173 ),
174 ),
175 }),
176 );
177 const installing = yield* manager.install.pipe(Effect.forkChild);
178 yield* Deferred.await(contended);
179 yield* Fiber.interrupt(installing);
180 expect(yield* fileSystem.readFileString(lockPath)).toBe("other-installer");
181 }).pipe(
182 Effect.scoped,
183 Effect.provide(
184 Layer.mergeAll(
185 NodeServices.layer,
186 NodeCrypto.layer,
187 layerHttpClient(new Uint8Array()),
188 layerSpawner([]),
189 layerHostRuntime({ PATH: "" }),
190 ),
191 ),
192 ),
193 );
194​
195 it.effect.each(["live owner", "recent legacy"] as const)("keeps a lock with a %s", (kind) =>
196 Effect.gen(function* () {
197 const fileSystem = yield* FileSystem.FileSystem;
198 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
199 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
200 const owner = `${process.pid}-still-running`;
201 yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {
202 recursive: true,
203 });
204 if (kind === "live owner") {
205 yield* fileSystem.makeDirectory(lockPath);
206 yield* fileSystem.writeFileString(`${lockPath}/${owner}`, "");
207 } else {
208 yield* fileSystem.writeFileString(lockPath, "");
209 }
210 const written = yield* fileSystem.stat(lockPath);
211 yield* TestClock.setTime(
212 Option.getOrThrow(written.mtime).getTime() + (kind === "live owner" ? 3_600_000 : 6_000),
213 );
214 const waiting = yield* Deferred.make<void>();
215 const clock = yield* Clock.Clock;
216 const manager = yield* RelayClient.makeCloudflaredRelayClient({
217 baseDir,
218 releaseAsset: testReleaseAsset,
219 });
220 const installing = yield* manager.install.pipe(
221 Effect.provideService(Clock.Clock, {
222 ...clock,
223 sleep: () => Deferred.succeed(waiting, undefined).pipe(Effect.andThen(Effect.never)),
224 }),
225 Effect.forkChild,
226 );
227 yield* Deferred.await(waiting);
228 yield* Fiber.interrupt(installing);
229 if (kind === "live owner") {
230 expect(yield* fileSystem.readDirectory(lockPath)).toEqual([owner]);
231 } else {
232 expect(yield* fileSystem.readFileString(lockPath)).toBe("");
233 }
234 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
235 );
236​
237 it.effect.skipIf(windowsHost)("replaces an install lock left by an exited installer", () =>
238 Effect.gen(function* () {
239 const fileSystem = yield* FileSystem.FileSystem;
240 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
241 prefix: "t3-cloudflared-test-",
242 });
243 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
244 yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {
245 recursive: true,
246 });
247 yield* fileSystem.makeDirectory(lockPath);
248 yield* fileSystem.writeFileString(`${lockPath}/2147483647-exited-installer`, "");
249 const manager = yield* RelayClient.makeCloudflaredRelayClient({
250 baseDir,
251 releaseAsset: testReleaseAsset,
252 });
253​
254 expect(yield* manager.install).toMatchObject({ status: "available" });
255 expect(yield* fileSystem.exists(lockPath)).toBe(false);
256 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
257 );
258​
259 it.effect.skipIf(windowsHost)("replaces an empty install lock left by an exited installer", () =>
260 Effect.gen(function* () {
261 const fileSystem = yield* FileSystem.FileSystem;
262 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
263 prefix: "t3-cloudflared-test-",
264 });
265 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
266 yield* fileSystem.makeDirectory(lockPath.slice(0, lockPath.lastIndexOf("/")), {
267 recursive: true,
268 });
269 yield* fileSystem.writeFileString(lockPath, "");
270 const written = yield* fileSystem.stat(lockPath);
271 const mtime = Option.getOrThrow(written.mtime).getTime();
272 // File mtimes use wall time; advance the test clock past legacy expiry.
273 yield* TestClock.setTime(mtime + 60 * 60 * 1_000);
274 const manager = yield* RelayClient.makeCloudflaredRelayClient({
275 baseDir,
276 releaseAsset: testReleaseAsset,
277 });
278​
279 expect(yield* manager.install).toMatchObject({ status: "available" });
280 expect(yield* fileSystem.exists(lockPath)).toBe(false);
281 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
282 );
283​
284 it.effect("keeps a replacement lock when a stale contender resumes cleanup", () =>
285 Effect.gen(function* () {
286 const fileSystem = yield* FileSystem.FileSystem;
287 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
288 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
289 const abandoned = "2147483647-exited-installer";
290 const replacement = `${process.pid}-replacement`;
291 yield* fileSystem.makeDirectory(lockPath, { recursive: true });
292 yield* fileSystem.writeFileString(`${lockPath}/${abandoned}`, "");
293 const checked = yield* Deferred.make<void>();
294 let replaced = false;
295 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir }).pipe(
296 Effect.provideService(FileSystem.FileSystem, {
297 ...fileSystem,
298 readDirectory: (path) =>
299 fileSystem.readDirectory(path).pipe(
300 Effect.tap((entries) =>
301 Effect.gen(function* () {
302 if (path !== lockPath) return;
303 if (replaced) {
304 expect(entries).toEqual([replacement]);
305 yield* Deferred.succeed(checked, undefined);
306 return;
307 }
308 replaced = true;
309 yield* fileSystem.rename(lockPath, `${lockPath}.old`);
310 yield* fileSystem.makeDirectory(lockPath);
311 yield* fileSystem.writeFileString(`${lockPath}/${replacement}`, "");
312 }),
313 ),
314 ),
315 }),
316 );
317 const installing = yield* manager.install.pipe(Effect.forkChild);
318 yield* Deferred.await(checked);
319 yield* Fiber.interrupt(installing);
320 expect(yield* fileSystem.readDirectory(lockPath)).toEqual([replacement]);
321 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
322 );
323​
324 it.effect("releases the install lock when a download is cancelled", () =>
325 Effect.gen(function* () {
326 const fileSystem = yield* FileSystem.FileSystem;
327 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
328 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
329 const downloading = yield* Deferred.make<void>();
330 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
331 const installing = yield* manager
332 .installWithProgress((event) =>
333 event.type === "progress" && event.stage === "downloading"
334 ? Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never))
335 : Effect.void,
336 )
337 .pipe(Effect.forkChild);
338 yield* Deferred.await(downloading);
339 expect(yield* fileSystem.exists(lockPath)).toBe(true);
340 yield* Fiber.interrupt(installing);
341 expect(yield* fileSystem.exists(lockPath)).toBe(false);
342 }).pipe(
343 Effect.scoped,
344 Effect.provide(
345 Layer.mergeAll(
346 NodeServices.layer,
347 NodeCrypto.layer,
348 layerHttpClient(new Uint8Array()),
349 layerSpawner([]),
350 layerHostRuntime({ PATH: "" }),
351 ),
352 ),
353 ),
354 );
355​
356 it.effect.skipIf(windowsHost)("releases a lock acquired while installation is cancelled", () =>
357 Effect.gen(function* () {
358 const fileSystem = yield* FileSystem.FileSystem;
359 const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-cloudflared-test-" });
360 const lockPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`;
361 const acquired = yield* Deferred.make<void>();
362 const completeWrite = yield* Deferred.make<void>();
363 let pauseWrite = true;
364 const manager = yield* RelayClient.makeCloudflaredRelayClient({
365 baseDir,
366 releaseAsset: {
367 url: "https://example.test/cloudflared",
368 sha256: Hex.encode(sha256(new TextEncoder().encode("test-binary"))),
369 archive: "binary",
370 },
371 }).pipe(
372 Effect.provideService(FileSystem.FileSystem, {
373 ...fileSystem,
374 rename: (from, to) =>
375 fileSystem
376 .rename(from, to)
377 .pipe(
378 Effect.tap(() =>
379 to === lockPath && pauseWrite
380 ? Deferred.succeed(acquired, undefined).pipe(
381 Effect.andThen(Deferred.await(completeWrite)),
382 )
383 : Effect.void,
384 ),
385 ),
386 }),
387 );
388​
389 const installing = yield* manager.install.pipe(Effect.forkChild);
390 yield* Deferred.await(acquired);
391 const cancelling = yield* Fiber.interrupt(installing).pipe(
392 Effect.forkChild({ startImmediately: true }),
393 );
394 yield* Deferred.succeed(completeWrite, undefined);
395 yield* Fiber.join(cancelling);
396 expect(yield* fileSystem.exists(lockPath)).toBe(false);
397​
398 pauseWrite = false;
399 expect(yield* manager.install).toMatchObject({ status: "available" });
400 expect(yield* fileSystem.exists(lockPath)).toBe(false);
401 }).pipe(
402 Effect.scoped,
403 Effect.provide(
404 Layer.mergeAll(
405 NodeServices.layer,
406 NodeCrypto.layer,
407 layerHttpClient(new TextEncoder().encode("test-binary")),
408 layerSpawner([]),
409 layerHostRuntime({ PATH: "" }),
410 ),
411 ),
412 ),
413 );
414​
415 it.effect.skipIf(windowsHost)(
416 "removes a staged client whose rename lands after cancellation",
417 () =>
418 Effect.gen(function* () {
419 const fileSystem = yield* FileSystem.FileSystem;
420 const scope = yield* Effect.scope;
421 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
422 prefix: "t3-cloudflared-test-",
423 });
424 const directory = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64`;
425 const renamePending = yield* Deferred.make<void>();
426 const allowRename = yield* Deferred.make<void>();
427 const renameFinished = yield* Deferred.make<void, PlatformError.PlatformError>();
428 const manager = yield* RelayClient.makeCloudflaredRelayClient({
429 baseDir,
430 releaseAsset: testReleaseAsset,
431 }).pipe(
432 Effect.provideService(FileSystem.FileSystem, {
433 ...fileSystem,
434 // Like Node's rename, the staging rename completes even if its caller is interrupted.
435 rename: (from, to) =>
436 to.endsWith(".tmp")
437 ? Effect.forkIn(
438 Deferred.complete(
439 renameFinished,
440 Deferred.await(allowRename).pipe(Effect.andThen(fileSystem.rename(from, to))),
441 ),
442 scope,
443 ).pipe(
444 Effect.andThen(Deferred.succeed(renamePending, undefined)),
445 Effect.andThen(Deferred.await(renameFinished)),
446 )
447 : fileSystem.rename(from, to),
448 // Land the rename before the install temp directory is removed.
449 remove: (path, options) =>
450 path.endsWith(".tmp")
451 ? fileSystem
452 .remove(path, options)
453 .pipe(
454 Effect.andThen(Deferred.succeed(allowRename, undefined)),
455 Effect.andThen(Deferred.await(renameFinished)),
456 )
457 : fileSystem.remove(path, options),
458 }),
459 );
460​
461 const installing = yield* manager.install.pipe(Effect.forkChild);
462 yield* Deferred.await(renamePending);
463 yield* Effect.yieldNow;
464 const cancelling = yield* Fiber.interrupt(installing).pipe(
465 Effect.forkChild({ startImmediately: true }),
466 );
467 yield* Effect.yieldNow;
468 yield* Deferred.succeed(allowRename, undefined);
469 yield* Fiber.join(cancelling);
470 yield* Deferred.await(renameFinished);
471​
472 expect(yield* fileSystem.readDirectory(directory)).toEqual([]);
473 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
474 );
475​
476 it.effect.skipIf(windowsHost)(
477 "downloads, verifies, validates, and atomically installs the managed executable",
478 () =>
479 Effect.gen(function* () {
480 const fileSystem = yield* FileSystem.FileSystem;
481 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
482 prefix: "t3-cloudflared-test-",
483 });
484 const bytes = new TextEncoder().encode("test-cloudflared-binary");
485 const manager = yield* RelayClient.makeCloudflaredRelayClient({
486 baseDir,
487 releaseAsset: {
488 url: "https://example.test/cloudflared",
489 sha256: Hex.encode(sha256(bytes)),
490 archive: "binary",
491 },
492 });
493​
494 const progress: Array<string> = [];
495 const installed = yield* manager.installWithProgress((event) =>
496 Effect.sync(() => {
497 if (event.type === "progress") {
498 progress.push(event.stage);
499 }
500 }),
501 );
502 const managedPath = `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared`;
503 expect(installed).toEqual({
504 status: "available",
505 executablePath: managedPath,
506 source: "managed",
507 version: RelayClient.CLOUDFLARED_VERSION,
508 });
509 expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe(
510 "test-cloudflared-binary",
511 );
512 expect(progress).toEqual([
513 "checking",
514 "waiting_for_lock",
515 "downloading",
516 "verifying",
517 "installing",
518 "validating",
519 "activating",
520 ]);
521 expect(yield* manager.resolve).toEqual(installed);
522 }).pipe(
523 Effect.scoped,
524 Effect.provide(
525 Layer.mergeAll(
526 NodeServices.layer,
527 NodeCrypto.layer,
528 layerHttpClient(new TextEncoder().encode("test-cloudflared-binary")),
529 layerSpawner([]),
530 layerHostRuntime(),
531 ),
532 ),
533 ),
534 );
535​
536 it.effect.skipIf(windowsHost)(
537 "installs when the downloaded binary's first launch is held by an antivirus scan",
538 () =>
539 Effect.gen(function* () {
540 const fileSystem = yield* FileSystem.FileSystem;
541 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
542 prefix: "t3-cloudflared-test-",
543 });
544 const scanning = yield* Deferred.make<void>();
545 const manager = yield* RelayClient.makeCloudflaredRelayClient({
546 baseDir,
547 releaseAsset: testReleaseAsset,
548 }).pipe(
549 Effect.provideService(
550 ChildProcessSpawner.ChildProcessSpawner,
551 ChildProcessSpawner.make(() =>
552 Deferred.succeed(scanning, undefined).pipe(
553 Effect.andThen(Effect.sleep("25 seconds")),
554 Effect.as(
555 makeHandle(
556 0,
557 `cloudflared version ${RelayClient.CLOUDFLARED_VERSION} (built 2026-01-01-00:00 UTC)\n`,
558 ),
559 ),
560 ),
561 ),
562 ),
563 );
564​
565 const installing = yield* manager.install.pipe(Effect.forkChild);
566 yield* Deferred.await(scanning);
567 yield* TestClock.adjust("25 seconds");
568​
569 expect(yield* Fiber.join(installing)).toMatchObject({
570 status: "available",
571 source: "managed",
572 version: RelayClient.CLOUDFLARED_VERSION,
573 });
574 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime("linux"))),
575 );
576​
577 it.effect("rejects downloads whose checksum does not match the pinned manifest", () =>
578 Effect.gen(function* () {
579 const fileSystem = yield* FileSystem.FileSystem;
580 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
581 prefix: "t3-cloudflared-test-",
582 });
583 const manager = yield* RelayClient.makeCloudflaredRelayClient({
584 baseDir,
585 releaseAsset: {
586 url: "https://example.test/cloudflared",
587 sha256: Hex.encode(sha256(new TextEncoder().encode("expected"))),
588 archive: "binary",
589 },
590 });
591​
592 const error = yield* manager.install.pipe(Effect.flip);
593 expect(error).toBeInstanceOf(RelayClient.RelayClientInstallError);
594 expect(error.reason).toBe("invalid_checksum");
595 expect(
596 yield* fileSystem.exists(
597 `${baseDir}/tools/cloudflared/${RelayClient.CLOUDFLARED_VERSION}/linux-x64/cloudflared.lock`,
598 ),
599 ).toBe(false);
600 }).pipe(
601 Effect.scoped,
602 Effect.provide(
603 Layer.mergeAll(
604 NodeServices.layer,
605 NodeCrypto.layer,
606 layerHttpClient(new TextEncoder().encode("tampered")),
607 layerSpawner([]),
608 layerHostRuntime(),
609 ),
610 ),
611 ),
612 );
613​
614 it.effect.skipIf(windowsHost)("serializes concurrent installs within one runtime", () => {
615 const commands: Array<string> = [];
616 const bytes = new TextEncoder().encode("test-cloudflared-binary");
617 return Effect.gen(function* () {
618 const fileSystem = yield* FileSystem.FileSystem;
619 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
620 prefix: "t3-cloudflared-test-",
621 });
622 const manager = yield* RelayClient.makeCloudflaredRelayClient({
623 baseDir,
624 releaseAsset: {
625 url: "https://example.test/cloudflared",
626 sha256: Hex.encode(sha256(bytes)),
627 archive: "binary",
628 },
629 });
630​
631 const [first, second] = yield* Effect.all([manager.install, manager.install], {
632 concurrency: "unbounded",
633 });
634 expect(second).toEqual(first);
635 expect(commands).toHaveLength(2);
636 }).pipe(
637 Effect.scoped,
638 Effect.provide(
639 Layer.mergeAll(
640 NodeServices.layer,
641 NodeCrypto.layer,
642 layerHttpClient(bytes),
643 layerSpawner(commands),
644 layerHostRuntime(),
645 ),
646 ),
647 );
648 });
649​
650 it.effect("observes hydrated PATH changes after the manager has been constructed", () => {
651 const platform = windowsHost ? "win32" : "linux";
652 const executableName = windowsHost ? "cloudflared.exe" : "cloudflared";
653 const configEnv = { PATH: "" };
654 const hostEnv = { PATH: "" };
655 return Effect.gen(function* () {
656 const fileSystem = yield* FileSystem.FileSystem;
657 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
658 prefix: "t3-cloudflared-test-",
659 });
660 const binDir = `${baseDir}/bin`;
661 const executablePath = `${binDir}/${executableName}`;
662 const resolvedExecutablePath = windowsHost
663 ? executablePath.replaceAll("/", "\\")
664 : executablePath;
665 const manager = yield* RelayClient.makeCloudflaredRelayClient({
666 baseDir,
667 });
668​
669 const resolveWithStaleConfig = manager.resolve.pipe(
670 Effect.provideService(
671 ConfigProvider.ConfigProvider,
672 ConfigProvider.fromEnv({ env: configEnv }),
673 ),
674 Effect.provideService(HostProcess.Environment, hostEnv),
675 );
676​
677 expect(yield* resolveWithStaleConfig).toEqual({
678 status: "missing",
679 version: RelayClient.CLOUDFLARED_VERSION,
680 });
681​
682 yield* fileSystem.makeDirectory(binDir);
683 yield* fileSystem.writeFileString(executablePath, "cloudflared");
684 if (!windowsHost) yield* fileSystem.chmod(executablePath, 0o755);
685 hostEnv.PATH = binDir;
686​
687 expect(yield* resolveWithStaleConfig).toEqual({
688 status: "available",
689 executablePath: resolvedExecutablePath,
690 source: "path",
691 version: RelayClient.CLOUDFLARED_VERSION,
692 });
693​
694 const resolveWithOverride = manager.resolve.pipe(
695 Effect.provideService(
696 ConfigProvider.ConfigProvider,
697 ConfigProvider.fromEnv({
698 env: { PATH: "", T3CODE_CLOUDFLARED_PATH: executablePath },
699 }),
700 ),
701 Effect.provideService(HostProcess.Environment, { PATH: "" }),
702 );
703 expect(yield* resolveWithOverride).toEqual({
704 status: "available",
705 executablePath,
706 source: "override",
707 version: RelayClient.CLOUDFLARED_VERSION,
708 });
709 }).pipe(
710 Effect.scoped,
711 Effect.provide(
712 Layer.mergeAll(
713 NodeServices.layer,
714 NodeCrypto.layer,
715 layerHttpClient(new Uint8Array()),
716 layerSpawner([]),
717 layerHostRuntime(configEnv, platform),
718 ),
719 ),
720 );
721 });
722​
723 describe("version selection", () => {
724 const run = <A, E>(
725 body: (baseDir: string) => Effect.Effect<A, E, RelayClientTestServices>,
726 options: { readonly versions?: Record<string, string> } = {},
727 ) =>
728 Effect.gen(function* () {
729 const fileSystem = yield* FileSystem.FileSystem;
730 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
731 prefix: "t3-cloudflared-test-",
732 });
733 return yield* body(baseDir);
734 }).pipe(
735 Effect.scoped,
736 Effect.provide(
737 Layer.mergeAll(
738 NodeServices.layer,
739 NodeCrypto.layer,
740 layerHttpClient(new Uint8Array()),
741 layerSpawner([], options.versions),
742 layerHostRuntime({ PATH: "" }),
743 ),
744 ),
745 );
746​
747 it.effect.skipIf(windowsHost)("skips binaries older than the minimum version", () => {
748 const versions: Record<string, string> = {};
749 return run(
750 (baseDir) =>
751 Effect.gen(function* () {
752 const oldPath = `${baseDir}/old/cloudflared`;
753 const newPath = `${baseDir}/new/cloudflared`;
754 yield* writeExecutable(oldPath);
755 yield* writeExecutable(newPath);
756 const managed = managedPathFor(baseDir, "2026.10.0");
757 yield* writeExecutable(managed);
758 versions[managed] = "2026.10.0";
759 versions[oldPath] = "2026.10.2";
760 versions[newPath] = "2026.10.3";
761 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
762 const env = { PATH: `${baseDir}/old:${baseDir}/new` };
763 expect(
764 yield* manager.resolve.pipe(
765 Effect.provideService(
766 ConfigProvider.ConfigProvider,
767 ConfigProvider.fromEnv({ env }),
768 ),
769 Effect.provideService(HostProcess.Environment, env),
770 ),
771 ).toEqual({
772 status: "available",
773 executablePath: newPath,
774 source: "path",
775 version: RelayClient.CLOUDFLARED_MIN_VERSION,
776 });
777 }),
778 { versions },
779 );
780 });
781​
782 it.effect.skipIf(windowsHost)(
783 "finds a PATH binary through an empty entry by its absolute path",
784 () =>
785 run((baseDir) =>
786 Effect.gen(function* () {
787 const cwd = `${baseDir}/work`;
788 const inCwd = `${cwd}/cloudflared`;
789 yield* writeExecutable(inCwd);
790 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
791 const resolveWith = (searchPath: string) => {
792 const env = { PATH: searchPath };
793 return manager.resolve.pipe(
794 Effect.provideService(
795 ConfigProvider.ConfigProvider,
796 ConfigProvider.fromEnv({ env }),
797 ),
798 Effect.provideService(HostProcess.Environment, env),
799 Effect.provideService(HostProcess.WorkingDirectory, cwd),
800 );
801 };
802 const found = {
803 status: "available",
804 executablePath: inCwd,
805 source: "path",
806 version: RelayClient.CLOUDFLARED_VERSION,
807 };
808​
809 expect(yield* resolveWith(`:${baseDir}/missing`)).toEqual(found);
810 expect(yield* resolveWith(`${baseDir}/missing:`)).toEqual(found);
811 const missing = { status: "missing", version: RelayClient.CLOUDFLARED_VERSION };
812 // An empty PATH searches nothing, not even the working directory.
813 expect(yield* resolveWith("")).toEqual(missing);
814 // A whitespace entry is not an empty one.
815 expect(yield* resolveWith(` :${baseDir}/missing`)).toEqual(missing);
816 expect(yield* resolveWith(`${baseDir}/missing: `)).toEqual(missing);
817 }),
818 ),
819 );
820​
821 it.effect.skipIf(windowsHost)(
822 "preserves trailing whitespace and quotes in POSIX PATH entries",
823 () =>
824 run((baseDir) =>
825 Effect.gen(function* () {
826 const trailingSpaceDir = `${baseDir}/path entry `;
827 const trailingSpaceBin = `${trailingSpaceDir}/cloudflared`;
828 const trailingQuoteDir = `${baseDir}/quoted"`;
829 const trailingQuoteBin = `${trailingQuoteDir}/cloudflared`;
830 yield* writeExecutable(trailingSpaceBin);
831 yield* writeExecutable(trailingQuoteBin);
832 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
833 const resolveWith = (searchPath: string) => {
834 const env = { PATH: searchPath };
835 return manager.resolve.pipe(
836 Effect.provideService(
837 ConfigProvider.ConfigProvider,
838 ConfigProvider.fromEnv({ env }),
839 ),
840 Effect.provideService(HostProcess.Environment, env),
841 );
842 };
843​
844 expect(yield* resolveWith(trailingSpaceDir)).toEqual({
845 status: "available",
846 executablePath: trailingSpaceBin,
847 source: "path",
848 version: RelayClient.CLOUDFLARED_VERSION,
849 });
850 expect(yield* resolveWith(trailingQuoteDir)).toEqual({
851 status: "available",
852 executablePath: trailingQuoteBin,
853 source: "path",
854 version: RelayClient.CLOUDFLARED_VERSION,
855 });
856 }),
857 ),
858 );
859​
860 it.effect.skipIf(windowsHost)("reports an outdated override as missing", () => {
861 const versions: Record<string, string> = {};
862 return run(
863 (baseDir) =>
864 Effect.gen(function* () {
865 const overridePath = `${baseDir}/override/cloudflared`;
866 yield* writeExecutable(overridePath);
867 versions[overridePath] = "2026.10.2";
868 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
869 const env = { PATH: "", T3CODE_CLOUDFLARED_PATH: overridePath };
870 const withEnv = Effect.provideService(
871 ConfigProvider.ConfigProvider,
872 ConfigProvider.fromEnv({ env }),
873 );
874 expect(yield* manager.resolve.pipe(withEnv)).toEqual({
875 status: "missing",
876 version: RelayClient.CLOUDFLARED_VERSION,
877 });
878 const error = yield* manager.install.pipe(withEnv, Effect.flip);
879 expect(error.reason).toBe("override_missing");
880 }),
881 { versions },
882 );
883 });
884​
885 it.effect.skipIf(windowsHost)(
886 "prefers the pinned release, then the newest older managed release, then PATH",
887 () => {
888 const versions: Record<string, string> = {};
889 return run(
890 (baseDir) =>
891 Effect.gen(function* () {
892 const fileSystem = yield* FileSystem.FileSystem;
893 const pathBinary = `${baseDir}/bin/cloudflared`;
894 const older = managedPathFor(baseDir, "2025.9.0");
895 const newer = managedPathFor(baseDir, "2026.1.0");
896 const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION);
897 const newerServer = managedPathFor(baseDir, "2099.1.0");
898 const olderBackupFile = `${baseDir}/tools/cloudflared/backup-of-2025.8.0.txt`;
899 const newerBackupFile = `${baseDir}/tools/cloudflared/backup-of-2026.10.2.txt`;
900 const nonDirectoryVersion = `${baseDir}/tools/cloudflared/2026.10.3`;
901 versions[newerServer] = "2099.1.0";
902 yield* writeExecutable(newerServer);
903 versions[pathBinary] = "2026.10.3";
904 versions[older] = "2025.9.0";
905 versions[newer] = "2026.10.3";
906 yield* writeExecutable(pathBinary);
907 yield* writeExecutable(older);
908 yield* writeExecutable(newer);
909 yield* fileSystem.writeFileString(olderBackupFile, "keep-older");
910 yield* fileSystem.writeFileString(newerBackupFile, "keep-newer");
911 yield* fileSystem.writeFileString(nonDirectoryVersion, "not-a-release-dir");
912 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
913 const resolveWith = manager.resolve.pipe(
914 Effect.provideService(
915 ConfigProvider.ConfigProvider,
916 ConfigProvider.fromEnv({ env: { PATH: `${baseDir}/bin` } }),
917 ),
918 Effect.provideService(HostProcess.Environment, { PATH: `${baseDir}/bin` }),
919 );
920​
921 expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.10.3" });
922​
923 yield* writeExecutable(pinned);
924 expect(yield* resolveWith).toMatchObject({
925 executablePath: pinned,
926 source: "managed",
927 version: RelayClient.CLOUDFLARED_VERSION,
928 });
929​
930 yield* manager.pruneManagedVersions;
931 expect(
932 (yield* fileSystem.readDirectory(`${baseDir}/tools/cloudflared`)).sort(),
933 ).toEqual([
934 "2026.1.0",
935 "2026.10.3",
936 RelayClient.CLOUDFLARED_VERSION,
937 "2099.1.0",
938 "backup-of-2025.8.0.txt",
939 "backup-of-2026.10.2.txt",
940 ]);
941​
942 yield* fileSystem.remove(pinned);
943 expect(yield* resolveWith).toMatchObject({ source: "managed", version: "2026.10.3" });
944 yield* fileSystem.remove(`${baseDir}/tools/cloudflared/2026.1.0`, {
945 recursive: true,
946 });
947 expect(yield* resolveWith).toMatchObject({ source: "path", version: "2026.10.3" });
948 }),
949 { versions },
950 );
951 },
952 );
953​
954 it.effect.skipIf(windowsHost)(
955 "keeps a self-updated managed binary as a fallback but still installs the pin",
956 () => {
957 const versions: Record<string, string> = {};
958 return run(
959 (baseDir) =>
960 Effect.gen(function* () {
961 const pinned = managedPathFor(baseDir, RelayClient.CLOUDFLARED_VERSION);
962 versions[pinned] = "2026.10.3";
963 yield* writeExecutable(pinned);
964 const manager = yield* RelayClient.makeCloudflaredRelayClient({ baseDir });
965 const resolved = yield* manager.resolve;
966 expect(resolved).toEqual({
967 status: "available",
968 executablePath: pinned,
969 source: "managed",
970 version: "2026.10.3",
971 });
972 expect(
973 resolved.status === "available" && RelayClient.isPinnedManagedRelayClient(resolved),
974 ).toBe(false);
975 }),
976 { versions },
977 );
978 },
979 );
980 });
981​
982 it("orders and parses cloudflared versions", () => {
983 expect(
984 RelayClient.parseCloudflaredVersionOutput(
985 "cloudflared version 2026.5.2 (built 2026-05-20-10:00 UTC)",
986 ),
987 ).toBe("2026.5.2");
988 expect(RelayClient.parseCloudflaredVersionOutput("Incorrect Usage")).toBeNull();
989 expect(RelayClient.compareCloudflaredVersions("2025.10.0", "2025.6.1")).toBeGreaterThan(0);
990 expect(RelayClient.compareCloudflaredVersions("2023.8.2", "2025.6.1")).toBeLessThan(0);
991 });
992​
993 it.effect.each([
994 ["linux", "EBUSY"],
995 ["win32", "EXDEV"],
996 ] as const)("fails staging at once on %s for %s", ([platform, code]) =>
997 Effect.gen(function* () {
998 const fileSystem = yield* FileSystem.FileSystem;
999 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1000 prefix: "t3-cloudflared-test-",
1001 });
1002 const { locked, renames } = yield* makeLockedRenames(fileSystem, {
1003 rename: "staging",
1004 failures: Infinity,
1005 code,
1006 });
1007 const manager = yield* RelayClient.makeCloudflaredRelayClient({
1008 baseDir,
1009 releaseAsset: testReleaseAsset,
1010 }).pipe(Effect.provideService(FileSystem.FileSystem, locked));
1011​
1012 const error = yield* manager.install.pipe(Effect.flip);
1013​
1014 expect(error.message).toBe("Could not stage the relay client.");
1015 expect(renames.attempts).toBe(1);
1016 }).pipe(Effect.scoped, Effect.provide(layerInstallRuntime(platform))),
1017 );
1018});