Open History to see the last commit
1import * as Cache from "effect/Cache";
2import * as Clock from "effect/Clock";
3import type {
4 RelayClientInstallProgressEvent,
5 RelayClientInstallProgressStage,
6} from "@t3tools/contracts";
7import * as Config from "effect/Config";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as Data from "effect/Data";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Hex from "effect/encoding/Hex";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as PlatformError from "effect/PlatformError";
20import * as Schedule from "effect/Schedule";
21import * as Semaphore from "effect/Semaphore";
22import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
23import { ChildProcess, ChildProcessSpawner } from "effect/process";
24import * as HostProcess from "./HostProcess.ts";
25
26export const CLOUDFLARED_VERSION = "2026.10.0";
27// The oldest release that accepts every flag the connector is started with
28// (`--output` arrived in 2025.6.1). Override, PATH, and older managed binaries
29// below it are skipped, since they exit immediately on the unknown flag.
30export const CLOUDFLARED_MIN_VERSION = "2025.6.1";
31const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";
32
33// Generous bound for a ~40MB binary download; without it a stalled
34// connection parks the install forever (same unbounded-wait family as the
35// other relay/cloud network calls).
36const CLOUDFLARED_DOWNLOAD_TIMEOUT = "10 minutes";
37
38export type RelayClientExecutableSource = "override" | "managed" | "path";
39
40export type RelayClientStatus =
41 | {
42 readonly status: "available";
43 readonly executablePath: string;
44 readonly source: RelayClientExecutableSource;
45 readonly version: string;
46 }
47 | {
48 readonly status: "missing";
49 readonly version: string;
50 }
51 | {
52 readonly status: "unsupported";
53 readonly platform: NodeJS.Platform;
54 readonly arch: string;
55 readonly version: string;
56 };
57
58export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
59
60export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
61 readonly reason:
62 | "download_failed"
63 | "invalid_checksum"
64 | "install_locked"
65 | "override_missing"
66 | "unsupported_platform"
67 | "validation_failed"
68 | "write_failed";
69 readonly message: string;
70 readonly cause?: unknown;
71}> {}
72
73class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
74 readonly command: string;
75 readonly exitCode: number;
76}> {}
77
78export interface CloudflaredReleaseAsset {
79 readonly url: string;
80 readonly sha256: string;
81 readonly archive: "binary" | "tgz";
82}
83
84const CLOUDFLARED_RELEASE_ASSETS: Readonly<
85 Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>
86> = {
87 "darwin-arm64": {
88 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-darwin-arm64.tgz",
89 sha256: "a2f79ff7b9420aa537d74af239f376da170bbabeb529aec416002adac6a72e70",
90 archive: "tgz",
91 },
92 "darwin-x64": {
93 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-darwin-amd64.tgz",
94 sha256: "903845b81828c8cb3c5d13d816a2de71c06a3da5785469df8eb0e1b736d92f9f",
95 archive: "tgz",
96 },
97 "linux-arm64": {
98 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-linux-arm64",
99 sha256: "e6422b9d4f72d3194bc5a38676f13667c06666523217b842a877d72a80b5ac08",
100 archive: "binary",
101 },
102 "linux-x64": {
103 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-linux-amd64",
104 sha256: "d33ff2d14475178d2012c2c56beba87389ac5ded27649519f198a7d3134a99db",
105 archive: "binary",
106 },
107 "win32-x64": {
108 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-windows-amd64.exe",
109 sha256: "86aee4017b26625cee8484c113558f48effa4cd47f7aa05fcf425604e5d2b23c",
110 archive: "binary",
111 },
112 // Cloudflare publishes no Windows ARM64 build; Windows 11 on ARM runs x64 under emulation.
113 "win32-arm64": {
114 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.0/cloudflared-windows-amd64.exe",
115 sha256: "86aee4017b26625cee8484c113558f48effa4cd47f7aa05fcf425604e5d2b23c",
116 archive: "binary",
117 },
118};
119
120const INSTALL_LOCK_RETRY_COUNT = 100;
121const INSTALL_LOCK_RETRY_DELAY = "100 millis";
122const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
123const VERSION_PROBE_TIMEOUT = "10 seconds";
124
125const ACTIVATE_RETRY_COUNT = 40;
126const ACTIVATE_RETRY_DELAY = "250 millis";
127
128const trimmedString = (name: string) =>
129 Config.String(name).pipe(
130 Config.option,
131 Config.map(
132 Option.flatMap((value) => {
133 const trimmed = value.trim();
134 return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
135 }),
136 ),
137 );
138
139const CloudflaredConfig = Config.all({
140 executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
141});
142
143export interface CloudflaredRelayClientOptions {
144 readonly baseDir: string;
145 readonly releaseAsset?: CloudflaredReleaseAsset;
146}
147
148export interface RelayClientShape {
149 /**
150 * Finds the relay client to run, without downloading anything: the override,
151 * else the pinned managed folder, else the newest older managed folder, else
152 * `cloudflared` on PATH. Every candidate must report a compatible version, and
153 * the status carries the version the binary reports.
154 */
155 readonly resolve: Effect.Effect<RelayClientStatus>;
156 /** Installs the pinned managed release unless it, or a valid override, is already present. */
157 readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
158 readonly installWithProgress: (
159 report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
160 ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
161 /** Removes managed releases older than the pin, except the newest one. Call once the pin has connected. */
162 readonly pruneManagedVersions: Effect.Effect<void>;
163}
164
165/** True when this is the pinned managed release, which needs no update. */
166export function isPinnedManagedRelayClient(client: AvailableRelayClient): boolean {
167 return client.source === "managed" && client.version === CLOUDFLARED_VERSION;
168}
169
170export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
171 "@t3tools/shared/relayClient",
172) {}
173
174function executableFileName(platform: NodeJS.Platform): string {
175 return platform === "win32" ? "cloudflared.exe" : "cloudflared";
176}
177
178function resolveReleaseAsset(
179 platform: NodeJS.Platform,
180 arch: string,
181): CloudflaredReleaseAsset | null {
182 return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
183}
184
185const VERSION_PATTERN = /\b(\d{4})\.(\d{1,2})\.(\d+)\b/u;
186
187function parseVersion(value: string): readonly [number, number, number] | null {
188 const match = VERSION_PATTERN.exec(value);
189 return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
190}
191
192/** Orders `YYYY.M.P` cloudflared versions; unparseable versions sort first. */
193export function compareCloudflaredVersions(left: string, right: string): number {
194 const a = parseVersion(left) ?? [0, 0, 0];
195 const b = parseVersion(right) ?? [0, 0, 0];
196 return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
197}
198
199/** Reads the version from `cloudflared version` output, e.g. `cloudflared version 2026.5.2 (built ...)`. */
200export function parseCloudflaredVersionOutput(output: string): string | null {
201 const version = parseVersion(output);
202 return version ? version.join(".") : null;
203}
204
205// A changed file is a new key, so a replaced binary is probed again.
206class VersionProbeKey extends Data.Class<{
207 readonly executablePath: string;
208 readonly size: number;
209 readonly mtimeMillis: number;
210}> {}
211
212function isAlreadyExists(error: PlatformError.PlatformError): boolean {
213 return error.reason._tag === "AlreadyExists";
214}
215
216// Windows refuses to rename a file another process briefly holds open, such as a virus
217// scanner reading the binary that just ran. These codes clear once it lets go.
218function isTransientWindowsLock(error: PlatformError.PlatformError): boolean {
219 const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
220 return code === "EBUSY" || code === "EPERM" || code === "EACCES";
221}
222
223const wrapInstallFailure =
224 (
225 reason: RelayClientInstallError["reason"],
226 message: string,
227 ): (<E, R>(
228 effect: Effect.Effect<void, E, R>,
229 ) => Effect.Effect<void, RelayClientInstallError, R>) =>
230 (effect) =>
231 effect.pipe(
232 Effect.mapError(
233 (cause) =>
234 new RelayClientInstallError({
235 reason,
236 message,
237 cause,
238 }),
239 ),
240 );
241
242export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
243 options: CloudflaredRelayClientOptions,
244): Effect.fn.Return<
245 RelayClientShape,
246 never,
247 | ChildProcessSpawner.ChildProcessSpawner
248 | Crypto.Crypto
249 | FileSystem.FileSystem
250 | HttpClient.HttpClient
251 | Path.Path
252> {
253 const crypto = yield* Crypto.Crypto;
254 const fileSystem = yield* FileSystem.FileSystem;
255 const httpClient = yield* HttpClient.HttpClient;
256 const path = yield* Path.Path;
257 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
258 const installSemaphore = yield* Semaphore.make(1);
259 const platform = yield* HostProcess.Platform;
260 const arch = yield* HostProcess.Architecture;
261 const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
262 const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);
263 const managedRoot = path.join(options.baseDir, "tools", "cloudflared");
264 const managedPathFor = (version: string) =>
265 path.join(managedRoot, version, `${platform}-${arch}`, executableFileName(platform));
266 const managedPath = managedPathFor(CLOUDFLARED_VERSION);
267
268 const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
269 executablePath: string,
270 ) {
271 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
272 if (Option.isNone(info) || info.value.type !== "File") return false;
273 return platform === "win32" || (info.value.mode & 0o111) !== 0;
274 });
275
276 // `cloudflared version` costs a process spawn, so answers are cached per file
277 // revision. Before `--no-autoupdate`, a managed binary could replace itself in
278 // place, so the version is read from the binary, never from its folder name.
279 // A failed or timed-out probe is not cached, so a slow spawn under an AV scan
280 // does not hide a good binary until it changes on disk.
281 const versionCache = yield* Cache.makeWith(
282 (key: VersionProbeKey) =>
283 spawner
284 .string(
285 ChildProcess.make(key.executablePath, ["version"], { stdin: "ignore", stderr: "ignore" }),
286 )
287 .pipe(
288 Effect.map(parseCloudflaredVersionOutput),
289 Effect.timeoutOption(VERSION_PROBE_TIMEOUT),
290 Effect.map(Option.getOrNull),
291 Effect.orElseSucceed(() => null),
292 ),
293 {
294 capacity: 16,
295 timeToLive: (exit) =>
296 Exit.isSuccess(exit) && exit.value !== null ? Duration.infinity : Duration.zero,
297 },
298 );
299 const probeVersion = Effect.fn("cloudflared.probeVersion")(function* (executablePath: string) {
300 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
301 if (Option.isNone(info) || info.value.type !== "File") return null;
302 if (platform !== "win32" && (info.value.mode & 0o111) === 0) return null;
303 return yield* Cache.get(
304 versionCache,
305 new VersionProbeKey({
306 executablePath,
307 size: Number(info.value.size),
308 mtimeMillis: Option.getOrUndefined(info.value.mtime)?.getTime() ?? 0,
309 }),
310 );
311 });
312
313 const compatibleCandidate = Effect.fn("cloudflared.compatibleCandidate")(function* (
314 executablePath: string,
315 source: RelayClientExecutableSource,
316 expectedVersion?: string,
317 ) {
318 const version = yield* probeVersion(executablePath);
319 if (version === null || compareCloudflaredVersions(version, CLOUDFLARED_MIN_VERSION) < 0) {
320 return null;
321 }
322 if (expectedVersion !== undefined && version !== expectedVersion) {
323 yield* Effect.logWarning("Ignoring a managed relay client that reports another version", {
324 executablePath,
325 expectedVersion,
326 version,
327 });
328 return null;
329 }
330 return { status: "available", executablePath, source, version } satisfies AvailableRelayClient;
331 });
332
333 // Managed releases older than the pin, newest first. Newer folders belong to
334 // a newer server sharing this base dir and are never used or pruned here.
335 const olderManagedVersions = Effect.gen(function* () {
336 const entries = yield* fileSystem
337 .readDirectory(managedRoot)
338 .pipe(Effect.orElseSucceed(() => []));
339 return entries
340 .filter(
341 (entry) =>
342 parseVersion(entry) !== null &&
343 compareCloudflaredVersions(entry, CLOUDFLARED_VERSION) < 0,
344 )
345 .sort((left, right) => compareCloudflaredVersions(right, left));
346 });
347
348 const resolvePathExecutable = Effect.gen(function* () {
349 // The default ConfigProvider is cached the first time any Config is read.
350 // Server startup reads its config before fixPath hydrates the environment,
351 // so reading PATH through Config here can retain the service's stale PATH.
352 const pathValue = (yield* HostProcess.Environment).PATH?.trim();
353 if (!pathValue) return null;
354 const delimiter = platform === "win32" ? ";" : ":";
355 for (const directory of pathValue.split(delimiter)) {
356 const trimmed = directory.trim().replace(/^"|"$/gu, "");
357 if (trimmed.length === 0) continue;
358 const candidate = path.join(trimmed, executableFileName(platform));
359 if (!(yield* isExecutableFile(candidate))) continue;
360 const available = yield* compatibleCandidate(candidate, "path");
361 if (available) return available;
362 yield* Effect.logWarning("Skipping an incompatible relay client on PATH", {
363 executablePath: candidate,
364 minimumVersion: CLOUDFLARED_MIN_VERSION,
365 });
366 }
367 return null;
368 });
369
370 const missingStatus: RelayClientStatus = { status: "missing", version: CLOUDFLARED_VERSION };
371 const unsupportedStatus: RelayClientStatus = {
372 status: "unsupported",
373 platform,
374 arch,
375 version: CLOUDFLARED_VERSION,
376 };
377 const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
378 const config = yield* loadCloudflaredConfig;
379 if (Option.isSome(config.executableOverride)) {
380 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
381 if (override) return override;
382 yield* Effect.logWarning(
383 `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer`,
384 { executablePath: config.executableOverride.value },
385 );
386 return missingStatus;
387 }
388 // A managed binary reports the version it actually runs. One that replaced
389 // itself in place still serves as a fallback; the runtime sees it is not the
390 // pinned release and installs that.
391 const pinned = yield* compatibleCandidate(managedPath, "managed");
392 if (pinned) return pinned;
393 for (const version of yield* olderManagedVersions) {
394 const older = yield* compatibleCandidate(managedPathFor(version), "managed");
395 if (older) return older;
396 }
397 const pathExecutable = yield* resolvePathExecutable;
398 if (pathExecutable) return pathExecutable;
399 return releaseAsset ? missingStatus : unsupportedStatus;
400 }).pipe(Effect.withSpan("cloudflared.resolve"));
401
402 const pruneManagedVersions: RelayClientShape["pruneManagedVersions"] = Effect.gen(function* () {
403 // The newest older release stays: an older server sharing this base dir, or a
404 // rollback after a failed update, may still need it and cannot redownload it.
405 for (const version of (yield* olderManagedVersions).slice(1)) {
406 // A connector from another server sharing this base dir may still run an
407 // older release; Windows refuses to delete it, so the next prune retries.
408 yield* fileSystem.remove(path.join(managedRoot, version), { recursive: true }).pipe(
409 Effect.tap(() => Effect.logInfo("Removed an older managed relay client", { version })),
410 Effect.catch((cause) =>
411 Effect.logDebug("Could not remove an older managed relay client", { version, cause }),
412 ),
413 );
414 }
415 }).pipe(Effect.withSpan("cloudflared.pruneManagedVersions"));
416
417 /** Moves the new binary toward its final path, waiting out a brief Windows lock. */
418 const renameWhenUnlocked = (from: string, to: string) =>
419 fileSystem.rename(from, to).pipe(
420 Effect.retry({
421 times: ACTIVATE_RETRY_COUNT,
422 schedule: Schedule.spaced(ACTIVATE_RETRY_DELAY),
423 while: (error) => platform === "win32" && isTransientWindowsLock(error),
424 }),
425 );
426
427 const runCommand = Effect.fn("cloudflared.runCommand")(function* (
428 command: string,
429 args: ReadonlyArray<string>,
430 ) {
431 const child = yield* spawner.spawn(
432 ChildProcess.make(command, args, {
433 shell: false,
434 stdout: "ignore",
435 stderr: "ignore",
436 }),
437 );
438 const exitCode = Number(yield* child.exitCode);
439 if (exitCode !== 0) {
440 return yield* new CloudflaredCommandError({ command, exitCode });
441 }
442 });
443
444 const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
445 asset: CloudflaredReleaseAsset,
446 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
447 ) {
448 yield* report("downloading");
449 const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
450 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
451 Effect.flatMap(HttpClientResponse.filterStatusOk),
452 Effect.mapError(
453 (cause) =>
454 new RelayClientInstallError({
455 reason: "download_failed",
456 message: "Could not download the relay client.",
457 cause,
458 }),
459 ),
460 );
461 const bytes = new Uint8Array(
462 yield* response.arrayBuffer.pipe(
463 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
464 Effect.mapError(
465 (cause) =>
466 new RelayClientInstallError({
467 reason: "download_failed",
468 message: "Could not read the downloaded relay client binary.",
469 cause,
470 }),
471 ),
472 ),
473 );
474 yield* report("verifying");
475 const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
476 Effect.mapError(
477 (cause) =>
478 new RelayClientInstallError({
479 reason: "validation_failed",
480 message: "Could not verify the downloaded relay client checksum.",
481 cause,
482 }),
483 ),
484 );
485 if (Hex.encode(checksum) !== asset.sha256) {
486 return yield* new RelayClientInstallError({
487 reason: "invalid_checksum",
488 message: "Downloaded relay client checksum did not match the pinned release.",
489 });
490 }
491 return bytes;
492 });
493
494 const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
495 lockPath: string,
496 ) {
497 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
498 const acquired = yield* Effect.acquireRelease(
499 fileSystem.writeFileString(lockPath, "", { flag: "wx" }),
500 () => fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore),
501 ).pipe(
502 Effect.as(true),
503 Effect.catchIf(isAlreadyExists, () => Effect.succeed(false)),
504 );
505 if (acquired) return;
506
507 const now = yield* Clock.currentTimeMillis;
508 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
509 const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
510 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
511 yield* fileSystem.remove(lockPath, { force: true });
512 continue;
513 }
514 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
515 }
516 return yield* new RelayClientInstallError({
517 reason: "install_locked",
518 message: "Another relay client installation is still in progress.",
519 });
520 });
521
522 const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
523 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
524 ) {
525 yield* report("checking");
526 const config = yield* loadCloudflaredConfig;
527 if (Option.isSome(config.executableOverride)) {
528 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
529 if (override) return override;
530 return yield* new RelayClientInstallError({
531 reason: "override_missing",
532 message: `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer.`,
533 });
534 }
535 const existing = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
536 if (existing) return existing;
537 if (!releaseAsset) {
538 return yield* new RelayClientInstallError({
539 reason: "unsupported_platform",
540 message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
541 });
542 }
543
544 const managedDirectory = path.dirname(managedPath);
545 const lockPath = `${managedPath}.lock`;
546 yield* fileSystem
547 .makeDirectory(managedDirectory, { recursive: true })
548 .pipe(
549 wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
550 );
551 yield* report("waiting_for_lock");
552 yield* acquireInstallLock(lockPath).pipe(
553 Effect.catchTags({
554 PlatformError: (cause) =>
555 Effect.fail(
556 new RelayClientInstallError({
557 reason: "write_failed",
558 message: "Could not acquire the relay client installation lock.",
559 cause,
560 }),
561 ),
562 }),
563 );
564 return yield* Effect.gen(function* () {
565 const afterLock = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
566 if (afterLock) return afterLock;
567
568 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
569 directory: managedDirectory,
570 prefix: ".install-",
571 });
572 const archivePath = path.join(
573 tempDirectory,
574 releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
575 );
576 const download = yield* downloadAsset(releaseAsset, report);
577 yield* report("installing");
578 yield* fileSystem
579 .writeFile(archivePath, download)
580 .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
581
582 const executablePath = path.join(tempDirectory, executableFileName(platform));
583 if (releaseAsset.archive === "tgz") {
584 yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
585 wrapInstallFailure("write_failed", "Could not extract the relay client."),
586 );
587 }
588 if (platform !== "win32") {
589 yield* fileSystem
590 .chmod(executablePath, 0o755)
591 .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
592 }
593 yield* report("validating");
594 // Requiring the pinned version here keeps a mislabelled asset from being
595 // activated, ignored by resolve, and downloaded again on every reconcile.
596 const installedVersion = yield* probeVersion(executablePath);
597 if (installedVersion !== CLOUDFLARED_VERSION) {
598 return yield* new RelayClientInstallError({
599 reason: "validation_failed",
600 message:
601 installedVersion === null
602 ? "The downloaded relay client binary did not run."
603 : `The downloaded relay client reports version ${installedVersion}, not ${CLOUDFLARED_VERSION}.`,
604 });
605 }
606
607 const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4()}.tmp`;
608 yield* report("activating");
609 yield* renameWhenUnlocked(executablePath, stagedPath).pipe(
610 wrapInstallFailure("write_failed", "Could not stage the relay client."),
611 );
612 yield* renameWhenUnlocked(stagedPath, managedPath).pipe(
613 wrapInstallFailure("write_failed", "Could not activate the relay client."),
614 Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
615 );
616 return {
617 status: "available",
618 executablePath: managedPath,
619 source: "managed",
620 version: CLOUDFLARED_VERSION,
621 } satisfies AvailableRelayClient;
622 }).pipe(
623 Effect.scoped,
624 Effect.catchIf(
625 (cause) => !(cause instanceof RelayClientInstallError),
626 (cause) =>
627 Effect.fail(
628 new RelayClientInstallError({
629 reason: "write_failed",
630 message: "Could not install the relay client.",
631 cause,
632 }),
633 ),
634 ),
635 );
636 });
637 const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
638 installSemaphore.withPermit(
639 installUnlocked((stage) =>
640 report({
641 type: "progress",
642 stage,
643 }),
644 ).pipe(Effect.scoped),
645 );
646 const install = installWithProgress(() => Effect.void);
647
648 return RelayClient.of({ resolve, install, installWithProgress, pruneManagedVersions });
649});
650
651export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
652 Layer.effect(RelayClient, makeCloudflaredRelayClient(options));