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

relayClient.ts

707 lines25.9 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; older connectors exit on that flag.
33export const CLOUDFLARED_MIN_VERSION = "2025.6.1";
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​
145const ACTIVATE_RETRY_COUNT = 40;
146const ACTIVATE_RETRY_DELAY = "250 millis";
147​
148const trimmedString = (name: string) =>
149 Config.String(name).pipe(
150 Config.option,
151 Config.map(
152 Option.flatMap((value) => {
153 const trimmed = value.trim();
154 return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
155 }),
156 ),
157 );
158​
159const CloudflaredConfig = Config.all({
160 executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
161});
162​
163export interface CloudflaredRelayClientOptions {
164 readonly baseDir: string;
165 readonly releaseAsset?: CloudflaredReleaseAsset;
167​
168export interface RelayClientShape {
169 readonly resolve: Effect.Effect<RelayClientStatus>;
170 readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
171 readonly installWithProgress: (
172 report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
173 ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
174 /** Removes managed releases older than the pin, except the newest one. Call once the pin has connected. */
175 readonly pruneManagedVersions: Effect.Effect<void>;
177​
178export function isPinnedManagedRelayClient(client: AvailableRelayClient): boolean {
179 return client.source === "managed" && client.version === CLOUDFLARED_VERSION;
181​
182export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
183 "@t3tools/shared/relayClient",
184) {}
185​
186function executableFileName(platform: NodeJS.Platform): string {
187 return platform === "win32" ? "cloudflared.exe" : "cloudflared";
189​
190function resolveReleaseAsset(
191 platform: NodeJS.Platform,
192 arch: string,
193): CloudflaredReleaseAsset | null {
194 return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
196​
197const VERSION_PATTERN = /\b(\d{4})\.(\d{1,2})\.(\d+)\b/u;
198​
199function parseVersion(value: string): readonly [number, number, number] | null {
200 const match = VERSION_PATTERN.exec(value);
201 return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
203​
204export function compareCloudflaredVersions(left: string, right: string): number {
205 const a = parseVersion(left) ?? [0, 0, 0];
206 const b = parseVersion(right) ?? [0, 0, 0];
207 return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
209​
210export function parseCloudflaredVersionOutput(output: string): string | null {
211 const version = parseVersion(output);
212 return version ? version.join(".") : null;
214​
215class VersionProbeKey extends Data.Class<{
216 readonly executablePath: string;
217 readonly size: number;
218 readonly mtimeMillis: number;
219}> {}
220​
221function isLockContention(error: PlatformError.PlatformError): boolean {
222 const code = (error.reason.cause as NodeJS.ErrnoException | undefined)?.code;
223 return (
224 error.reason._tag === "AlreadyExists" ||
225 error.reason._tag === "BadResource" ||
226 code === "ENOTEMPTY" ||
227 isWindowsRenameLock(error)
228 );
230​
231function parseLockOwnerPid(owner: string): number | null {
232 const separator = owner.indexOf("-");
233 if (separator <= 0) return null;
234 const pid = Number(owner.slice(0, separator));
235 return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
237​
238function processIsAlive(pid: number): boolean {
239 try {
240 process.kill(pid, 0);
241 return true;
242 } catch (error) {
243 return (error as { readonly code?: unknown }).code !== "ESRCH";
244 }
246​
247const wrapInstallFailure =
248 (
249 reason: RelayClientInstallError["reason"],
250 message: string,
251 ): (<E, R>(
252 effect: Effect.Effect<void, E, R>,
253 ) => Effect.Effect<void, RelayClientInstallError, R>) =>
254 (effect) =>
255 effect.pipe(
256 Effect.mapError(
257 (cause) =>
258 new RelayClientInstallError({
259 reason,
260 message,
261 cause,
262 }),
263 ),
264 );
265​
266export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
267 options: CloudflaredRelayClientOptions,
268): Effect.fn.Return<
269 RelayClientShape,
270 never,
271 | ChildProcessSpawner.ChildProcessSpawner
272 | SecureRandom.SecureRandom
273 | Digest.Digest
274 | FileSystem.FileSystem
275 | HttpClient.HttpClient
276 | Path.Path
277> {
278 const random = yield* SecureRandom.SecureRandom;
279 const digest = yield* Digest.Digest;
280 const fileSystem = yield* FileSystem.FileSystem;
281 const httpClient = yield* HttpClient.HttpClient;
282 const path = yield* Path.Path;
283 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
284 const installSemaphore = yield* Semaphore.make(1);
285 const platform = yield* HostProcess.Platform;
286 const arch = yield* HostProcess.Architecture;
287 const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
288 const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);
289 const managedRoot = path.join(options.baseDir, "tools", "cloudflared");
290 const managedPathFor = (version: string) =>
291 path.join(managedRoot, version, `${platform}-${arch}`, executableFileName(platform));
292 const managedPath = managedPathFor(CLOUDFLARED_VERSION);
293​
294 const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
295 executablePath: string,
296 ) {
297 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
298 if (Option.isNone(info) || info.value.type !== "File") return false;
299 return platform === "win32" || (info.value.mode & 0o111) !== 0;
300 });
301​
302 // Cache successful version probes per file revision; do not let transient failures hide valid binaries.
303 const versionCache = yield* Cache.makeWith(
304 (key: VersionProbeKey) =>
305 spawner
306 .string(
307 ChildProcess.make(key.executablePath, ["version"], { stdin: "ignore", stderr: "ignore" }),
308 )
309 .pipe(
310 Effect.map(parseCloudflaredVersionOutput),
311 Effect.timeoutOption(VERSION_PROBE_TIMEOUT),
312 Effect.map(Option.getOrNull),
313 Effect.orElseSucceed(() => null),
314 ),
315 {
316 capacity: 16,
317 timeToLive: (exit) =>
318 Exit.isSuccess(exit) && exit.value !== null ? Duration.infinity : Duration.zero,
319 },
320 );
321 const probeVersion = Effect.fn("cloudflared.probeVersion")(function* (executablePath: string) {
322 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
323 if (Option.isNone(info) || info.value.type !== "File") return null;
324 if (platform !== "win32" && (info.value.mode & 0o111) === 0) return null;
325 return yield* Cache.get(
326 versionCache,
327 new VersionProbeKey({
328 executablePath,
329 size: Number(info.value.size),
330 mtimeMillis: Option.getOrUndefined(info.value.mtime)?.getTime() ?? 0,
331 }),
332 );
333 });
334​
335 const compatibleCandidate = Effect.fn("cloudflared.compatibleCandidate")(function* (
336 executablePath: string,
337 source: RelayClientExecutableSource,
338 expectedVersion?: string,
339 ) {
340 const version = yield* probeVersion(executablePath);
341 if (version === null || compareCloudflaredVersions(version, CLOUDFLARED_MIN_VERSION) < 0) {
342 return null;
343 }
344 if (expectedVersion !== undefined && version !== expectedVersion) {
345 yield* Effect.logWarning("Ignoring a managed relay client that reports another version", {
346 executablePath,
347 expectedVersion,
348 version,
349 });
350 return null;
351 }
352 return { status: "available", executablePath, source, version } satisfies AvailableRelayClient;
353 });
354​
355 // Newer managed folders may belong to another server; never use or prune them.
356 const olderManagedVersions = Effect.gen(function* () {
357 const entries = yield* fileSystem
358 .readDirectory(managedRoot)
359 .pipe(Effect.orElseSucceed(() => []));
360 return entries
361 .filter(
362 (entry) =>
363 parseVersion(entry) !== null &&
364 compareCloudflaredVersions(entry, CLOUDFLARED_VERSION) < 0,
365 )
366 .sort((left, right) => compareCloudflaredVersions(right, left));
367 });
368​
369 const resolvePathExecutable = Effect.gen(function* () {
370 // Read hydrated PATH directly; ConfigProvider may have cached it before fixPath.
371 const pathValue = (yield* HostProcess.Environment).PATH?.trim();
372 if (!pathValue) return null;
373 const delimiter = platform === "win32" ? ";" : ":";
374 for (const directory of pathValue.split(delimiter)) {
375 const trimmed = directory.trim().replace(/^"|"$/gu, "");
376 if (trimmed.length === 0) continue;
377 const candidate = path.join(trimmed, executableFileName(platform));
378 if (!(yield* isExecutableFile(candidate))) continue;
379 const available = yield* compatibleCandidate(candidate, "path");
380 if (available) return available;
381 yield* Effect.logWarning("Skipping an incompatible relay client on PATH", {
382 executablePath: candidate,
383 minimumVersion: CLOUDFLARED_MIN_VERSION,
384 });
385 }
386 return null;
387 });
388​
389 const missingStatus: RelayClientStatus = { status: "missing", version: CLOUDFLARED_VERSION };
390 const unsupportedStatus: RelayClientStatus = {
391 status: "unsupported",
392 platform,
393 arch,
394 version: CLOUDFLARED_VERSION,
395 };
396 const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
397 const config = yield* loadCloudflaredConfig;
398 if (Option.isSome(config.executableOverride)) {
399 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
400 if (override) return override;
401 yield* Effect.logWarning(
402 `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer`,
403 { executablePath: config.executableOverride.value },
404 );
405 return missingStatus;
406 }
407 const pinned = yield* compatibleCandidate(managedPath, "managed");
408 if (pinned) return pinned;
409 for (const version of yield* olderManagedVersions) {
410 const older = yield* compatibleCandidate(managedPathFor(version), "managed");
411 if (older) return older;
412 }
413 const pathExecutable = yield* resolvePathExecutable;
414 if (pathExecutable) return pathExecutable;
415 return releaseAsset ? missingStatus : unsupportedStatus;
416 }).pipe(Effect.withSpan("cloudflared.resolve"));
417​
418 const pruneManagedVersions: RelayClientShape["pruneManagedVersions"] = Effect.gen(function* () {
419 // Retain the newest older release for rollback or older servers that cannot redownload it.
420 for (const version of (yield* olderManagedVersions).slice(1)) {
421 // Windows cannot delete another server's running connector; retry next prune.
422 yield* fileSystem.remove(path.join(managedRoot, version), { recursive: true }).pipe(
423 Effect.tap(() => Effect.logInfo("Removed an older managed relay client", { version })),
424 Effect.catch((cause) =>
425 Effect.logDebug("Could not remove an older managed relay client", { version, cause }),
426 ),
427 );
428 }
429 }).pipe(Effect.withSpan("cloudflared.pruneManagedVersions"));
430​
431 const renameWhenUnlocked = (from: string, to: string) =>
432 fileSystem.rename(from, to).pipe(
433 Effect.retry({
434 times: ACTIVATE_RETRY_COUNT,
435 schedule: Schedule.spaced(ACTIVATE_RETRY_DELAY),
436 while: (error) => platform === "win32" && isWindowsRenameLock(error),
437 }),
438 );
439​
440 const runCommand = Effect.fn("cloudflared.runCommand")(function* (
441 command: string,
442 args: ReadonlyArray<string>,
443 ) {
444 const child = yield* spawner.spawn(
445 ChildProcess.make(command, args, {
446 shell: false,
447 stdout: "ignore",
448 stderr: "ignore",
449 }),
450 );
451 const exitCode = Number(yield* child.exitCode);
452 if (exitCode !== 0) {
453 return yield* new CloudflaredCommandError({ command, exitCode });
454 }
455 });
456​
457 const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
458 asset: CloudflaredReleaseAsset,
459 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
460 ) {
461 yield* report("downloading");
462 const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
463 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
464 Effect.flatMap(HttpClientResponse.filterStatusOk),
465 Effect.mapError(
466 (cause) =>
467 new RelayClientInstallError({
468 reason: "download_failed",
469 message: "Could not download the relay client.",
470 cause,
471 }),
472 ),
473 );
474 const bytes = new Uint8Array(
475 yield* response.arrayBuffer.pipe(
476 Effect.timeout(CLOUDFLARED_DOWNLOAD_TIMEOUT),
477 Effect.mapError(
478 (cause) =>
479 new RelayClientInstallError({
480 reason: "download_failed",
481 message: "Could not read the downloaded relay client binary.",
482 cause,
483 }),
484 ),
485 ),
486 );
487 yield* report("verifying");
488 const checksum = yield* digest.digest(Digest.sha256, bytes).pipe(
489 Effect.mapError(
490 (cause) =>
491 new RelayClientInstallError({
492 reason: "validation_failed",
493 message: "Could not verify the downloaded relay client checksum.",
494 cause,
495 }),
496 ),
497 );
498 if (Hex.encode(checksum) !== asset.sha256) {
499 return yield* new RelayClientInstallError({
500 reason: "invalid_checksum",
501 message: "Downloaded relay client checksum did not match the pinned release.",
502 });
503 }
504 return bytes;
505 });
506​
507 const removeEmptyLock = (lockPath: string) =>
508 Effect.tryPromise({
509 try: () => NodeFSP.rmdir(lockPath),
510 catch: (cause) => new RelayClientLockRemoveError({ lockPath, cause }),
511 }).pipe(Effect.ignore);
512​
513 const releaseOwnedLock = Effect.fn("cloudflared.releaseOwnedLock")(function* (
514 lockPath: string,
515 owner: string,
516 ) {
517 yield* fileSystem.remove(path.join(lockPath, owner), { force: true }).pipe(Effect.ignore);
518 // A replacement contains a different owner entry, so rmdir cannot remove it.
519 yield* removeEmptyLock(lockPath);
520 });
521​
522 const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
523 lockPath: string,
524 ) {
525 const owner = `${process.pid}-${yield* random.uuidV4()}`;
526 const candidate = yield* Effect.acquireRelease(
527 fileSystem.makeTempDirectory({ directory: path.dirname(lockPath), prefix: ".lock-" }),
528 (directory) =>
529 fileSystem.remove(directory, { recursive: true, force: true }).pipe(Effect.ignore),
530 );
531 yield* fileSystem.writeFileString(path.join(candidate, owner), "");
532 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
533 const acquired = yield* Effect.acquireRelease(
534 // Publish a populated directory atomically, with no ownerless acquisition window.
535 fileSystem.rename(candidate, lockPath),
536 () => releaseOwnedLock(lockPath, owner),
537 ).pipe(
538 Effect.as(true),
539 Effect.catchIf(isLockContention, () => Effect.succeed(false)),
540 );
541 if (acquired) return;
542​
543 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
544 if (Option.isNone(lockInfo)) continue;
545 if (lockInfo.value.type === "Directory") {
546 const owners = yield* fileSystem
547 .readDirectory(lockPath)
548 .pipe(Effect.orElseSucceed(() => []));
549 let recovered = owners.length === 0;
550 for (const entry of owners) {
551 const pid = parseLockOwnerPid(entry);
552 if (pid !== null && !processIsAlive(pid)) {
553 yield* releaseOwnedLock(lockPath, entry);
554 recovered = true;
555 }
556 }
557 if (recovered) {
558 yield* removeEmptyLock(lockPath);
559 continue;
560 }
561 } else {
562 const now = yield* Clock.currentTimeMillis;
563 const mtime = lockInfo.value.mtime;
564 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_LEGACY_STALE_MS) {
565 // Nonrecursive removal also refuses a populated directory that replaced this file.
566 yield* fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore);
567 continue;
568 }
569 }
570 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
571 }
572 return yield* new RelayClientInstallError({
573 reason: "install_locked",
574 message: "Another relay client installation is still in progress.",
575 });
576 });
577​
578 const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
579 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
580 ) {
581 yield* report("checking");
582 const config = yield* loadCloudflaredConfig;
583 if (Option.isSome(config.executableOverride)) {
584 const override = yield* compatibleCandidate(config.executableOverride.value, "override");
585 if (override) return override;
586 return yield* new RelayClientInstallError({
587 reason: "override_missing",
588 message: `${CLOUDFLARED_PATH_ENV_NAME} must point to cloudflared ${CLOUDFLARED_MIN_VERSION} or newer.`,
589 });
590 }
591 const existing = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
592 if (existing) return existing;
593 if (!releaseAsset) {
594 return yield* new RelayClientInstallError({
595 reason: "unsupported_platform",
596 message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
597 });
598 }
599​
600 const managedDirectory = path.dirname(managedPath);
601 const lockPath = `${managedPath}.lock`;
602 yield* fileSystem
603 .makeDirectory(managedDirectory, { recursive: true })
604 .pipe(
605 wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
606 );
607 yield* report("waiting_for_lock");
608 yield* acquireInstallLock(lockPath).pipe(
609 Effect.catchTags({
610 PlatformError: (cause) =>
611 Effect.fail(
612 new RelayClientInstallError({
613 reason: "write_failed",
614 message: "Could not acquire the relay client installation lock.",
615 cause,
616 }),
617 ),
618 }),
619 );
620 return yield* Effect.gen(function* () {
621 const afterLock = yield* compatibleCandidate(managedPath, "managed", CLOUDFLARED_VERSION);
622 if (afterLock) return afterLock;
623​
624 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
625 directory: managedDirectory,
626 prefix: ".install-",
627 });
628 const archivePath = path.join(
629 tempDirectory,
630 releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
631 );
632 const download = yield* downloadAsset(releaseAsset, report);
633 yield* report("installing");
634 yield* fileSystem
635 .writeFile(archivePath, download)
636 .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
637​
638 const executablePath = path.join(tempDirectory, executableFileName(platform));
639 if (releaseAsset.archive === "tgz") {
640 yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
641 wrapInstallFailure("write_failed", "Could not extract the relay client."),
642 );
643 }
644 if (platform !== "win32") {
645 yield* fileSystem
646 .chmod(executablePath, 0o755)
647 .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
648 }
649 yield* report("validating");
650 // Verify the pin so mislabeled assets cannot cause repeated redownloads.
651 const installedVersion = yield* probeVersion(executablePath);
652 if (installedVersion !== CLOUDFLARED_VERSION) {
653 return yield* new RelayClientInstallError({
654 reason: "validation_failed",
655 message:
656 installedVersion === null
657 ? "The downloaded relay client binary did not run."
658 : `The downloaded relay client reports version ${installedVersion}, not ${CLOUDFLARED_VERSION}.`,
659 });
660 }
661​
662 const stagedPath = `${managedPath}.${yield* random.uuidV4()}.tmp`;
663 yield* report("activating");
664 yield* renameWhenUnlocked(executablePath, stagedPath).pipe(
665 wrapInstallFailure("write_failed", "Could not stage the relay client."),
666 );
667 yield* renameWhenUnlocked(stagedPath, managedPath).pipe(
668 wrapInstallFailure("write_failed", "Could not activate the relay client."),
669 Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
670 );
671 return {
672 status: "available",
673 executablePath: managedPath,
674 source: "managed",
675 version: CLOUDFLARED_VERSION,
676 } satisfies AvailableRelayClient;
677 }).pipe(
678 Effect.scoped,
679 Effect.catchIf(
680 (cause) => !isRelayClientInstallError(cause),
681 (cause) =>
682 Effect.fail(
683 new RelayClientInstallError({
684 reason: "write_failed",
685 message: "Could not install the relay client.",
686 cause,
687 }),
688 ),
689 ),
690 );
691 });
692 const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
693 installSemaphore.withPermit(
694 installUnlocked((stage) =>
695 report({
696 type: "progress",
697 stage,
698 }),
699 ).pipe(Effect.scoped),
700 );
701 const install = installWithProgress(() => Effect.void);
702​
703 return RelayClient.of({ resolve, install, installWithProgress, pruneManagedVersions });
704});
705​
706export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
707 Layer.effect(RelayClient, makeCloudflaredRelayClient(options));