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

relayClient.ts

626 lines23.4 KB

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