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

relayClient.ts

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