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

relayClient.ts

733 lines27.4 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.remove cannot remove an empty directory nonrecursively.
2import * as NodeFSP from "node:fs/promises";
3import * as Cache from "effect/Cache";
4import * as Clock from "effect/Clock";
5import type {
6 RelayClientInstallProgressEvent,
7 RelayClientInstallProgressStage,
8} from "@t3tools/contracts";
9import * as Config from "effect/Config";
10import * as Context from "effect/Context";
11import * as Digest from "effect/crypto/Digest";
12import * as SecureRandom from "effect/crypto/SecureRandom";
13import * as Data from "effect/Data";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Hex from "effect/encoding/Hex";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import type * as PlatformError from "effect/PlatformError";
23import * as Schedule from "effect/Schedule";
24import * as Schema from "effect/Schema";
25import * as Semaphore from "effect/Semaphore";
26import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
27import { ChildProcess, ChildProcessSpawner } from "effect/process";
28import { isWindowsRenameLock } from "./atomicWrite.ts";
29import * as HostProcess from "./HostProcess.ts";
30​
31export const CLOUDFLARED_VERSION = "2026.10.4";
32// Minimum for --output support and the eMudhra fix, which 2026.10.2 macOS builds lack.
33export const CLOUDFLARED_MIN_VERSION = "2026.10.3";
34const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";
35​
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​
60class RelayClientLockRemoveError extends Schema.TaggedError<RelayClientLockRemoveError>()(
61 "RelayClientLockRemoveError",
62 { lockPath: Schema.String, cause: Schema.Defect() },
63) {
64 override get message(): string {
65 return `Could not remove the relay client lock ${this.lockPath}.`;
66 }
68​
69export class RelayClientInstallError extends Schema.TaggedError<RelayClientInstallError>()(
70 "RelayClientInstallError",
71 {
72 reason: Schema.Literals([
73 "download_failed",
74 "invalid_checksum",
75 "install_locked",
76 "managed_by_policy",
77 "override_missing",
78 "unsupported_platform",
79 "validation_failed",
80 "write_failed",
81 ]),
82 message: Schema.String,
83 cause: Schema.optional(Schema.Defect()),
84 },
85) {}
86​
87const isRelayClientInstallError = Schema.is(RelayClientInstallError);
88​
89class CloudflaredCommandError extends Schema.TaggedError<CloudflaredCommandError>()(
90 "CloudflaredCommandError",
91 {
92 command: Schema.String,
93 exitCode: Schema.Number,
94 },
95) {}
96​
97export interface CloudflaredReleaseAsset {
98 readonly url: string;
99 readonly sha256: string;
100 readonly archive: "binary" | "tgz";
102​
103const CLOUDFLARED_RELEASE_ASSETS: Readonly<
104 Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>
105> = {
106 "darwin-arm64": {
107 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-darwin-arm64.tgz",
108 sha256: "68b6bc4080ac1330234db2a9002d07f98b000537a1bd531a687b660d4160fa7f",
109 archive: "tgz",
110 },
111 "darwin-x64": {
112 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-darwin-amd64.tgz",
113 sha256: "f11fbef4207d715892331917dafd437f032cf4b7137ed64dea3008338c1c613d",
114 archive: "tgz",
115 },
116 "linux-arm64": {
117 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-linux-arm64",
118 sha256: "2b7203b4fb0ba28a0c1e12f8855ce2c25f76d266a8d5edafac5540b6812acff6",
119 archive: "binary",
120 },
121 "linux-x64": {
122 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-linux-amd64",
123 sha256: "ae5e8add7884b0531d66bbca4570d1de491ff6da51e4ebe7eb160cdf241d9e42",
124 archive: "binary",
125 },
126 "win32-x64": {
127 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-windows-amd64.exe",
128 sha256: "411b16d40c8d872243efeb52c550053d00af0a8a97fbb32e730fb8aba429eaa8",
129 archive: "binary",
130 },
131 // Cloudflare publishes no Windows ARM64 build; Windows 11 on ARM runs x64 under emulation.
132 "win32-arm64": {
133 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.10.4/cloudflared-windows-amd64.exe",
134 sha256: "411b16d40c8d872243efeb52c550053d00af0a8a97fbb32e730fb8aba429eaa8",
135 archive: "binary",
136 },
137};
138​
139const INSTALL_LOCK_RETRY_COUNT = 100;
140const INSTALL_LOCK_RETRY_DELAY = "100 millis";
141// Legacy locks have no owner; allow both ten-minute download stages and the install tail.
142const INSTALL_LOCK_LEGACY_STALE_MS = 30 * 60 * 1_000;
143const VERSION_PROBE_TIMEOUT = "10 seconds";
144// Antivirus scans can hold the first launch of a freshly downloaded binary for 20-30 s.
145const INSTALL_VALIDATION_TIMEOUT = "2 minutes";
146​
147const ACTIVATE_RETRY_COUNT = 40;
148const ACTIVATE_RETRY_DELAY = "250 millis";
149​
150const trimmedString = (name: string) =>
151 Config.String(name).pipe(
152 Config.option,
153 Config.map(
154 Option.flatMap((value) => {
155 const trimmed = value.trim();
156 return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
157 }),
158 ),
159 );
160​
161const CloudflaredConfig = Config.all({
162 executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
163});
164​
165export interface CloudflaredRelayClientOptions {
166 readonly baseDir: string;
167 readonly releaseAsset?: CloudflaredReleaseAsset;
169​
170export interface RelayClientShape {
171 readonly resolve: Effect.Effect<RelayClientStatus>;
172 readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
173 readonly installWithProgress: (
174 report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
175 ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
176 /** Removes managed releases older than the pin, except the newest one. Call once the pin has connected. */
177 readonly pruneManagedVersions: Effect.Effect<void>;
179​
180export function isPinnedManagedRelayClient(client: AvailableRelayClient): boolean {
181 return client.source === "managed" && client.version === CLOUDFLARED_VERSION;
183​
184export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
185 "@t3tools/shared/relayClient",
186) {}
187​
188function executableFileName(platform: NodeJS.Platform): string {
189 return platform === "win32" ? "cloudflared.exe" : "cloudflared";
191​
192function resolveReleaseAsset(
193 platform: NodeJS.Platform,
194 arch: string,
195): CloudflaredReleaseAsset | null {
196 return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
198​
199const VERSION_PATTERN = /\b(\d{4})\.(\d{1,2})\.(\d+)\b/u;
200const MANAGED_VERSION_PATTERN = /^\d{4}\.\d{1,2}\.\d+$/u;
201​
202function parseVersion(value: string): readonly [number, number, number] | null {
203 const match = VERSION_PATTERN.exec(value);
204 return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
206​
207export function compareCloudflaredVersions(left: string, right: string): number {
208 const a = parseVersion(left) ?? [0, 0, 0];
209 const b = parseVersion(right) ?? [0, 0, 0];
210 return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
212​
213export function parseCloudflaredVersionOutput(output: string): string | null {
214 const version = parseVersion(output);
215 return version ? version.join(".") : null;
217​
218class VersionProbeKey extends Data.Class<{
219 readonly executablePath: string;
220 readonly size: number;
221 readonly mtimeMillis: number;
222}> {}
223​
224function isLockContention(error: PlatformError.PlatformError): boolean {
225 const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
226 return (
227 error.reason._tag === "AlreadyExists" ||
228 error.reason._tag === "BadResource" ||
229 code === "ENOTEMPTY" ||
230 isWindowsRenameLock(error)
231 );
233​
234function parseLockOwnerPid(owner: string): number | null {
235 const separator = owner.indexOf("-");
236 if (separator <= 0) return null;
237 const pid = Number(owner.slice(0, separator));
238 return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
240​
241function processIsAlive(pid: number): boolean {
242 try {
243 process.kill(pid, 0);
244 return true;
245 } catch (error) {
246 return (error as { readonly code?: unknown }).code !== "ESRCH";
247 }
249​
250const wrapInstallFailure =
251 (
252 reason: RelayClientInstallError["reason"],
253 message: string,
254 ): (<E, R>(
255 effect: Effect.Effect<void, E, R>,
256 ) => Effect.Effect<void, RelayClientInstallError, R>) =>
257 (effect) =>
258 effect.pipe(
259 Effect.mapError(
260 (cause) =>
261 new RelayClientInstallError({
262 reason,
263 message,
264 cause,
265 }),
266 ),
267 );
268​
269export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
270 options: CloudflaredRelayClientOptions,
271): Effect.fn.Return<
272 RelayClientShape,
273 never,
274 | ChildProcessSpawner.ChildProcessSpawner
275 | SecureRandom.SecureRandom
276 | Digest.Digest
277 | FileSystem.FileSystem
278 | HttpClient.HttpClient
279 | Path.Path
280> {
281 const random = yield* SecureRandom.SecureRandom;
282 const digest = yield* Digest.Digest;
283 const fileSystem = yield* FileSystem.FileSystem;
284 const httpClient = yield* HttpClient.HttpClient;
285 const path = yield* Path.Path;
286 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
287 const installSemaphore = yield* Semaphore.make(1);
288 const platform = yield* HostProcess.Platform;
289 const arch = yield* HostProcess.Architecture;
290 const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
291 const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);
292 const managedRoot = path.join(options.baseDir, "tools", "cloudflared");
293 const managedPathFor = (version: string) =>
294 path.join(managedRoot, version, `${platform}-${arch}`, executableFileName(platform));
295 const managedPath = managedPathFor(CLOUDFLARED_VERSION);
296​
297 const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
298 executablePath: string,
299 ) {
300 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
301 if (Option.isNone(info) || info.value.type !== "File") return false;
302 return platform === "win32" || (info.value.mode & 0o111) !== 0;
303 });
304​
305 const runVersionProbe = Effect.fn("cloudflared.runVersionProbe")(function* (
306 executablePath: string,
307 timeout: Duration.Input,
308 ) {
309 return yield* spawner
310 .string(ChildProcess.make(executablePath, ["version"], { stdin: "ignore", stderr: "ignore" }))
311 .pipe(
312 Effect.map(parseCloudflaredVersionOutput),
313 Effect.timeoutOption(timeout),
314 Effect.map(Option.getOrNull),
315 Effect.orElseSucceed(() => null),
316 );
317 });
318​
319 // Cache successful version probes per file revision; do not let transient failures hide valid binaries.
320 const versionCache = yield* Cache.makeWith(
321 (key: VersionProbeKey) => runVersionProbe(key.executablePath, VERSION_PROBE_TIMEOUT),
322 {
323 capacity: 16,
324 timeToLive: (exit) =>
325 Exit.isSuccess(exit) && exit.value !== null ? Duration.infinity : Duration.zero,
326 },
327 );
328 const probeVersion = Effect.fn("cloudflared.probeVersion")(function* (executablePath: string) {
329 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
330 if (Option.isNone(info) || info.value.type !== "File") return null;
331 if (platform !== "win32" && (info.value.mode & 0o111) === 0) return null;
332 return yield* Cache.get(
333 versionCache,
334 new VersionProbeKey({
335 executablePath,
336 size: Number(info.value.size),
337 mtimeMillis: Option.getOrUndefined(info.value.mtime)?.getTime() ?? 0,
338 }),
339 );
340 });
341​
342 const compatibleCandidate = Effect.fn("cloudflared.compatibleCandidate")(function* (
343 executablePath: string,
344 source: RelayClientExecutableSource,
345 expectedVersion?: string,
346 ) {
347 const version = yield* probeVersion(executablePath);
348 if (version === null || compareCloudflaredVersions(version, CLOUDFLARED_MIN_VERSION) < 0) {
349 return null;
350 }
351 if (expectedVersion !== undefined && version !== expectedVersion) {
352 yield* Effect.logWarning("Ignoring a managed relay client that reports another version", {
353 executablePath,
354 expectedVersion,
355 version,
356 });
357 return null;
358 }
359 return { status: "available", executablePath, source, version } satisfies AvailableRelayClient;
360 });
361​
362 // Newer managed folders may belong to another server; never use or prune them.
363 const olderManagedVersions = Effect.gen(function* () {
364 const entries = yield* fileSystem
365 .readDirectory(managedRoot)
366 .pipe(Effect.orElseSucceed(() => []));
367 const candidates = entries
368 .filter(
369 (entry) =>
370 MANAGED_VERSION_PATTERN.test(entry) &&
371 compareCloudflaredVersions(entry, CLOUDFLARED_VERSION) < 0,
372 )
373 .sort((left, right) => compareCloudflaredVersions(right, left));
374 return yield* Effect.filter(candidates, (entry) =>
375 fileSystem.stat(path.join(managedRoot, entry)).pipe(
376 Effect.map((info) => info.type === "Directory"),
377 Effect.orElseSucceed(() => false),
378 ),
379 );
380 });
381​
382 const resolvePathExecutable = Effect.gen(function* () {
383 // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath.
384 const rawPathValue = (yield* HostProcess.Environment).PATH;
385 // POSIX keeps the raw value, so trimming never turns " :/bin" into an empty entry.
386 const pathValue = platform === "win32" ? rawPathValue?.trim() : rawPathValue;
387 if (!pathValue) return null;
388 const delimiter = platform === "win32" ? ";" : ":";
389 const cwd = yield* HostProcess.WorkingDirectory;
390 for (const directory of pathValue.split(delimiter)) {
391 // POSIX shells search the working directory for an empty entry. Resolve it now: the
392 // connector may be launched from elsewhere.
393 const workingDirectoryEntry = directory === "" && platform !== "win32";
394 const entry = platform === "win32" ? directory.trim().replace(/^"|"$/gu, "") : directory;
395 if (entry.length === 0 && !workingDirectoryEntry) continue;
396 const candidate = workingDirectoryEntry
397 ? path.resolve(cwd, executableFileName(platform))
398 : path.join(entry, executableFileName(platform));
399 if (!(yield* isExecutableFile(candidate))) continue;
400 const available = yield* compatibleCandidate(candidate, "path");
401 if (available) return available;
402 yield* Effect.logWarning("Skipping an incompatible relay client on PATH", {
403 executablePath: candidate,
404 minimumVersion: CLOUDFLARED_MIN_VERSION,
405 });
406 }
407 return null;
408 });
409​
410 const missingStatus: RelayClientStatus = { status: "missing", version: CLOUDFLARED_VERSION };
411 const unsupportedStatus: RelayClientStatus = {
412 status: "unsupported",
413 platform,
414 arch,
415 version: CLOUDFLARED_VERSION,
416 };
417 const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
418 const config = yield* loadCloudflaredConfig;
419 if (Option.isSome(config.executableOverride)) {
420 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
421 if (override) return override;
422 yield* Effect.logWarning(
423 `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer`,
424 { executablePath: config.executableOverride.value },
425 );
426 return missingStatus;
427 }
428 const pinned = yield* compatibleCandidate(managedPath, "managed");
429 if (pinned) return pinned;
430 for (const version of yield* olderManagedVersions) {
431 const older = yield* compatibleCandidate(managedPathFor(version), "managed");
432 if (older) return older;
433 }
434 const pathExecutable = yield* resolvePathExecutable;
435 if (pathExecutable) return pathExecutable;
436 return releaseAsset ? missingStatus : unsupportedStatus;
437 }).pipe(Effect.withSpan("cloudflared.resolve"));
438​
439 const pruneManagedVersions: RelayClientShape["pruneManagedVersions"] = Effect.gen(function* () {
440 // Retain the newest older release for rollback or older servers that cannot redownload it.
441 for (const version of (yield* olderManagedVersions).slice(1)) {
442 // Windows cannot delete another server's running connector; retry next prune.
443 yield* fileSystem.remove(path.join(managedRoot, version), { recursive: true }).pipe(
444 Effect.tap(() => Effect.logInfo("Removed an older managed relay client", { version })),
445 Effect.catch((cause) =>
446 Effect.logDebug("Could not remove an older managed relay client", { version, cause }),
447 ),
448 );
449 }
450 }).pipe(Effect.withSpan("cloudflared.pruneManagedVersions"));
451​
452 // Node can finish an in-flight rename after interruption. Wait for each attempt before
453 // releasing the install scope, while keeping Windows retry delays interruptible.
454 const renameWhenUnlocked = (from: string, to: string) =>
455 fileSystem.rename(from, to).pipe(
456 Effect.uninterruptible,
457 Effect.retry({
458 times: ACTIVATE_RETRY_COUNT,
459 schedule: Schedule.spaced(ACTIVATE_RETRY_DELAY),
460 while: (error) => platform === "win32" && isWindowsRenameLock(error),
461 }),
462 );
463​
464 const runCommand = Effect.fn("cloudflared.runCommand")(function* (
465 command: string,
466 args: ReadonlyArray<string>,
467 ) {
468 const child = yield* spawner.spawn(
469 ChildProcess.make(command, args, {
470 shell: false,
471 stdout: "ignore",
472 stderr: "ignore",
473 }),
474 );
475 const exitCode = Number(yield* child.exitCode);
476 if (exitCode !== 0) {
477 return yield* new CloudflaredCommandError({ command, exitCode });
478 }
479 });
480​
481 const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
482 asset: CloudflaredReleaseAsset,
483 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
484 ) {
485 yield* report("downloading");
486 const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
487 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
488 Effect.flatMap(HttpClientResponse.filterStatusOk),
489 Effect.mapError(
490 (cause) =>
491 new RelayClientInstallError({
492 reason: "download_failed",
493 message: "Could not download the relay client.",
494 cause,
495 }),
496 ),
497 );
498 const bytes = new Uint8Array(
499 yield* response.arrayBuffer.pipe(
500 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
501 Effect.mapError(
502 (cause) =>
503 new RelayClientInstallError({
504 reason: "download_failed",
505 message: "Could not read the downloaded relay client binary.",
506 cause,
507 }),
508 ),
509 ),
510 );
511 yield* report("verifying");
512 const checksum = yield* digest.digest(Digest.sha256, bytes).pipe(
513 Effect.mapError(
514 (cause) =>
515 new RelayClientInstallError({
516 reason: "validation_failed",
517 message: "Could not verify the downloaded relay client checksum.",
518 cause,
519 }),
520 ),
521 );
522 if (Hex.encode(checksum) !== asset.sha256) {
523 return yield* new RelayClientInstallError({
524 reason: "invalid_checksum",
525 message: "Downloaded relay client checksum did not match the pinned release.",
526 });
527 }
528 return bytes;
529 });
530​
531 const removeEmptyLock = (lockPath: string) =>
532 Effect.tryPromise({
533 try: () => NodeFSP.rmdir(lockPath),
534 catch: (cause) => new RelayClientLockRemoveError({ lockPath, cause }),
535 }).pipe(Effect.ignore);
536​
537 const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* (
538 lockPath: string,
539 owner: string,
540 ) {
541 yield* fileSystem.remove(path.join(lockPath, owner), { force: true }).pipe(Effect.ignore);
542 // A replacement contains a different owner entry, so rmdir cannot remove it.
543 yield* removeEmptyLock(lockPath);
544 });
545​
546 const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
547 lockPath: string,
548 ) {
549 const owner = `${process.pid}-${yield* random.uuidV4()}`;
550 const candidate = yield* Effect.acquireRelease(
551 fileSystem.makeTempDirectory({ directory: path.dirname(lockPath), prefix: ".lock-" }),
552 (directory) =>
553 fileSystem.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore),
554 );
555 yield* fileSystem.writeFileString(path.join(candidate, owner), "");
556 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
557 const acquired = yield* Effect.acquireRelease(
558 // Publish a populated directory atomically, with no ownerless acquisition window.
559 fileSystem.rename(candidate, lockPath),
560 () => releaseOwnedLock(lockPath, owner),
561 ).pipe(
562 Effect.as(true),
563 Effect.catchIf(isLockContention, () => Effect.succeed(false)),
564 );
565 if (acquired) return;
566​
567 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
568 if (Option.isNone(lockInfo)) continue;
569 if (lockInfo.value.type === "Directory") {
570 const owners = yield* fileSystem
571 .readDirectory(lockPath)
572 .pipe(Effect.orElseSucceed(() => []));
573 let recovered = owners.length === 0;
574 for (const entry of owners) {
575 const pid = parseLockOwnerPid(entry);
576 if (pid !== null && !processIsAlive(pid)) {
577 yield* releaseOwnedLock(lockPath, entry);
578 recovered = true;
579 }
580 }
581 if (recovered) {
582 yield* removeEmptyLock(lockPath);
583 continue;
584 }
585 } else {
586 const now = yield* Clock.currentTimeMillis;
587 const mtime = lockInfo.value.mtime;
588 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_LEGACY_STALE_MS) {
589 // Nonrecursive removal also refuses a populated directory that replaced this file.
590 yield* fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore);
591 continue;
592 }
593 }
594 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
595 }
596 return yield* new RelayClientInstallError({
597 reason: "install_locked",
598 message: "Another relay client installation is still in progress.",
599 });
600 });
601​
602 const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
603 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
604 ) {
605 yield* report("checking");
606 const config = yield* loadCloudflaredConfig;
607 if (Option.isSome(config.executableOverride)) {
608 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
609 if (override) return override;
610 return yield* new RelayClientInstallError({
611 reason: "override_missing",
612 message: `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer.`,
613 });
614 }
615 const existing = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
616 if (existing) return existing;
617 if (!releaseAsset) {
618 return yield* new RelayClientInstallError({
619 reason: "unsupported_platform",
620 message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
621 });
622 }
623​
624 const managedDirectory = path.dirname(managedPath);
625 const lockPath = `${managedPath}.lock`;
626 yield* fileSystem
627 .makeDirectory(managedDirectory, { recursive: true })
628 .pipe(
629 wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
630 );
631 yield* report("waiting_for_lock");
632 yield* acquireInstallLock(lockPath).pipe(
633 Effect.catchTags({
634 PlatformError: (cause) =>
635 Effect.fail(
636 new RelayClientInstallError({
637 reason: "write_failed",
638 message: "Could not acquire the relay client installation lock.",
639 cause,
640 }),
641 ),
642 }),
643 );
644 return yield* Effect.gen(function* () {
645 const afterLock = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
646 if (afterLock) return afterLock;
647​
648 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
649 directory: managedDirectory,
650 prefix: ".install-",
651 });
652 const archivePath = path.join(
653 tempDirectory,
654 releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
655 );
656 const download = yield* downloadAsset(releaseAsset, report);
657 yield* report("installing");
658 yield* fileSystem
659 .writeFile(archivePath, download)
660 .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
661​
662 const executablePath = path.join(tempDirectory, executableFileName(platform));
663 if (releaseAsset.archive === "tgz") {
664 yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
665 wrapInstallFailure("write_failed", "Could not extract the relay client."),
666 );
667 }
668 if (platform !== "win32") {
669 yield* fileSystem
670 .chmod(executablePath, 0o755)
671 .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
672 }
673 yield* report("validating");
674 // Verify the pin so mislabeled assets cannot cause repeated redownloads.
675 const installedVersion = yield* runVersionProbe(executablePath, INSTALL_VALIDATION_TIMEOUT);
676 if (installedVersion !== CLOUDFLARED_VERSION) {
677 return yield* new RelayClientInstallError({
678 reason: "validation_failed",
679 message:
680 installedVersion === null
681 ? "The downloaded relay client binary did not run."
682 : `The downloaded relay client reports version ${installedVersion}, not ${CLOUDFLARED_VERSION}.`,
683 });
684 }
685​
686 const stagedPath = `${managedPath}.${yield* random.uuidV4()}.tmp`;
687 yield* report("activating");
688 yield* Effect.addFinalizer(() =>
689 fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore),
690 );
691 yield* renameWhenUnlocked(executablePath, stagedPath).pipe(
692 wrapInstallFailure("write_failed", "Could not stage the relay client."),
693 );
694 yield* renameWhenUnlocked(stagedPath, managedPath).pipe(
695 wrapInstallFailure("write_failed", "Could not activate the relay client."),
696 );
697 return {
698 status: "available",
699 executablePath: managedPath,
700 source: "managed",
701 version: CLOUDFLARED_VERSION,
702 } satisfies AvailableRelayClient;
703 }).pipe(
704 Effect.scoped,
705 Effect.catchIf(
706 (cause) => !isRelayClientInstallError(cause),
707 (cause) =>
708 Effect.fail(
709 new RelayClientInstallError({
710 reason: "write_failed",
711 message: "Could not install the relay client.",
712 cause,
713 }),
714 ),
715 ),
716 );
717 });
718 const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
719 installSemaphore.withPermit(
720 installUnlocked((stage) =>
721 report({
722 type: "progress",
723 stage,
724 }),
725 ).pipe(Effect.scoped),
726 );
727 const install = installWithProgress(() => Effect.void);
728​
729 return RelayClient.of({ resolve, install, installWithProgress, pruneManagedVersions });
730});
731​
732export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
733 Layer.effect(RelayClient, makeCloudflaredRelayClient(options));