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

ManagedEndpointRuntime.ts

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