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

ManagedEndpointRuntime.ts

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