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

ManagedEndpointRuntime.ts

374 lines13.7 KB

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);
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;
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";
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 });
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​
114/** @public Service construction is part of the canonical Effect module API. */
115export const make = Effect.gen(function* () {
116 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
117 const relayClient = yield* RelayClient.RelayClient;
118 const activeRef = yield* Ref.make<ActiveConnector | null>(null);
119 const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
120 const reconcileSemaphore = yield* Semaphore.make(1);
121 const restartDelayRef = yield* Ref.make(0);
122 let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
123​
124 const stopActive = Effect.gen(function* () {
125 const active = yield* Ref.getAndSet(activeRef, null);
126 yield* stopConnector(active);
127 });
128​
129 const superviseConnector = (connector: ActiveConnector) =>
130 Effect.gen(function* () {
131 const result = yield* Effect.result(connector.child.exitCode);
132 const activeAtExit = yield* Ref.get(activeRef);
133 if (
134 activeAtExit?.child.pid !== connector.child.pid ||
135 activeAtExit.configKey !== connector.configKey
136 ) {
137 return;
138 }
139 const uptimeMillis = (yield* Clock.currentTimeMillis) - connector.startedAtMillis;
140 // The first crash restarts immediately; every further crash inside the
141 // stable-uptime window doubles the wait, up to the cap. The delay runs
142 // before the semaphore so a user config change is never blocked behind
143 // it, and reconcileConfig re-checks the desired config afterwards.
144 const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
145 if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
146 return [0, 0];
147 }
148 return [
149 current,
150 current === 0
151 ? RELAY_RESTART_BACKOFF_BASE_MS
152 : Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
153 ];
154 });
155 if (restartDelayMillis > 0) {
156 yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
157 pid: Number(connector.child.pid),
158 uptimeMillis,
159 restartDelayMillis,
160 tunnelId: connector.config.tunnelId,
161 tunnelName: connector.config.tunnelName,
162 });
163 yield* Effect.sleep(Duration.millis(restartDelayMillis));
164 }
165 yield* reconcileSemaphore.withPermits(1)(
166 Effect.gen(function* () {
167 const active = yield* Ref.get(activeRef);
168 if (
169 active?.child.pid !== connector.child.pid ||
170 active.configKey !== connector.configKey
171 ) {
172 return;
173 }
174 yield* Ref.set(activeRef, null);
175 yield* stopConnector(connector);
176​
177 const desiredConfig = yield* Ref.get(desiredConfigRef);
178 if (
179 !desiredConfig ||
180 desiredConfig.providerKind !== "cloudflare_tunnel" ||
181 runtimeConfigKey(desiredConfig) !== connector.configKey
182 ) {
183 return;
184 }
185​
186 yield* Effect.logWarning("Relay client exited; restarting", {
187 pid: Number(connector.child.pid),
188 ...(Result.isSuccess(result)
189 ? { exitCode: Number(result.success) }
190 : { cause: result.failure }),
191 tunnelId: connector.config.tunnelId,
192 tunnelName: connector.config.tunnelName,
193 });
194 yield* reconcileConfig(desiredConfig);
195 }),
196 );
197 }).pipe(
198 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
199 );
200​
201 const observeConnectorOutput = (connector: ActiveConnector) =>
202 connector.child.all.pipe(
203 Stream.decodeText(),
204 Stream.splitLines,
205 Stream.map((line) => line.trim()),
206 Stream.filter((line) => line.length > 0),
207 Stream.runForEach((line) => {
208 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
209 const attributes = {
210 pid: Number(connector.child.pid),
211 tunnelId: connector.config.tunnelId,
212 tunnelName: connector.config.tunnelName,
213 output,
214 };
215 switch (classifyRelayClientOutput(line)) {
216 case "connected":
217 return Effect.logInfo("Relay client tunnel connection registered", attributes);
218 case "warning":
219 return Effect.logWarning("Relay client reported a transport warning", attributes);
220 case "debug":
221 return Effect.logDebug("Relay client output", attributes);
222 }
223 }),
224 Effect.catchCause((cause) =>
225 Effect.logWarning("Relay client output observer failed", {
226 cause,
227 pid: Number(connector.child.pid),
228 tunnelId: connector.config.tunnelId,
229 tunnelName: connector.config.tunnelName,
230 }),
231 ),
232 );
233​
234 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
235 if (!config || config.providerKind !== "cloudflare_tunnel") {
236 yield* stopActive;
237 return config
238 ? { status: "unsupported", providerKind: config.providerKind }
239 : { status: "disabled" };
240 }
241​
242 const nextConfigKey = runtimeConfigKey(config);
243 const active = yield* Ref.get(activeRef);
244 if (active?.configKey === nextConfigKey) {
245 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
246 if (isRunning) {
247 return {
248 status: "running",
249 providerKind: "cloudflare_tunnel",
250 pid: Number(active.child.pid),
251 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
252 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
253 } satisfies CloudManagedEndpointRuntimeStatus;
254 }
255 }
256​
257 yield* stopActive;
258​
259 const executable = yield* relayClient.resolve;
260 if (executable.status !== "available") {
261 return {
262 status: "failed",
263 providerKind: "cloudflare_tunnel",
264 reason:
265 executable.status === "unsupported"
266 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
267 : "The relay client is not installed.",
268 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
269 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
270 } satisfies CloudManagedEndpointRuntimeStatus;
271 }
272​
273 const connectorScope = yield* Scope.make("sequential");
274 const child = yield* spawner
275 .spawn(
276 ChildProcess.make(executable.executablePath, ["tunnel", "run"], {
277 detached: false,
278 env: {
279 ...process.env,
280 TUNNEL_TOKEN: config.connectorToken,
281 },
282 shell: false,
283 stderr: "pipe",
284 stdout: "pipe",
285 }),
286 )
287 .pipe(
288 Effect.provideService(Scope.Scope, connectorScope),
289 Effect.tap((child) =>
290 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
291 pid: Number(child.pid),
292 tunnelId: config.tunnelId,
293 tunnelName: config.tunnelName,
294 }),
295 ),
296 Effect.catch((cause) =>
297 Effect.logWarning("Failed to start relay client", {
298 cause,
299 tunnelId: config.tunnelId,
300 tunnelName: config.tunnelName,
301 }).pipe(
302 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
303 Effect.as({
304 status: "failed",
305 providerKind: "cloudflare_tunnel",
306 reason: String(cause),
307 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
308 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
309 } satisfies CloudManagedEndpointRuntimeStatus),
310 ),
311 ),
312 );
313​
314 if ("status" in child && child.status === "failed") {
315 return child;
316 }
317​
318 if (!("status" in child)) {
319 const connector = {
320 child,
321 scope: connectorScope,
322 configKey: nextConfigKey,
323 config,
324 startedAtMillis: yield* Clock.currentTimeMillis,
325 } satisfies ActiveConnector;
326 yield* Ref.set(activeRef, connector);
327 yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
328 yield* Effect.forkIn(superviseConnector(connector), connectorScope);
329 return {
330 status: "running",
331 providerKind: "cloudflare_tunnel",
332 pid: Number(child.pid),
333 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
334 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
335 } satisfies CloudManagedEndpointRuntimeStatus;
336 }
337​
338 return {
339 status: "failed",
340 providerKind: "cloudflare_tunnel",
341 reason: "Relay client did not start.",
342 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
343 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
344 } satisfies CloudManagedEndpointRuntimeStatus;
345 });
346​
347 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
348 (config: RelayManagedEndpointRuntimeConfig | null) =>
349 reconcileSemaphore.withPermits(1)(
350 // An explicit config change starts over with a fresh backoff.
351 Ref.set(restartDelayRef, 0).pipe(
352 Effect.andThen(Ref.set(desiredConfigRef, config)),
353 Effect.andThen(reconcileConfig(config)),
354 ),
355 ),
356 );
357​
358 const runtime = CloudManagedEndpointRuntime.of({
359 applyConfig,
360 });
361​
362 const initialConfig = yield* readRuntimeConfig.pipe(
363 Effect.catch((cause) =>
364 Effect.logWarning("Failed to read managed endpoint runtime config", { cause }).pipe(
365 Effect.as(null),
366 ),
367 ),
368 );
369 yield* runtime.applyConfig(initialConfig);
370 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
371 return runtime;
372});
373​
374export const layer = Layer.effect(CloudManagedEndpointRuntime, make);