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

ManagedEndpointRuntime.ts

422 lines16.2 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 Queue from "effect/Queue";
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​
18export type CloudManagedEndpointRuntimeStatus =
19 | {
20 readonly status: "disabled";
21 }
22 | {
23 readonly status: "failed";
24 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
25 readonly failure: "unsupported-platform" | "not-installed" | "spawn-failed";
26 readonly reason: string;
27 readonly tunnelId?: string;
28 readonly tunnelName?: string;
29 }
30 | {
31 readonly status: "running";
32 readonly providerKind: "cloudflare_tunnel";
33 readonly pid: number;
34 readonly tunnelId?: string;
35 readonly tunnelName?: string;
36 }
37 | {
38 readonly status: "unsupported";
39 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
40 };
41​
42export class CloudManagedEndpointRuntime extends Context.Service<
43 CloudManagedEndpointRuntime,
44 {
45 readonly applyConfig: (
46 config: RelayManagedEndpointRuntimeConfig | null,
47 ) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
48 readonly recoveryRequests: Stream.Stream<RelayManagedEndpointRuntimeConfig>;
49 readonly requestRecovery: (config: RelayManagedEndpointRuntimeConfig) => Effect.Effect<void>;
50 readonly withLinkStateLock: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
51 }
52>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
53​
54interface ActiveConnector {
55 readonly child: ChildProcessSpawner.ChildProcessHandle;
56 readonly scope: Scope.Closeable;
57 readonly configKey: string;
58 readonly config: RelayManagedEndpointRuntimeConfig;
59 readonly startedAtMillis: number;
61​
62// A connector that exits before running this long is treated as part of a
63// crash loop; one that stays up at least this long earns an immediate restart
64// again. Without the backoff below, a relay client that fails instantly (a
65// stale version-manager shim, a bad binary) respawns ~100 times per second
66// until the accumulated tracing exhausts the V8 heap.
67const RELAY_RESTART_STABLE_UPTIME_MS = 30_000;
68const RELAY_RESTART_BACKOFF_BASE_MS = 1_000;
69const RELAY_RESTART_BACKOFF_MAX_MS = 60_000;
70// Newly created tunnels can fail authorization briefly while Cloudflare propagates their token.
71const TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY = 4;
72​
73export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
74 if (/\bRegistered tunnel connection\b/iu.test(line)) {
75 return "connected";
76 }
77 // cloudflared uses zerolog level tokens. FTL (fatal) and PNC (panic) are more
78 // severe than ERR, so they must surface at least as loudly — without them a
79 // fatal connector failure would be logged at debug and hidden.
80 return /\b(?:ERR|WRN|FTL|PNC)\b/u.test(line) ? "warning" : "debug";
82​
83/**
84 * Cloudflare's edge rejects a connector whose tunnel was deleted or whose
85 * token no longer matches. Current edge output is
86 * `error="Failed to get tunnel"` with no prefix; older edges prefixed the
87 * same messages with `Unauthorized:`. Match both so recovery fires on either.
88 */
89export function isRejectedRelayClientTunnelOutput(line: string): boolean {
90 return (
91 /\bRegister tunnel error from server side\b/iu.test(line) &&
92 /error="(?:Unauthorized:\s*)?(?:Failed to get tunnel|Record for tunnel not found|Invalid tunnel secret)"/iu.test(
93 line,
94 )
95 );
97​
98/** Connector startup failures can clear after installation or a later spawn attempt. */
99export function isRetryableManagedEndpointRuntimeStatus(status: unknown): boolean {
100 if (typeof status !== "object" || status === null || !("status" in status)) {
101 return false;
102 }
103 if (status.status !== "failed" || !("failure" in status)) {
104 return false;
105 }
106 return status.failure === "not-installed" || status.failure === "spawn-failed";
108​
109function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
110 return JSON.stringify({
111 providerKind: config.providerKind,
112 connectorToken: config.connectorToken,
113 tunnelId: config.tunnelId ?? null,
114 tunnelName: config.tunnelName ?? null,
115 });
117​
118const stopConnector = (connector: ActiveConnector | null) =>
119 connector
120 ? Scope.close(connector.scope, Exit.void).pipe(
121 Effect.tap(() =>
122 Effect.logInfo("Relay client stopped", {
123 pid: Number(connector.child.pid),
124 }),
125 ),
126 Effect.ignore,
127 )
128 : Effect.void;
129​
130/** @public Service construction is part of the canonical Effect module API. */
131export const make = Effect.gen(function* () {
132 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
133 const relayClient = yield* RelayClient.RelayClient;
134 const activeRef = yield* Ref.make<ActiveConnector | null>(null);
135 const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
136 const recoveryRequests = yield* Queue.sliding<RelayManagedEndpointRuntimeConfig>(1);
137 const reconcileSemaphore = yield* Semaphore.make(1);
138 const restartDelayRef = yield* Ref.make(0);
139 const linkStateSemaphore = yield* Semaphore.make(1);
140 let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
141​
142 const stopActive = Effect.gen(function* () {
143 const active = yield* Ref.getAndSet(activeRef, null);
144 yield* stopConnector(active);
145 });
146​
147 const superviseConnector = (connector: ActiveConnector) =>
148 Effect.gen(function* () {
149 const result = yield* Effect.result(connector.child.exitCode);
150 const activeAtExit = yield* Ref.get(activeRef);
151 if (
152 activeAtExit?.child.pid !== connector.child.pid ||
153 activeAtExit.configKey !== connector.configKey
154 ) {
155 return;
156 }
157 const uptimeMillis = (yield* Clock.currentTimeMillis) - connector.startedAtMillis;
158 // The first crash restarts immediately; every further crash inside the
159 // stable-uptime window doubles the wait, up to the cap. The delay runs
160 // before the semaphore so a user config change is never blocked behind
161 // it, and reconcileConfig re-checks the desired config afterwards.
162 const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
163 if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
164 return [0, 0];
165 }
166 return [
167 current,
168 current === 0
169 ? RELAY_RESTART_BACKOFF_BASE_MS
170 : Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
171 ];
172 });
173 if (restartDelayMillis > 0) {
174 yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
175 pid: Number(connector.child.pid),
176 uptimeMillis,
177 restartDelayMillis,
178 tunnelId: connector.config.tunnelId,
179 tunnelName: connector.config.tunnelName,
180 });
181 yield* Effect.sleep(Duration.millis(restartDelayMillis));
182 }
183 yield* reconcileSemaphore.withPermits(1)(
184 Effect.gen(function* () {
185 const active = yield* Ref.get(activeRef);
186 if (
187 active?.child.pid !== connector.child.pid ||
188 active.configKey !== connector.configKey
189 ) {
190 return;
191 }
192 yield* Ref.set(activeRef, null);
193 yield* stopConnector(connector);
194​
195 const desiredConfig = yield* Ref.get(desiredConfigRef);
196 if (
197 !desiredConfig ||
198 desiredConfig.providerKind !== "cloudflare_tunnel" ||
199 runtimeConfigKey(desiredConfig) !== connector.configKey
200 ) {
201 return;
202 }
203​
204 yield* Effect.logWarning("Relay client exited; restarting", {
205 pid: Number(connector.child.pid),
206 ...(Result.isSuccess(result)
207 ? { exitCode: Number(result.success) }
208 : { cause: result.failure }),
209 tunnelId: connector.config.tunnelId,
210 tunnelName: connector.config.tunnelName,
211 });
212 yield* Queue.offer(recoveryRequests, connector.config);
213 yield* reconcileConfig(desiredConfig);
214 }),
215 );
216 }).pipe(
217 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
218 );
219​
220 const observeConnectorOutput = (connector: ActiveConnector) => {
221 let rejectedRegistrations = 0;
222​
223 return connector.child.all.pipe(
224 Stream.decodeText(),
225 Stream.splitLines,
226 Stream.map((line) => line.trim()),
227 Stream.filter((line) => line.length > 0),
228 Stream.runForEach((line) => {
229 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
230 const attributes = {
231 pid: Number(connector.child.pid),
232 tunnelId: connector.config.tunnelId,
233 tunnelName: connector.config.tunnelName,
234 output,
235 };
236 switch (classifyRelayClientOutput(line)) {
237 case "connected":
238 rejectedRegistrations = 0;
239 return Effect.logInfo("Relay client tunnel connection registered", attributes);
240 case "warning":
241 if (isRejectedRelayClientTunnelOutput(line)) {
242 rejectedRegistrations += 1;
243 if (rejectedRegistrations >= TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY) {
244 rejectedRegistrations = 0;
245 return Effect.logWarning(
246 "Relay client tunnel was rejected; requesting recovery",
247 attributes,
248 ).pipe(
249 Effect.andThen(Queue.offer(recoveryRequests, connector.config)),
250 Effect.asVoid,
251 );
252 }
253 }
254 return Effect.logWarning("Relay client reported a transport warning", attributes);
255 case "debug":
256 return Effect.logDebug("Relay client output", attributes);
257 }
258 }),
259 Effect.catchCause((cause) =>
260 Effect.logWarning("Relay client output observer failed", {
261 cause,
262 pid: Number(connector.child.pid),
263 tunnelId: connector.config.tunnelId,
264 tunnelName: connector.config.tunnelName,
265 }),
266 ),
267 );
268 };
269​
270 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
271 if (!config || config.providerKind !== "cloudflare_tunnel") {
272 yield* stopActive;
273 return config
274 ? { status: "unsupported", providerKind: config.providerKind }
275 : { status: "disabled" };
276 }
277​
278 const nextConfigKey = runtimeConfigKey(config);
279 const active = yield* Ref.get(activeRef);
280 if (active?.configKey === nextConfigKey) {
281 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
282 if (isRunning) {
283 return {
284 status: "running",
285 providerKind: "cloudflare_tunnel",
286 pid: Number(active.child.pid),
287 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
288 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
289 } satisfies CloudManagedEndpointRuntimeStatus;
290 }
291 }
292​
293 yield* stopActive;
294​
295 const executable = yield* relayClient.resolve;
296 if (executable.status !== "available") {
297 return {
298 status: "failed",
299 providerKind: "cloudflare_tunnel",
300 failure: executable.status === "unsupported" ? "unsupported-platform" : "not-installed",
301 reason:
302 executable.status === "unsupported"
303 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
304 : "The relay client is not installed.",
305 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
306 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
307 } satisfies CloudManagedEndpointRuntimeStatus;
308 }
309​
310 const connectorScope = yield* Scope.make("sequential");
311 const child = yield* spawner
312 .spawn(
313 ChildProcess.make(
314 executable.executablePath,
315 ["tunnel", "--no-autoupdate", "--loglevel", "info", "--output", "default", "run"],
316 {
317 detached: false,
318 env: {
319 ...process.env,
320 TUNNEL_TOKEN: config.connectorToken,
321 },
322 shell: false,
323 stderr: "pipe",
324 stdout: "pipe",
325 },
326 ),
327 )
328 .pipe(
329 Effect.provideService(Scope.Scope, connectorScope),
330 Effect.tap((child) =>
331 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
332 pid: Number(child.pid),
333 tunnelId: config.tunnelId,
334 tunnelName: config.tunnelName,
335 }),
336 ),
337 Effect.catch((cause) =>
338 Effect.logWarning("Failed to start relay client", {
339 cause,
340 tunnelId: config.tunnelId,
341 tunnelName: config.tunnelName,
342 }).pipe(
343 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
344 Effect.as({
345 status: "failed",
346 providerKind: "cloudflare_tunnel",
347 failure: "spawn-failed",
348 reason: String(cause),
349 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
350 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
351 } satisfies CloudManagedEndpointRuntimeStatus),
352 ),
353 ),
354 );
355​
356 if ("status" in child && child.status === "failed") {
357 return child;
358 }
359​
360 if (!("status" in child)) {
361 const connector = {
362 child,
363 scope: connectorScope,
364 configKey: nextConfigKey,
365 config,
366 startedAtMillis: yield* Clock.currentTimeMillis,
367 } satisfies ActiveConnector;
368 yield* Ref.set(activeRef, connector);
369 yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
370 yield* Effect.forkIn(superviseConnector(connector), connectorScope);
371 return {
372 status: "running",
373 providerKind: "cloudflare_tunnel",
374 pid: Number(child.pid),
375 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
376 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
377 } satisfies CloudManagedEndpointRuntimeStatus;
378 }
379​
380 return {
381 status: "failed",
382 providerKind: "cloudflare_tunnel",
383 failure: "spawn-failed",
384 reason: "Relay client did not start.",
385 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
386 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
387 } satisfies CloudManagedEndpointRuntimeStatus;
388 });
389​
390 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
391 (config: RelayManagedEndpointRuntimeConfig | null) =>
392 reconcileSemaphore.withPermits(1)(
393 Effect.gen(function* () {
394 // A real config change starts over with a fresh backoff. Recovery
395 // that hands back the same tunnel and token must keep the delay, or
396 // a crash-looping connector respawns on every recovery round trip.
397 const desired = yield* Ref.get(desiredConfigRef);
398 const unchanged =
399 desired !== null &&
400 config !== null &&
401 runtimeConfigKey(desired) === runtimeConfigKey(config);
402 if (!unchanged) {
403 yield* Ref.set(restartDelayRef, 0);
404 }
405 yield* Ref.set(desiredConfigRef, config);
406 return yield* reconcileConfig(config);
407 }),
408 ),
409 );
410​
411 const runtime = CloudManagedEndpointRuntime.of({
412 applyConfig,
413 recoveryRequests: Stream.fromQueue(recoveryRequests),
414 requestRecovery: (config) => Queue.offer(recoveryRequests, config).pipe(Effect.asVoid),
415 withLinkStateLock: linkStateSemaphore.withPermits(1),
416 });
417​
418 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
419 return runtime;
420});
421​
422export const layer = Layer.effect(CloudManagedEndpointRuntime, make);