Open History to see the last commit
1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import * as RelayClient from "@t3tools/shared/relayClient";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Ref from "effect/Ref";
9import * as Result from "effect/Result";
10import * as Semaphore from "effect/Semaphore";
11import * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13import * as ChildProcess from "effect/unstable/process/ChildProcess";
14import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
15
16import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
17import { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from "./config.ts";
18
19function bytesToString(bytes: Uint8Array): string {
20 return new TextDecoder().decode(bytes);
21}
22
23const readRuntimeConfig = Effect.gen(function* () {
24 const secrets = yield* ServerSecretStore.ServerSecretStore;
25 const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);
26 if (Option.isNone(bytes)) {
27 return null;
28 }
29 return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));
30});
31
32export type CloudManagedEndpointRuntimeStatus =
33 | {
34 readonly status: "disabled";
35 }
36 | {
37 readonly status: "failed";
38 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
39 readonly reason: string;
40 readonly tunnelId?: string;
41 readonly tunnelName?: string;
42 }
43 | {
44 readonly status: "running";
45 readonly providerKind: "cloudflare_tunnel";
46 readonly pid: number;
47 readonly tunnelId?: string;
48 readonly tunnelName?: string;
49 }
50 | {
51 readonly status: "unsupported";
52 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
53 };
54
55export class CloudManagedEndpointRuntime extends Context.Service<
56 CloudManagedEndpointRuntime,
57 {
58 readonly applyConfig: (
59 config: RelayManagedEndpointRuntimeConfig | null,
60 ) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
61 }
62>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
63
64interface ActiveConnector {
65 readonly child: ChildProcessSpawner.ChildProcessHandle;
66 readonly scope: Scope.Closeable;
67 readonly configKey: string;
68 readonly config: RelayManagedEndpointRuntimeConfig;
69}
70
71export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
72 if (/\bRegistered tunnel connection\b/iu.test(line)) {
73 return "connected";
74 }
75 // cloudflared uses zerolog level tokens. FTL (fatal) and PNC (panic) are more
76 // severe than ERR, so they must surface at least as loudly — without them a
77 // fatal connector failure would be logged at debug and hidden.
78 return /\b(?:ERR|WRN|FTL|PNC)\b/u.test(line) ? "warning" : "debug";
79}
80
81function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
82 return JSON.stringify({
83 providerKind: config.providerKind,
84 connectorToken: config.connectorToken,
85 tunnelId: config.tunnelId ?? null,
86 tunnelName: config.tunnelName ?? null,
87 });
88}
89
90const stopConnector = (connector: ActiveConnector | null) =>
91 connector
92 ? Scope.close(connector.scope, Exit.void).pipe(
93 Effect.tap(() =>
94 Effect.logInfo("Relay client stopped", {
95 pid: Number(connector.child.pid),
96 }),
97 ),
98 Effect.ignore,
99 )
100 : Effect.void;
101
102export const make = Effect.gen(function* () {
103 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
104 const relayClient = yield* RelayClient.RelayClient;
105 const activeRef = yield* Ref.make<ActiveConnector | null>(null);
106 const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
107 const reconcileSemaphore = yield* Semaphore.make(1);
108 let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
109
110 const stopActive = Effect.gen(function* () {
111 const active = yield* Ref.getAndSet(activeRef, null);
112 yield* stopConnector(active);
113 });
114
115 const superviseConnector = (connector: ActiveConnector) =>
116 Effect.gen(function* () {
117 const result = yield* Effect.result(connector.child.exitCode);
118 yield* reconcileSemaphore.withPermits(1)(
119 Effect.gen(function* () {
120 const active = yield* Ref.get(activeRef);
121 if (
122 active?.child.pid !== connector.child.pid ||
123 active.configKey !== connector.configKey
124 ) {
125 return;
126 }
127 yield* Ref.set(activeRef, null);
128 yield* stopConnector(connector);
129
130 const desiredConfig = yield* Ref.get(desiredConfigRef);
131 if (
132 !desiredConfig ||
133 desiredConfig.providerKind !== "cloudflare_tunnel" ||
134 runtimeConfigKey(desiredConfig) !== connector.configKey
135 ) {
136 return;
137 }
138
139 yield* Effect.logWarning("Relay client exited; restarting", {
140 pid: Number(connector.child.pid),
141 ...(Result.isSuccess(result)
142 ? { exitCode: Number(result.success) }
143 : { cause: result.failure }),
144 tunnelId: connector.config.tunnelId,
145 tunnelName: connector.config.tunnelName,
146 });
147 yield* reconcileConfig(desiredConfig);
148 }),
149 );
150 }).pipe(
151 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
152 );
153
154 const observeConnectorOutput = (connector: ActiveConnector) =>
155 connector.child.all.pipe(
156 Stream.decodeText(),
157 Stream.splitLines,
158 Stream.map((line) => line.trim()),
159 Stream.filter((line) => line.length > 0),
160 Stream.runForEach((line) => {
161 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
162 const attributes = {
163 pid: Number(connector.child.pid),
164 tunnelId: connector.config.tunnelId,
165 tunnelName: connector.config.tunnelName,
166 output,
167 };
168 switch (classifyRelayClientOutput(line)) {
169 case "connected":
170 return Effect.logInfo("Relay client tunnel connection registered", attributes);
171 case "warning":
172 return Effect.logWarning("Relay client reported a transport warning", attributes);
173 case "debug":
174 return Effect.logDebug("Relay client output", attributes);
175 }
176 }),
177 Effect.catchCause((cause) =>
178 Effect.logWarning("Relay client output observer failed", {
179 cause,
180 pid: Number(connector.child.pid),
181 tunnelId: connector.config.tunnelId,
182 tunnelName: connector.config.tunnelName,
183 }),
184 ),
185 );
186
187 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
188 if (!config || config.providerKind !== "cloudflare_tunnel") {
189 yield* stopActive;
190 return config
191 ? { status: "unsupported", providerKind: config.providerKind }
192 : { status: "disabled" };
193 }
194
195 const nextConfigKey = runtimeConfigKey(config);
196 const active = yield* Ref.get(activeRef);
197 if (active?.configKey === nextConfigKey) {
198 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
199 if (isRunning) {
200 return {
201 status: "running",
202 providerKind: "cloudflare_tunnel",
203 pid: Number(active.child.pid),
204 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
205 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
206 } satisfies CloudManagedEndpointRuntimeStatus;
207 }
208 }
209
210 yield* stopActive;
211
212 const executable = yield* relayClient.resolve;
213 if (executable.status !== "available") {
214 return {
215 status: "failed",
216 providerKind: "cloudflare_tunnel",
217 reason:
218 executable.status === "unsupported"
219 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
220 : "The relay client is not installed.",
221 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
222 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
223 } satisfies CloudManagedEndpointRuntimeStatus;
224 }
225
226 const connectorScope = yield* Scope.make("sequential");
227 const child = yield* spawner
228 .spawn(
229 ChildProcess.make(executable.executablePath, ["tunnel", "run"], {
230 detached: false,
231 env: {
232 ...process.env,
233 TUNNEL_TOKEN: config.connectorToken,
234 },
235 shell: false,
236 stderr: "pipe",
237 stdout: "pipe",
238 }),
239 )
240 .pipe(
241 Effect.provideService(Scope.Scope, connectorScope),
242 Effect.tap((child) =>
243 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
244 pid: Number(child.pid),
245 tunnelId: config.tunnelId,
246 tunnelName: config.tunnelName,
247 }),
248 ),
249 Effect.catch((cause) =>
250 Effect.logWarning("Failed to start relay client", {
251 cause,
252 tunnelId: config.tunnelId,
253 tunnelName: config.tunnelName,
254 }).pipe(
255 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
256 Effect.as({
257 status: "failed",
258 providerKind: "cloudflare_tunnel",
259 reason: String(cause),
260 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
261 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
262 } satisfies CloudManagedEndpointRuntimeStatus),
263 ),
264 ),
265 );
266
267 if ("status" in child && child.status === "failed") {
268 return child;
269 }
270
271 if (!("status" in child)) {
272 const connector = {
273 child,
274 scope: connectorScope,
275 configKey: nextConfigKey,
276 config,
277 } satisfies ActiveConnector;
278 yield* Ref.set(activeRef, connector);
279 yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
280 yield* Effect.forkIn(superviseConnector(connector), connectorScope);
281 return {
282 status: "running",
283 providerKind: "cloudflare_tunnel",
284 pid: Number(child.pid),
285 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
286 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
287 } satisfies CloudManagedEndpointRuntimeStatus;
288 }
289
290 return {
291 status: "failed",
292 providerKind: "cloudflare_tunnel",
293 reason: "Relay client did not start.",
294 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
295 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
296 } satisfies CloudManagedEndpointRuntimeStatus;
297 });
298
299 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
300 (config: RelayManagedEndpointRuntimeConfig | null) =>
301 reconcileSemaphore.withPermits(1)(
302 Ref.set(desiredConfigRef, config).pipe(Effect.andThen(reconcileConfig(config))),
303 ),
304 );
305
306 const runtime = CloudManagedEndpointRuntime.of({
307 applyConfig,
308 });
309
310 const initialConfig = yield* readRuntimeConfig.pipe(
311 Effect.catch((cause) =>
312 Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(
313 Effect.as(null),
314 ),
315 ),
316 );
317 yield* runtime.applyConfig(initialConfig);
318 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
319 return runtime;
320});
321
322export const layer = Layer.effect(CloudManagedEndpointRuntime, make);