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