refactor(cloud): name managed connector relay client

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-04 14:03:00 -07:00
1 parent 321e4b9551
commit 373e9fc504
18 files changed
+168 -170

No files matched your search

+3 -3
View File
@@ -9,7 +9,7 @@ import {
setCloudAuthToken,
} from "./methods/cloudAuth.ts";
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
import { getCloudflaredStatus, installCloudflared } from "./methods/cloudflared.ts";
import { getRelayClientStatus, installRelayClient } from "./methods/relayClient.ts";
import {
getSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
@@ -88,8 +88,8 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
yield* ipc.handle(setCloudAuthToken);
yield* ipc.handle(clearCloudAuthToken);
yield* ipc.handle(fetchCloudAuth);
yield* ipc.handle(getCloudflaredStatus);
yield* ipc.handle(installCloudflared);
yield* ipc.handle(getRelayClientStatus);
yield* ipc.handle(installRelayClient);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
+2 -2
View File
@@ -8,8 +8,8 @@ export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token";
export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token";
export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token";
export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth";
export const GET_CLOUDFLARED_STATUS_CHANNEL = "desktop:get-cloudflared-status";
export const INSTALL_CLOUDFLARED_CHANNEL = "desktop:install-cloudflared";
export const GET_RELAY_CLIENT_STATUS_CHANNEL = "desktop:get-relay-client-status";
export const INSTALL_RELAY_CLIENT_CHANNEL = "desktop:install-relay-client";
export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
@@ -1,27 +0,0 @@
import { DesktopCloudflaredStatusSchema } from "@t3tools/contracts";
import * as Cloudflared from "@t3tools/shared/cloudflared";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getCloudflaredStatus = makeIpcMethod({
channel: IpcChannels.GET_CLOUDFLARED_STATUS_CHANNEL,
payload: Schema.Undefined,
result: DesktopCloudflaredStatusSchema,
handler: Effect.fn("desktop.ipc.cloudflared.getStatus")(function* () {
const cloudflared = yield* Cloudflared.CloudflaredExecutable;
return yield* cloudflared.resolve;
}),
});
export const installCloudflared = makeIpcMethod({
channel: IpcChannels.INSTALL_CLOUDFLARED_CHANNEL,
payload: Schema.Undefined,
result: DesktopCloudflaredStatusSchema,
handler: Effect.fn("desktop.ipc.cloudflared.install")(function* () {
const cloudflared = yield* Cloudflared.CloudflaredExecutable;
return yield* cloudflared.install;
}),
});
@@ -1,27 +1,27 @@
import { describe, expect, it } from "@effect/vitest";
import * as Cloudflared from "@t3tools/shared/cloudflared";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { getCloudflaredStatus, installCloudflared } from "./cloudflared.ts";
import { getRelayClientStatus, installRelayClient } from "./relayClient.ts";
const available = {
status: "available",
executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared",
source: "managed",
version: Cloudflared.CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
} as const;
describe("Desktop cloudflared IPC", () => {
describe("Desktop relay client IPC", () => {
it.effect("reads status and delegates installation to the shared manager", () =>
Effect.gen(function* () {
const installed: Array<boolean> = [];
const layer = Layer.succeed(
Cloudflared.CloudflaredExecutable,
Cloudflared.CloudflaredExecutable.of({
RelayClient.RelayClient,
RelayClient.RelayClient.of({
resolve: Effect.succeed({
status: "missing",
version: Cloudflared.CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
}),
install: Effect.sync(() => {
installed.push(true);
@@ -30,11 +30,11 @@ describe("Desktop cloudflared IPC", () => {
}),
);
expect(yield* getCloudflaredStatus.handler(undefined).pipe(Effect.provide(layer))).toEqual({
expect(yield* getRelayClientStatus.handler(undefined).pipe(Effect.provide(layer))).toEqual({
status: "missing",
version: Cloudflared.CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
});
expect(yield* installCloudflared.handler(undefined).pipe(Effect.provide(layer))).toEqual(
expect(yield* installRelayClient.handler(undefined).pipe(Effect.provide(layer))).toEqual(
available,
);
expect(installed).toEqual([true]);
@@ -0,0 +1,27 @@
import { DesktopRelayClientStatusSchema } from "@t3tools/contracts";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
export const getRelayClientStatus = makeIpcMethod({
channel: IpcChannels.GET_RELAY_CLIENT_STATUS_CHANNEL,
payload: Schema.Undefined,
result: DesktopRelayClientStatusSchema,
handler: Effect.fn("desktop.ipc.relayClient.getStatus")(function* () {
const relayClient = yield* RelayClient.RelayClient;
return yield* relayClient.resolve;
}),
});
export const installRelayClient = makeIpcMethod({
channel: IpcChannels.INSTALL_RELAY_CLIENT_CHANNEL,
payload: Schema.Undefined,
result: DesktopRelayClientStatusSchema,
handler: Effect.fn("desktop.ipc.relayClient.install")(function* () {
const relayClient = yield* RelayClient.RelayClient;
return yield* relayClient.install;
}),
});
+4 -4
View File
@@ -9,7 +9,7 @@ import * as Option from "effect/Option";
import * as Electron from "electron";
import * as NetService from "@t3tools/shared/Net";
import * as Cloudflared from "@t3tools/shared/cloudflared";
import * as RelayClient from "@t3tools/shared/relayClient";
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
@@ -95,10 +95,10 @@ const desktopSshEnvironmentLayer = Layer.unwrap(
}),
);
const desktopCloudflaredLayer = Layer.unwrap(
const desktopRelayClientLayer = Layer.unwrap(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return Cloudflared.layer({
return RelayClient.layerCloudflared({
baseDir: environment.baseDir,
platform: environment.platform,
arch: environment.processArch,
@@ -155,7 +155,7 @@ const desktopApplicationLayer = Layer.mergeAll(
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Layer.provideMerge(desktopCloudflaredLayer),
Layer.provideMerge(desktopRelayClientLayer),
Layer.provideMerge(desktopBackendLayer),
);
+2 -2
View File
@@ -102,8 +102,8 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token),
clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL),
fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input),
getCloudflaredStatus: () => ipcRenderer.invoke(IpcChannels.GET_CLOUDFLARED_STATUS_CHANNEL),
installCloudflared: () => ipcRenderer.invoke(IpcChannels.INSTALL_CLOUDFLARED_CHANNEL),
getRelayClientStatus: () => ipcRenderer.invoke(IpcChannels.GET_RELAY_CLIENT_STATUS_CHANNEL),
installRelayClient: () => ipcRenderer.invoke(IpcChannels.INSTALL_RELAY_CLIENT_CHANNEL),
onCloudAuthCallback: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => {
if (typeof rawUrl !== "string") return;
@@ -8,18 +8,18 @@ import * as PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import * as Cloudflared from "@t3tools/shared/cloudflared";
import * as RelayClient from "@t3tools/shared/relayClient";
import { makeCloudManagedEndpointRuntime } from "./ManagedEndpointRuntime.ts";
const cloudflaredAvailableLayer = Layer.succeed(
Cloudflared.CloudflaredExecutable,
Cloudflared.CloudflaredExecutable.of({
const relayClientAvailableLayer = Layer.succeed(
RelayClient.RelayClient,
RelayClient.RelayClient.of({
resolve: Effect.succeed({
status: "available",
executablePath: "cloudflared",
source: "path",
version: Cloudflared.CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
}),
install: Effect.die("unused"),
}),
@@ -28,7 +28,7 @@ const cloudflaredAvailableLayer = Layer.succeed(
const runtimeDependencies = (spawner: ReturnType<typeof ChildProcessSpawner.make>) =>
Layer.mergeAll(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
cloudflaredAvailableLayer,
relayClientAvailableLayer,
);
function makeHandle(input: {
@@ -317,7 +317,7 @@ describe("CloudManagedEndpointRuntime", () => {
}),
);
it.effect("reports a missing cloudflared executable without spawning", () =>
it.effect("reports a missing relay client executable without spawning", () =>
Effect.gen(function* () {
const spawn = vi.fn();
const spawner = ChildProcessSpawner.make(spawn);
@@ -326,11 +326,11 @@ describe("CloudManagedEndpointRuntime", () => {
Layer.mergeAll(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
Layer.succeed(
Cloudflared.CloudflaredExecutable,
Cloudflared.CloudflaredExecutable.of({
RelayClient.RelayClient,
RelayClient.RelayClient.of({
resolve: Effect.succeed({
status: "missing",
version: Cloudflared.CLOUDFLARED_VERSION,
version: RelayClient.CLOUDFLARED_VERSION,
}),
install: Effect.die("unused"),
}),
@@ -347,7 +347,7 @@ describe("CloudManagedEndpointRuntime", () => {
expect(status).toEqual({
status: "failed",
providerKind: "cloudflare_tunnel",
reason: "cloudflared is not installed.",
reason: "The relay client is not installed.",
});
expect(spawn).not.toHaveBeenCalled();
}),
@@ -1,5 +1,5 @@
import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
import * as Cloudflared from "@t3tools/shared/cloudflared";
import * as RelayClient from "@t3tools/shared/relayClient";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -91,7 +91,7 @@ const stopConnector = (connector: ActiveConnector | null) =>
export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const cloudflared = yield* Cloudflared.CloudflaredExecutable;
const relayClient = yield* RelayClient.RelayClient;
const activeRef = yield* Ref.make<ActiveConnector | null>(null);
const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
const reconcileSemaphore = yield* Semaphore.make(1);
@@ -170,15 +170,15 @@ export const makeCloudManagedEndpointRuntime = Effect.gen(function* () {
yield* stopActive;
const executable = yield* cloudflared.resolve;
const executable = yield* relayClient.resolve;
if (executable.status !== "available") {
return {
status: "failed",
providerKind: "cloudflare_tunnel",
reason:
executable.status === "unsupported"
? `Managed cloudflared is unsupported on ${executable.platform}-${executable.arch}.`
: "cloudflared is not installed.",
? `Managed relay client is unsupported on ${executable.platform}-${executable.arch}.`
: "The relay client is not installed.",
...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
} satisfies CloudManagedEndpointRuntimeStatus;
+4 -4
View File
@@ -81,7 +81,7 @@ import {
} from "./serverRuntimeState.ts";
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
import * as NetService from "@t3tools/shared/Net";
import * as Cloudflared from "@t3tools/shared/cloudflared";
import * as RelayClient from "@t3tools/shared/relayClient";
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
const PtyAdapterLive = Layer.unwrap(
@@ -96,10 +96,10 @@ const PtyAdapterLive = Layer.unwrap(
}),
);
const CloudflaredExecutableLive = Layer.unwrap(
const RelayClientLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
return Cloudflared.layer({ baseDir: config.baseDir });
return RelayClient.layerCloudflared({ baseDir: config.baseDir });
}),
);
@@ -287,7 +287,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
Layer.provideMerge(
CloudManagedEndpointRuntime.layer.pipe(
Layer.provide(ServerSecretStore.layer),
Layer.provide(CloudflaredExecutableLive),
Layer.provide(RelayClientLive),
),
),
);
+14 -14
View File
@@ -16,7 +16,7 @@ import {
import type { SavedEnvironmentRecord } from "../environments/runtime";
import {
connectManagedCloudEnvironment,
ensureDesktopCloudflaredAvailable,
ensureDesktopRelayClientAvailable,
linkEnvironmentToCloud,
linkPrimaryEnvironmentToCloud,
listManagedCloudEnvironments,
@@ -124,10 +124,10 @@ describe("web cloud link environment client", () => {
expect(normalizeRelayBaseUrl(" ")).toBeNull();
});
it("installs cloudflared after desktop confirmation", async () => {
it("installs the relay client after desktop confirmation", async () => {
vi.stubGlobal("window", {});
const confirm = vi.fn().mockResolvedValue(true);
const installCloudflared = vi.fn().mockResolvedValue({
const installRelayClient = vi.fn().mockResolvedValue({
status: "available",
executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared",
source: "managed",
@@ -135,35 +135,35 @@ describe("web cloud link environment client", () => {
});
window.desktopBridge = {
confirm,
getCloudflaredStatus: vi.fn().mockResolvedValue({
getRelayClientStatus: vi.fn().mockResolvedValue({
status: "missing",
version: "2026.5.2",
}),
installCloudflared,
installRelayClient,
} as unknown as DesktopBridge;
await Effect.runPromise(ensureDesktopCloudflaredAvailable());
await Effect.runPromise(ensureDesktopRelayClientAvailable());
expect(confirm).toHaveBeenCalledOnce();
expect(installCloudflared).toHaveBeenCalledOnce();
expect(installRelayClient).toHaveBeenCalledOnce();
});
it("does not install cloudflared when desktop confirmation is declined", async () => {
it("does not install the relay client when desktop confirmation is declined", async () => {
vi.stubGlobal("window", {});
const installCloudflared = vi.fn();
const installRelayClient = vi.fn();
window.desktopBridge = {
confirm: vi.fn().mockResolvedValue(false),
getCloudflaredStatus: vi.fn().mockResolvedValue({
getRelayClientStatus: vi.fn().mockResolvedValue({
status: "missing",
version: "2026.5.2",
}),
installCloudflared,
installRelayClient,
} as unknown as DesktopBridge;
await expect(Effect.runPromise(ensureDesktopCloudflaredAvailable())).rejects.toMatchObject({
message: "Cloudflare Tunnel installation was cancelled.",
await expect(Effect.runPromise(ensureDesktopRelayClientAvailable())).rejects.toMatchObject({
message: "Relay client installation was cancelled.",
});
expect(installCloudflared).not.toHaveBeenCalled();
expect(installRelayClient).not.toHaveBeenCalled();
});
it.effect("lists relay-managed environments for hosted and served web clients", () =>
+14 -14
View File
@@ -56,13 +56,13 @@ export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmen
readonly cause?: unknown;
}> {}
const desktopCloudflaredBridgeError = (cause: unknown) =>
const desktopRelayClientBridgeError = (cause: unknown) =>
new CloudEnvironmentLinkError({
message: "Could not prepare Cloudflare Tunnel.",
message: "Could not prepare the relay client.",
cause,
});
export function ensureDesktopCloudflaredAvailable(): Effect.Effect<
export function ensureDesktopRelayClientAvailable(): Effect.Effect<
void,
CloudEnvironmentLinkError
> {
@@ -71,39 +71,39 @@ export function ensureDesktopCloudflaredAvailable(): Effect.Effect<
return Effect.gen(function* () {
const status = yield* Effect.tryPromise({
try: () => bridge.getCloudflaredStatus(),
catch: desktopCloudflaredBridgeError,
try: () => bridge.getRelayClientStatus(),
catch: desktopRelayClientBridgeError,
});
if (status.status === "available") return;
if (status.status === "unsupported") {
return yield* new CloudEnvironmentLinkError({
message: `T3 Code cannot install cloudflared automatically on ${status.platform}-${status.arch}.`,
message: `T3 Code cannot install the relay client automatically on ${status.platform}-${status.arch}.`,
});
}
const confirmed = yield* Effect.tryPromise({
try: () =>
bridge.confirm(
"T3 Code needs Cloudflare Tunnel to make this environment available through T3 Cloud. Download and install cloudflared now?",
"T3 Code needs the relay client to make this environment available through T3 Cloud. Download and install it now?",
),
catch: desktopCloudflaredBridgeError,
catch: desktopRelayClientBridgeError,
});
if (!confirmed) {
return yield* new CloudEnvironmentLinkError({
message: "Cloudflare Tunnel installation was cancelled.",
message: "Relay client installation was cancelled.",
});
}
const installed = yield* Effect.tryPromise({
try: () => bridge.installCloudflared(),
catch: desktopCloudflaredBridgeError,
try: () => bridge.installRelayClient(),
catch: desktopRelayClientBridgeError,
});
if (installed.status !== "available") {
return yield* new CloudEnvironmentLinkError({
message:
installed.status === "unsupported"
? `T3 Code cannot install cloudflared automatically on ${installed.platform}-${installed.arch}.`
: "cloudflared is still unavailable after installation.",
? `T3 Code cannot install the relay client automatically on ${installed.platform}-${installed.arch}.`
: "The relay client is still unavailable after installation.",
});
}
});
@@ -624,7 +624,7 @@ export function linkPrimaryEnvironmentToCloud(input: {
message: "Local environment is not ready yet.",
});
}
yield* ensureDesktopCloudflaredAvailable();
yield* ensureDesktopRelayClientAvailable();
const challenge = yield* relayClient
.createEnvironmentLinkChallenge({
@@ -470,13 +470,13 @@ const createDesktopBridgeStub = (overrides?: {
headers: {},
body: "",
}),
getCloudflaredStatus: vi.fn().mockResolvedValue({
getRelayClientStatus: vi.fn().mockResolvedValue({
status: "available",
executablePath: "/usr/local/bin/cloudflared",
source: "path",
version: "2026.5.2",
}),
installCloudflared: vi.fn().mockResolvedValue({
installRelayClient: vi.fn().mockResolvedValue({
status: "available",
executablePath: "/usr/local/bin/cloudflared",
source: "path",
+2 -2
View File
@@ -245,13 +245,13 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridg
headers: {},
body: "",
}),
getCloudflaredStatus: async () => ({
getRelayClientStatus: async () => ({
status: "available",
executablePath: "/usr/local/bin/cloudflared",
source: "path",
version: "2026.5.2",
}),
installCloudflared: async () => ({
installRelayClient: async () => ({
status: "available",
executablePath: "/usr/local/bin/cloudflared",
source: "path",
+4 -4
View File
@@ -394,7 +394,7 @@ export const DesktopCloudAuthFetchResultSchema = Schema.Struct({
});
export type DesktopCloudAuthFetchResult = typeof DesktopCloudAuthFetchResultSchema.Type;
export const DesktopCloudflaredStatusSchema = Schema.Union([
export const DesktopRelayClientStatusSchema = Schema.Union([
Schema.Struct({
status: Schema.Literal("available"),
executablePath: Schema.String,
@@ -412,7 +412,7 @@ export const DesktopCloudflaredStatusSchema = Schema.Union([
version: Schema.String,
}),
]);
export type DesktopCloudflaredStatus = typeof DesktopCloudflaredStatusSchema.Type;
export type DesktopRelayClientStatus = typeof DesktopRelayClientStatusSchema.Type;
export interface DesktopBridge {
getAppBranding: () => DesktopAppBranding | null;
@@ -464,8 +464,8 @@ export interface DesktopBridge {
setCloudAuthToken: (token: string) => Promise<boolean>;
clearCloudAuthToken: () => Promise<void>;
fetchCloudAuth: (input: DesktopCloudAuthFetchInput) => Promise<DesktopCloudAuthFetchResult>;
getCloudflaredStatus: () => Promise<DesktopCloudflaredStatus>;
installCloudflared: () => Promise<DesktopCloudflaredStatus>;
getRelayClientStatus: () => Promise<DesktopRelayClientStatus>;
installRelayClient: () => Promise<DesktopRelayClientStatus>;
onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
onMenuAction: (listener: (action: string) => void) => () => void;
getUpdateState: () => Promise<DesktopUpdateState>;
+3 -3
View File
@@ -139,9 +139,9 @@
"types": "./src/terminalLabels.ts",
"import": "./src/terminalLabels.ts"
},
"./cloudflared": {
"types": "./src/cloudflared.ts",
"import": "./src/cloudflared.ts"
"./relayClient": {
"types": "./src/relayClient.ts",
"import": "./src/relayClient.ts"
}
},
"scripts": {
@@ -12,11 +12,11 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
CloudflaredInstallError,
RelayClientInstallError,
CLOUDFLARED_VERSION,
makeCloudflaredExecutable,
makeCloudflaredRelayClient,
resolveManagedCloudflaredPath,
} from "./cloudflared.ts";
} from "./relayClient.ts";
const emptyConfigProvider = () => ConfigProvider.fromEnv({ env: {} });
@@ -57,7 +57,7 @@ const makeSpawnerLayer = (commands: Array<string>) =>
),
);
describe("CloudflaredExecutable", () => {
describe("RelayClient", () => {
it.effect("resolves explicit overrides before managed and PATH executables", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -67,7 +67,7 @@ describe("CloudflaredExecutable", () => {
const overridePath = `${baseDir}/override-cloudflared`;
yield* fileSystem.writeFileString(overridePath, "override");
yield* fileSystem.chmod(overridePath, 0o755);
const manager = yield* makeCloudflaredExecutable({
const manager = yield* makeCloudflaredRelayClient({
baseDir,
platform: "linux",
arch: "x64",
@@ -105,7 +105,7 @@ describe("CloudflaredExecutable", () => {
prefix: "t3-cloudflared-test-",
});
const bytes = new TextEncoder().encode("test-cloudflared-binary");
const manager = yield* makeCloudflaredExecutable({
const manager = yield* makeCloudflaredRelayClient({
baseDir,
platform: "linux",
arch: "x64",
@@ -151,7 +151,7 @@ describe("CloudflaredExecutable", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-cloudflared-test-",
});
const manager = yield* makeCloudflaredExecutable({
const manager = yield* makeCloudflaredRelayClient({
baseDir,
platform: "linux",
arch: "x64",
@@ -164,7 +164,7 @@ describe("CloudflaredExecutable", () => {
});
const error = yield* manager.install.pipe(Effect.flip);
expect(error).toBeInstanceOf(CloudflaredInstallError);
expect(error).toBeInstanceOf(RelayClientInstallError);
expect(error.reason).toBe("invalid_checksum");
}).pipe(
Effect.scoped,
@@ -186,7 +186,7 @@ describe("CloudflaredExecutable", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-cloudflared-test-",
});
const manager = yield* makeCloudflaredExecutable({
const manager = yield* makeCloudflaredRelayClient({
baseDir,
platform: "linux",
arch: "x64",
@@ -220,7 +220,7 @@ describe("CloudflaredExecutable", () => {
const binDir = `${baseDir}/bin`;
const executablePath = `${binDir}/cloudflared`;
let path = "";
const manager = yield* makeCloudflaredExecutable({
const manager = yield* makeCloudflaredRelayClient({
baseDir,
platform: "linux",
arch: "x64",
@@ -18,13 +18,13 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export const CLOUDFLARED_VERSION = "2026.5.2";
export const CLOUDFLARED_PATH_ENV_NAME = "T3CODE_CLOUDFLARED_PATH";
export type CloudflaredExecutableSource = "override" | "managed" | "path";
export type RelayClientExecutableSource = "override" | "managed" | "path";
export type CloudflaredExecutableStatus =
export type RelayClientStatus =
| {
readonly status: "available";
readonly executablePath: string;
readonly source: CloudflaredExecutableSource;
readonly source: RelayClientExecutableSource;
readonly version: string;
}
| {
@@ -38,12 +38,9 @@ export type CloudflaredExecutableStatus =
readonly version: string;
};
export type AvailableCloudflaredExecutable = Extract<
CloudflaredExecutableStatus,
{ readonly status: "available" }
>;
export type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: "available" }>;
export class CloudflaredInstallError extends Data.TaggedError("CloudflaredInstallError")<{
export class RelayClientInstallError extends Data.TaggedError("RelayClientInstallError")<{
readonly reason:
| "download_failed"
| "invalid_checksum"
@@ -117,7 +114,7 @@ const CloudflaredConfig = Config.all({
path: trimmedString("PATH"),
});
export interface CloudflaredExecutableOptions {
export interface CloudflaredRelayClientOptions {
readonly baseDir: string;
readonly platform?: NodeJS.Platform;
readonly arch?: string;
@@ -125,15 +122,14 @@ export interface CloudflaredExecutableOptions {
readonly configProvider?: () => ConfigProvider.ConfigProvider;
}
export interface CloudflaredExecutableShape {
readonly resolve: Effect.Effect<CloudflaredExecutableStatus>;
readonly install: Effect.Effect<AvailableCloudflaredExecutable, CloudflaredInstallError>;
export interface RelayClientShape {
readonly resolve: Effect.Effect<RelayClientStatus>;
readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
}
export class CloudflaredExecutable extends Context.Service<
CloudflaredExecutable,
CloudflaredExecutableShape
>()("@t3tools/shared/cloudflared/CloudflaredExecutable") {}
export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
"@t3tools/shared/relayClient",
) {}
function executableFileName(platform: NodeJS.Platform): string {
return platform === "win32" ? "cloudflared.exe" : "cloudflared";
@@ -168,16 +164,16 @@ function isAlreadyExists(error: PlatformError.PlatformError): boolean {
const wrapInstallFailure =
(
reason: CloudflaredInstallError["reason"],
reason: RelayClientInstallError["reason"],
message: string,
): (<E, R>(
effect: Effect.Effect<void, E, R>,
) => Effect.Effect<void, CloudflaredInstallError, R>) =>
) => Effect.Effect<void, RelayClientInstallError, R>) =>
(effect) =>
effect.pipe(
Effect.mapError(
(cause) =>
new CloudflaredInstallError({
new RelayClientInstallError({
reason,
message,
cause,
@@ -185,10 +181,10 @@ const wrapInstallFailure =
),
);
export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function* (
options: CloudflaredExecutableOptions,
export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function* (
options: CloudflaredRelayClientOptions,
): Effect.fn.Return<
CloudflaredExecutableShape,
RelayClientShape,
never,
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
@@ -244,7 +240,7 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
return null;
});
const resolve: CloudflaredExecutableShape["resolve"] = Effect.gen(function* () {
const resolve: RelayClientShape["resolve"] = Effect.gen(function* () {
const config = yield* loadCloudflaredConfig;
if (Option.isSome(config.executableOverride)) {
return (yield* isExecutableFile(config.executableOverride.value))
@@ -307,9 +303,9 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
Effect.flatMap(HttpClientResponse.filterStatusOk),
Effect.mapError(
(cause) =>
new CloudflaredInstallError({
new RelayClientInstallError({
reason: "download_failed",
message: "Could not download cloudflared.",
message: "Could not download the relay client.",
cause,
}),
),
@@ -318,9 +314,9 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
yield* response.arrayBuffer.pipe(
Effect.mapError(
(cause) =>
new CloudflaredInstallError({
new RelayClientInstallError({
reason: "download_failed",
message: "Could not read the downloaded cloudflared binary.",
message: "Could not read the downloaded relay client binary.",
cause,
}),
),
@@ -329,17 +325,17 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
const checksum = yield* crypto.digest("SHA-256", bytes).pipe(
Effect.mapError(
(cause) =>
new CloudflaredInstallError({
new RelayClientInstallError({
reason: "validation_failed",
message: "Could not verify the downloaded cloudflared checksum.",
message: "Could not verify the downloaded relay client checksum.",
cause,
}),
),
);
if (Encoding.encodeHex(checksum) !== asset.sha256) {
return yield* new CloudflaredInstallError({
return yield* new RelayClientInstallError({
reason: "invalid_checksum",
message: "Downloaded cloudflared checksum did not match the pinned release.",
message: "Downloaded relay client checksum did not match the pinned release.",
});
}
return bytes;
@@ -366,26 +362,26 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
}
yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);
}
return yield* new CloudflaredInstallError({
return yield* new RelayClientInstallError({
reason: "install_locked",
message: "Another cloudflared installation is still in progress.",
message: "Another relay client installation is still in progress.",
});
});
const installUnlocked: CloudflaredExecutableShape["install"] = Effect.gen(function* () {
const installUnlocked: RelayClientShape["install"] = Effect.gen(function* () {
const existing = yield* resolve;
if (existing.status === "available") return existing;
const config = yield* loadCloudflaredConfig;
if (Option.isSome(config.executableOverride)) {
return yield* new CloudflaredInstallError({
return yield* new RelayClientInstallError({
reason: "override_missing",
message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,
});
}
if (!releaseAsset) {
return yield* new CloudflaredInstallError({
return yield* new RelayClientInstallError({
reason: "unsupported_platform",
message: `T3 Code does not provide a managed cloudflared binary for ${platform}-${arch}.`,
message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,
});
}
@@ -393,13 +389,15 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
const lockPath = `${managedPath}.lock`;
yield* fileSystem
.makeDirectory(managedDirectory, { recursive: true })
.pipe(wrapInstallFailure("write_failed", "Could not create the cloudflared tool directory."));
.pipe(
wrapInstallFailure("write_failed", "Could not create the relay client tool directory."),
);
yield* acquireInstallLock(lockPath).pipe(
Effect.catchTag("PlatformError", (cause) =>
Effect.fail(
new CloudflaredInstallError({
new RelayClientInstallError({
reason: "write_failed",
message: "Could not acquire the cloudflared installation lock.",
message: "Could not acquire the relay client installation lock.",
cause,
}),
),
@@ -419,31 +417,31 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
);
yield* fileSystem
.writeFile(archivePath, yield* downloadAsset(releaseAsset))
.pipe(wrapInstallFailure("write_failed", "Could not write the cloudflared download."));
.pipe(wrapInstallFailure("write_failed", "Could not write the relay client download."));
const executablePath = path.join(tempDirectory, executableFileName(platform));
if (releaseAsset.archive === "tgz") {
yield* runCommand("tar", ["-xzf", archivePath, "-C", tempDirectory]).pipe(
wrapInstallFailure("write_failed", "Could not extract cloudflared."),
wrapInstallFailure("write_failed", "Could not extract the relay client."),
);
}
if (platform !== "win32") {
yield* fileSystem
.chmod(executablePath, 0o755)
.pipe(wrapInstallFailure("write_failed", "Could not make cloudflared executable."));
.pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable."));
}
yield* runCommand(executablePath, ["--version"]).pipe(
wrapInstallFailure("validation_failed", "The downloaded cloudflared binary did not run."),
wrapInstallFailure("validation_failed", "The downloaded relay client binary did not run."),
);
const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;
yield* fileSystem
.rename(executablePath, stagedPath)
.pipe(wrapInstallFailure("write_failed", "Could not stage cloudflared."));
.pipe(wrapInstallFailure("write_failed", "Could not stage the relay client."));
yield* fileSystem
.rename(stagedPath, managedPath)
.pipe(
wrapInstallFailure("write_failed", "Could not activate cloudflared."),
wrapInstallFailure("write_failed", "Could not activate the relay client."),
Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),
);
return {
@@ -451,17 +449,17 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
executablePath: managedPath,
source: "managed",
version: CLOUDFLARED_VERSION,
} satisfies AvailableCloudflaredExecutable;
} satisfies AvailableRelayClient;
}).pipe(
Effect.scoped,
Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),
Effect.catch((cause) =>
cause instanceof CloudflaredInstallError
cause instanceof RelayClientInstallError
? Effect.fail(cause)
: Effect.fail(
new CloudflaredInstallError({
new RelayClientInstallError({
reason: "write_failed",
message: "Could not install cloudflared.",
message: "Could not install the relay client.",
cause,
}),
),
@@ -470,8 +468,8 @@ export const makeCloudflaredExecutable = Effect.fn("cloudflared.make")(function*
});
const install = installSemaphore.withPermit(installUnlocked);
return CloudflaredExecutable.of({ resolve, install });
return RelayClient.of({ resolve, install });
});
export const layer = (options: CloudflaredExecutableOptions) =>
Layer.effect(CloudflaredExecutable, makeCloudflaredExecutable(options));
export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>
Layer.effect(RelayClient, makeCloudflaredRelayClient(options));