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

relayClient.ts

502 lines16.8 KB

1import * as Clock from "effect/Clock";
2import type {
3 RelayClientInstallProgressEvent,
4 RelayClientInstallProgressStage,
5} from "@t3tools/contracts";
6import * as Config from "effect/Config";
7import * as ConfigProvider from "effect/ConfigProvider";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as Data from "effect/Data";
11import * as Effect from "effect/Effect";
12import * as Encoding from "effect/Encoding";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Path from "effect/Path";
17import * as PlatformError from "effect/PlatformError";
18import * as Semaphore from "effect/Semaphore";
19import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
20import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
21​
22export const CLOUDFLARED_VERSION = "2026.5.2";
23export const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";
24​
25export type RelayClientExecutableSource = "override" | "managed" | "path";
26​
27export type RelayClientStatus =
28 | {
29 readonly status: "available";
30 readonly executablePath: string;
31 readonly source: RelayClientExecutableSource;
32 readonly version: string;
33 }
34 | {
35 readonly status: "missing";
36 readonly version: string;
37 }
38 | {
39 readonly status: "unsupported";
40 readonly platform: NodeJS.Platform;
41 readonly arch: string;
42 readonly version: string;
43 };
44​
45export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
46​
47export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
48 readonly reason:
49 | "download_failed"
50 | "invalid_checksum"
51 | "install_locked"
52 | "override_missing"
53 | "unsupported_platform"
54 | "validation_failed"
55 | "write_failed";
56 readonly message: string;
57 readonly cause?: unknown;
58}> {}
59​
60class CloudflaredCommandError extends Data.TaggedError("CloudflaredCommandError")<{
61 readonly command: string;
62 readonly exitCode: number;
63}> {}
64​
65export interface CloudflaredReleaseAsset {
66 readonly url: string;
67 readonly sha256: string;
68 readonly archive: "binary" | "tgz";
70​
71const CLOUDFLARED_RELEASE_ASSETS: Readonly<
72 Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>
73> = {
74 "darwin-arm64": {
75 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-arm64.tgz",
76 sha256: "ba94054c9fd4297645093d59d51442e5e546d07bb0516120e694a13d5b216d38",
77 archive: "tgz",
78 },
79 "darwin-x64": {
80 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-amd64.tgz",
81 sha256: "7240f709506bc2c1eb9da4d89cf2555499c60280ecb854b7d80e8f17d4b7903d",
82 archive: "tgz",
83 },
84 "linux-arm64": {
85 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-arm64",
86 sha256: "5a4e8ce2701105271412059f44b6a0bf1ae4542b4d98ff3180c0c019443a5815",
87 archive: "binary",
88 },
89 "linux-x64": {
90 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-amd64",
91 sha256: "5286698547f03df745adb2355f04c12dde52ef425491e81f433642d695521886",
92 archive: "binary",
93 },
94 "win32-x64": {
95 url: "https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-windows-amd64.exe",
96 sha256: "20b9638f685333d623798e733effbad2487093f15ba592f6c7752360ff3b7ab7",
97 archive: "binary",
98 },
99};
100​
101const INSTALL_LOCK_RETRY_COUNT = 100;
102const INSTALL_LOCK_RETRY_DELAY = "100 millis";
103const INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;
104​
105const trimmedString = (name: string) =>
106 Config.string(name).pipe(
107 Config.option,
108 Config.map(
109 Option.flatMap((value) => {
110 const trimmed = value.trim();
111 return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
112 }),
113 ),
114 );
115​
116const CloudflaredConfig = Config.all({
117 executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),
118 path: trimmedString("PATH"),
119});
120​
121export interface CloudflaredRelayClientOptions {
122 readonly baseDir: string;
123 readonly platform?: NodeJS.Platform;
124 readonly arch?: string;
125 readonly releaseAsset?: CloudflaredReleaseAsset;
126 readonly configProvider?: () => ConfigProvider.ConfigProvider;
128​
129export interface RelayClientShape {
130 readonly resolve: Effect.Effect<RelayClientStatus>;
131 readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
132 readonly installWithProgress: (
133 report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
134 ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
136​
137export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
138 "@t3tools/shared/relayClient",
139) {}
140​
141function executableFileName(platform: NodeJS.Platform): string {
142 return platform === "win32" ? "cloudflared.exe" : "cloudflared";
144​
145export function resolveManagedCloudflaredPath(input: {
146 readonly baseDir: string;
147 readonly platform: NodeJS.Platform;
148 readonly arch: string;
149}): string {
150 const separator = input.platform === "win32" ? "\\" : "/";
151 return [
152 input.baseDir.replace(/[\\/]+$/u, ""),
153 "tools",
154 "cloudflared",
155 CLOUDFLARED_VERSION,
156 `${input.platform}-${input.arch}`,
157 executableFileName(input.platform),
158 ].join(separator);
160​
161function resolveReleaseAsset(
162 platform: NodeJS.Platform,
163 arch: string,
164): CloudflaredReleaseAsset | null {
165 return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;
167​
168function isAlreadyExists(error: PlatformError.PlatformError): boolean {
169 return error.reason._tag === "AlreadyExists";
171​
172const wrapInstallFailure =
173 (
174 reason: RelayClientInstallError["reason"],
175 message: string,
176 ): (<E, R>(
177 effect: Effect.Effect<void, E, R>,
178 ) => Effect.Effect<void, RelayClientInstallError, R>) =>
179 (effect) =>
180 effect.pipe(
181 Effect.mapError(
182 (cause) =>
183 new RelayClientInstallError({
184 reason,
185 message,
186 cause,
187 }),
188 ),
189 );
190​
191export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
192 options: CloudflaredRelayClientOptions,
193): Effect.fn.Return<
194 RelayClientShape,
195 never,
196 | ChildProcessSpawner.ChildProcessSpawner
197 | Crypto.Crypto
198 | FileSystem.FileSystem
199 | HttpClient.HttpClient
200 | Path.Path
201> {
202 const crypto = yield* Crypto.Crypto;
203 const fileSystem = yield* FileSystem.FileSystem;
204 const httpClient = yield* HttpClient.HttpClient;
205 const path = yield* Path.Path;
206 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
207 const installSemaphore = yield* Semaphore.make(1);
208 const platform = options.platform ?? process.platform;
209 const arch = options.arch ?? process.arch;
210 const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);
211 const loadCloudflaredConfig = Effect.suspend(() =>
212 CloudflaredConfig.pipe(
213 Effect.provideService(
214 ConfigProvider.ConfigProvider,
215 options.configProvider?.() ?? ConfigProvider.fromEnv(),
216 ),
217 ),
218 ).pipe(Effect.orDie);
219 const managedPath = path.join(
220 options.baseDir,
221 "tools",
222 "cloudflared",
223 CLOUDFLARED_VERSION,
224 `${platform}-${arch}`,
225 executableFileName(platform),
226 );
227​
228 const isExecutableFile = Effect.fn("cloudflared.isExecutableFile")(function* (
229 executablePath: string,
230 ) {
231 const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);
232 if (Option.isNone(info) || info.value.type !== "File") return false;
233 return platform === "win32" || (info.value.mode & 0o111) !== 0;
234 });
235​
236 const resolvePathExecutable = Effect.gen(function* () {
237 const config = yield* loadCloudflaredConfig;
238 const pathValue = Option.getOrUndefined(config.path);
239 if (!pathValue) return null;
240 const delimiter = platform === "win32" ? ";" : ":";
241 for (const directory of pathValue.split(delimiter)) {
242 const trimmed = directory.trim().replace(/^"|"$/gu, "");
243 if (trimmed.length === 0) continue;
244 const candidate = path.join(trimmed, executableFileName(platform));
245 if (yield* isExecutableFile(candidate)) return candidate;
246 }
247 return null;
248 });
249​
250 const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
251 const config = yield* loadCloudflaredConfig;
252 if (Option.isSome(config.executableOverride)) {
253 return (yield* isExecutableFile(config.executableOverride.value))
254 ? {
255 status: "available",
256 executablePath: config.executableOverride.value,
257 source: "override",
258 version: CLOUDFLARED_VERSION,
259 }
260 : { status: "missing", version: CLOUDFLARED_VERSION };
261 }
262 if (yield* isExecutableFile(managedPath)) {
263 return {
264 status: "available",
265 executablePath: managedPath,
266 source: "managed",
267 version: CLOUDFLARED_VERSION,
268 };
269 }
270 const pathExecutable = yield* resolvePathExecutable;
271 if (pathExecutable) {
272 return {
273 status: "available",
274 executablePath: pathExecutable,
275 source: "path",
276 version: CLOUDFLARED_VERSION,
277 };
278 }
279 return releaseAsset
280 ? { status: "missing", version: CLOUDFLARED_VERSION }
281 : {
282 status: "unsupported",
283 platform,
284 arch,
285 version: CLOUDFLARED_VERSION,
286 };
287 });
288​
289 const runCommand = Effect.fn("cloudflared.runCommand")(function* (
290 command: string,
291 args: ReadonlyArray<string>,
292 ) {
293 const child = yield* spawner.spawn(
294 ChildProcess.make(command, args, {
295 shell: false,
296 stdout: "ignore",
297 stderr: "ignore",
298 }),
299 );
300 const exitCode = Number(yield* child.exitCode);
301 if (exitCode !== 0) {
302 return yield* new CloudflaredCommandError({ command, exitCode });
303 }
304 });
305​
306 const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* (
307 asset: CloudflaredReleaseAsset,
308 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
309 ) {
310 yield* report("downloading");
311 const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(
312 Effect.flatMap(HttpClientResponse.filterStatusOk),
313 Effect.mapError(
314 (cause) =>
315 new RelayClientInstallError({
316 reason: "download_failed",
317 message: "Could not download the relay client.",
318 cause,
319 }),
320 ),
321 );
322 const bytes = new Uint8Array(
323 yield* response.arrayBuffer.pipe(
324 Effect.mapError(
325 (cause) =>
326 new RelayClientInstallError({
327 reason: "download_failed",
328 message: "Could not read the downloaded relay client binary.",
329 cause,
330 }),
331 ),
332 ),
333 );
334 yield* report("verifying");
335 const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
336 Effect.mapError(
337 (cause) =>
338 new RelayClientInstallError({
339 reason: "validation_failed",
340 message: "Could not verify the downloaded relay client checksum.",
341 cause,
342 }),
343 ),
344 );
345 if (Encoding.encodeHex(checksum) !== asset.sha256) {
346 return yield* new RelayClientInstallError({
347 reason: "invalid_checksum",
348 message: "Downloaded relay client checksum did not match the pinned release.",
349 });
350 }
351 return bytes;
352 });
353​
354 const acquireInstallLock = Effect.fn("cloudflared.acquireInstallLock")(function* (
355 lockPath: string,
356 ) {
357 for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {
358 const acquired = yield* fileSystem.writeFileString(lockPath, "", { flag: "wx" }).pipe(
359 Effect.as(true),
360 Effect.catch((error) =>
361 isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),
362 ),
363 );
364 if (acquired) return;
365​
366 const now = yield* Clock.currentTimeMillis;
367 const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);
368 const mtime = Option.flatMap(lockInfo, (info) => info.mtime);
369 if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {
370 yield* fileSystem.remove(lockPath, { force: true });
371 continue;
372 }
373 yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
374 }
375 return yield* new RelayClientInstallError({
376 reason: "install_locked",
377 message: "Another relay client installation is still in progress.",
378 });
379 });
380​
381 const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* (
382 report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,
383 ) {
384 yield* report("checking");
385 const existing = yield* resolve;
386 if (existing.status === "available") return existing;
387 const config = yield* loadCloudflaredConfig;
388 if (Option.isSome(config.executableOverride)) {
389 return yield* new RelayClientInstallError({
390 reason: "override_missing",
391 message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,
392 });
393 }
394 if (!releaseAsset) {
395 return yield* new RelayClientInstallError({
396 reason: "unsupported_platform",
397 message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
398 });
399 }
400​
401 const managedDirectory = path.dirname(managedPath);
402 const lockPath = `${managedPath}.lock`;
403 yield* fileSystem
404 .makeDirectory(managedDirectory, { recursive: true })
405 .pipe(
406 wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
407 );
408 yield* report("waiting_for_lock");
409 yield* acquireInstallLock(lockPath).pipe(
410 Effect.catchTag("PlatformError", (cause) =>
411 Effect.fail(
412 new RelayClientInstallError({
413 reason: "write_failed",
414 message: "Could not acquire the relay client installation lock.",
415 cause,
416 }),
417 ),
418 ),
419 );
420 return yield* Effect.gen(function* () {
421 const afterLock = yield* resolve;
422 if (afterLock.status === "available") return afterLock;
423​
424 const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({
425 directory: managedDirectory,
426 prefix: ".install-",
427 });
428 const archivePath = path.join(
429 tempDirectory,
430 releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform),
431 );
432 const download = yield* downloadAsset(releaseAsset, report);
433 yield* report("installing");
434 yield* fileSystem
435 .writeFile(archivePath, download)
436 .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
437​
438 const executablePath = path.join(tempDirectory, executableFileName(platform));
439 if (releaseAsset.archive === "tgz") {
440 yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
441 wrapInstallFailure("write_failed", "Could not extract the relay client."),
442 );
443 }
444 if (platform !== "win32") {
445 yield* fileSystem
446 .chmod(executablePath, 0o755)
447 .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
448 }
449 yield* report("validating");
450 yield* runCommand(executablePath, ["--version"]).pipe(
451 wrapInstallFailure("validation_failed", "The downloaded relay client binary did not run."),
452 );
453​
454 const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;
455 yield* report("activating");
456 yield* fileSystem
457 .rename(executablePath, stagedPath)
458 .pipe(wrapInstallFailure("write_failed", "Could not stage the relay client."));
459 yield* fileSystem
460 .rename(stagedPath, managedPath)
461 .pipe(
462 wrapInstallFailure("write_failed", "Could not activate the relay client."),
463 Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
464 );
465 return {
466 status: "available",
467 executablePath: managedPath,
468 source: "managed",
469 version: CLOUDFLARED_VERSION,
470 } satisfies AvailableRelayClient;
471 }).pipe(
472 Effect.scoped,
473 Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
474 Effect.catch((cause) =>
475 cause instanceof RelayClientInstallError
476 ? Effect.fail(cause)
477 : Effect.fail(
478 new RelayClientInstallError({
479 reason: "write_failed",
480 message: "Could not install the relay client.",
481 cause,
482 }),
483 ),
484 ),
485 );
486 });
487 const installWithProgress: RelayClientShape["installWithProgress"] = (report) =>
488 installSemaphore.withPermit(
489 installUnlocked((stage) =>
490 report({
491 type: "progress",
492 stage,
493 }),
494 ),
495 );
496 const install = installWithProgress(() => Effect.void);
497​
498 return RelayClient.of({ resolve, install, installWithProgress });
499});
500​
501export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
502 Layer.effect(RelayClient, makeCloudflaredRelayClient(options));