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

ManagedEndpointRuntime.ts

962 lines38.9 KB

1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import { RotatingFileSink, RotatingFileSinkError } from "@t3tools/shared/logging";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as RelayClient from "@t3tools/shared/relayClient";
5import * as Clock from "effect/Clock";
6import * as Config from "effect/Config";
7import * as Context from "effect/Context";
8import * as Deferred from "effect/Deferred";
9import * as Duration from "effect/Duration";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Layer from "effect/Layer";
13import * as Logger from "effect/Logger";
14import * as Option from "effect/Option";
15import * as Path from "effect/Path";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Result from "effect/Result";
19import * as Schema from "effect/Schema";
20import * as Semaphore from "effect/Semaphore";
21import * as Scope from "effect/Scope";
22import * as Stream from "effect/Stream";
23import { HttpClient, HttpClientResponse } from "effect/http";
24import * as ChildProcess from "effect/process/ChildProcess";
25import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
26​
27import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
28import * as ServerConfig from "../config.ts";
29import * as ManagedLimits from "../policy/managedLimits.ts";
30import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
31import * as RelayClientLedger from "./RelayClientLedger.ts";
32​
33export type CloudManagedEndpointRuntimeStatus =
34 | {
35 readonly status: "disabled";
36 }
37 | {
38 readonly status: "failed";
39 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
40 readonly failure: "unsupported-platform" | "not-installed" | "spawn-failed";
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​
57/** What the running cloudflared reports about itself. `null` fields are not known yet. */
58export interface ConnectorFacts {
59 readonly pid: number;
60 readonly readyConnections: number | null;
61 /** The public tunnel hostname from the remote config cloudflared receives once it connects. */
62 readonly hostname: string | null;
63 readonly protocol: string | null;
65​
66export class CloudManagedEndpointRuntime extends Context.Service<
67 CloudManagedEndpointRuntime,
68 {
69 readonly applyConfig: (
70 config: RelayManagedEndpointRuntimeConfig | null,
71 ) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
72 /** `null` when no connector is running. */
73 readonly inspectConnector: Effect.Effect<ConnectorFacts | null>;
74 /** Emits when a connector registers a connection or its readiness changes. */
75 readonly readinessChanged: Stream.Stream<void>;
76 readonly recoveryRequests: Stream.Stream<RelayManagedEndpointRuntimeConfig>;
77 readonly requestRecovery: (config: RelayManagedEndpointRuntimeConfig) => Effect.Effect<void>;
78 /**
79 * Restarts the connector if it still runs as `pid` and `stillDead` holds once it has
80 * the lock. Returns whether it sent the restart.
81 */
82 readonly restartConnector: (
83 pid: number,
84 stillDead: Effect.Effect<boolean>,
85 ) => Effect.Effect<boolean>;
86 readonly tunnelConnected: Stream.Stream<void>;
87 readonly withLinkStateLock: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
88 }
89>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
90​
91interface ActiveConnector {
92 readonly child: ChildProcessSpawner.ChildProcessHandle;
93 readonly executable: RelayClient.AvailableRelayClient;
94 readonly scope: Scope.Closeable;
95 readonly configKey: string;
96 readonly config: RelayManagedEndpointRuntimeConfig;
97 readonly startedAtMillis: number;
98 readonly registered: Deferred.Deferred<void>;
99 readonly metricsAddress: Deferred.Deferred<string>;
100 readonly protocol: Ref.Ref<string | null>;
102​
103// An instantly failing relay client otherwise respawns ~100 times/sec and exhausts V8 via tracing.
104const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
105​
106const RELAY_RESTART_STABLE_UPTIME_MS = 30_000;
107const RELAY_RESTART_BACKOFF_BASE_MS = 1_000;
108const RELAY_RESTART_BACKOFF_MAX_MS = 60_000;
109// Newly created tunnels can fail authorization briefly while Cloudflare propagates their token.
110const TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY = 4;
111// Unknown rejection wording can leave a dead tunnel unconnected; periodically request recovery.
112const CONNECTOR_REGISTRATION_TIMEOUT = Duration.minutes(3);
113// cloudflared resolves edges only at startup and can keep dialing stale addresses after a network change.
114const CONNECTOR_READINESS_INTERVAL = Duration.seconds(30);
115const CONNECTOR_READINESS_REQUEST_TIMEOUT = Duration.seconds(5);
116const CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART = 6;
117const CONNECTOR_NOT_READY_CHECKS_MAX = 60;
118const RELAY_CLIENT_METRICS_LINE = /\bStarting metrics server on (127\.0\.0\.1:\d+)\/metrics\b/u;
119const RELAY_CLIENT_PROTOCOL = /\bprotocol=(\w+)/u;
120// cloudflared's metrics server: `/ready` answers 200 or 503 with this body, and
121// `/config` holds the ingress rules the edge pushed after the first connection.
122const ConnectorReadyBody = Schema.Struct({ readyConnections: Schema.Number });
123const ConnectorConfigBody = Schema.Struct({
124 config: Schema.Struct({
125 ingress: Schema.optional(
126 Schema.NullOr(Schema.Array(Schema.Struct({ hostname: Schema.optional(Schema.String) }))),
127 ),
128 }),
129});
130// Registration resets cloudflared's own fallback, even when QUIC stalls again
131// immediately. Keep that evidence across registrations and connector restarts.
132const QUIC_STALLS_BEFORE_HTTP2 = 30;
133const QUIC_STALL_WINDOW_MS = 5 * 60_000;
134// Retry QUIC on a later startup after transient failures or network changes; reuse never renews this hint.
135const HTTP2_FALLBACK_TTL_MS = 24 * 60 * 60_000;
136const HTTP2_FALLBACK_STATE = "cloud-endpoint-http2-fallback";
137const Http2Fallback = Schema.fromJsonString(Schema.Struct({ fellBackAt: Schema.Number }));
138const decodeHttp2Fallback = Schema.decodeUnknownOption(Http2Fallback);
139const encodeHttp2Fallback = Schema.encodeSync(Http2Fallback);
140// A failed background install of the pinned relay client is retried no sooner
141// than this, so a crash-looping connector or an offline host does not redownload
142// on every reconcile.
143const RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS = 10 * 60_000;
144export const RELAY_CLIENT_LOG_FILE = "relay-client.ndjson";
145​
146/** Preserve user-chosen PATH binaries and overrides; CLI downloads require consent. */
147function needsPinnedRelayClient(executable: RelayClient.RelayClientStatus): boolean {
148 return (
149 executable.status === "missing" ||
150 (executable.status === "available" &&
151 executable.source === "managed" &&
152 !RelayClient.isPinnedManagedRelayClient(executable))
153 );
155​
156export function classifyRelayClientOutput(
157 line: string,
158): "connected" | "unregistered" | "warning" | "debug" {
159 if (/\bRegistered tunnel connection\b/iu.test(line)) {
160 return "connected";
161 }
162 // cloudflared uses zerolog FTL/PNC for fatal/panic; classify them above debug too.
163 if (/\b(?:ERR|WRN|FTL|PNC)\b/u.test(line)) {
164 return "warning";
165 }
166 return /\bINF\b.*\bUnregistered tunnel connection\b/u.test(line) ? "unregistered" : "debug";
168​
169/** Edge rejection wording varies; any Unauthorized registration error counts. */
170export function isRejectedRelayClientTunnelOutput(line: string): boolean {
171 return (
172 /\bRegister tunnel error from server side\b/iu.test(line) &&
173 /error="(?:Unauthorized:[^"]*|Failed to get tunnel|Tunnel not found|Record for tunnel not found|Invalid tunnel secret)"/iu.test(
174 line,
175 )
176 );
178​
179export function isRetryableManagedEndpointRuntimeStatus(status: unknown): boolean {
180 if (typeof status !== "object" || status === null || !("status" in status)) {
181 return false;
182 }
183 if (status.status !== "failed" || !("failure" in status)) {
184 return false;
185 }
186 return status.failure === "not-installed" || status.failure === "spawn-failed";
188​
189function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
190 return JSON.stringify({
191 providerKind: config.providerKind,
192 connectorToken: config.connectorToken,
193 tunnelId: config.tunnelId ?? null,
194 tunnelName: config.tunnelName ?? null,
195 });
197​
198const stopConnector = (connector: ActiveConnector | null) =>
199 connector
200 ? Scope.close(connector.scope, Exit.void).pipe(
201 Effect.tap(() =>
202 Effect.logInfo("Relay client stopped", {
203 pid: Number(connector.child.pid),
204 }),
205 ),
206 Effect.ignore,
207 )
208 : Effect.void;
209​
210/** @public */
211export const make = Effect.gen(function* () {
212 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
213 const relayClient = yield* RelayClient.RelayClient;
214 const relayClientLedger = yield* RelayClientLedger.RelayClientLedger;
215 const secrets = yield* ServerSecretStore.ServerSecretStore;
216 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
217 // Without T3 Connect no connector ever runs, whoever asks for one.
218 const connectAllowed = ManagedLimits.allowsConnect(yield* ManagedPolicy.ManagedPolicy);
219 const activeRef = yield* Ref.make<ActiveConnector | null>(null);
220 const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
221 const recoveryRequests = yield* Queue.sliding<RelayManagedEndpointRuntimeConfig>(1);
222 const tunnelConnections = yield* Queue.sliding<void>(1);
223 const readinessChanges = yield* Queue.sliding<void>(1);
224 const reconcileSemaphore = yield* Semaphore.make(1);
225 const restartDelayRef = yield* Ref.make(0);
226 const linkStateSemaphore = yield* Semaphore.make(1);
227 const runtimeScope = yield* Effect.scope;
228 const installInFlightRef = yield* Ref.make(false);
229 const lastInstallFailureAtRef = yield* Ref.make<number | null>(null);
230 const prunedRef = yield* Ref.make(false);
231 const retryLoopRunningRef = yield* Ref.make(false);
232 const notReadyChecksBeforeRestartRef = yield* Ref.make(CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
233 // The relay client shares the server's process group, so it exits on these signals before the finalizer runs.
234 let shutdownSignalReceived = false;
235 const onShutdownSignal = () => {
236 shutdownSignalReceived = true;
237 };
238 yield* Effect.acquireRelease(
239 Effect.sync(() => {
240 process.on("SIGINT", onShutdownSignal);
241 process.on("SIGTERM", onShutdownSignal);
242 }),
243 () =>
244 Effect.sync(() => {
245 process.off("SIGINT", onShutdownSignal);
246 process.off("SIGTERM", onShutdownSignal);
247 }),
248 );
249 // An explicit cloudflared transport in the environment is the user's choice.
250 const env = yield* HostProcess.Environment;
251 const transportChosenByUser = Option.isSome(
252 yield* Config.String("TUNNEL_TRANSPORT_PROTOCOL").pipe(Config.option),
253 );
254 const previousFallback = transportChosenByUser
255 ? Option.none()
256 : yield* secrets.get(HTTP2_FALLBACK_STATE).pipe(
257 Effect.map(Option.flatMap((bytes) => decodeHttp2Fallback(new TextDecoder().decode(bytes)))),
258 Effect.orElseSucceed(() => Option.none()),
259 );
260 const now = yield* Clock.currentTimeMillis;
261 const http2Ref = yield* Ref.make(
262 Option.isSome(previousFallback) &&
263 now >= previousFallback.value.fellBackAt &&
264 now - previousFallback.value.fellBackAt < HTTP2_FALLBACK_TTL_MS,
265 );
266 const quicStallsRef = yield* Ref.make<ReadonlyArray<number>>([]);
267 let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
268​
269 const { logsDir } = yield* ServerConfig.ServerConfig;
270 const path = yield* Path.Path;
271 const relayClientLogPath = path.join(logsDir, RELAY_CLIENT_LOG_FILE);
272 // Synchronous appends avoid a flush timer for this low-volume log.
273 const fallbackLoggers = yield* Effect.service(Logger.CurrentLoggers);
274 let writeFailureReported = false;
275 const relayClientLog = yield* Effect.try({
276 try: () =>
277 new RotatingFileSink({
278 filePath: relayClientLogPath,
279 maxBytes: 1024 * 1024,
280 maxFiles: 2,
281 throwOnError: true,
282 }),
283 catch: (cause) =>
284 isRotatingFileSinkError(cause)
285 ? cause
286 : new RotatingFileSinkError({
287 operation: "initialize",
288 filePath: relayClientLogPath,
289 cause,
290 }),
291 }).pipe(
292 Effect.map((sink) =>
293 Logger.make((options) => {
294 try {
295 const entry = Logger.formatJson.log(options);
296 const bytes = Buffer.byteLength(entry) + 1;
297 sink.write(
298 bytes <= 1024 * 1024
299 ? `${entry}\n`
300 : `${JSON.stringify({
301 timestamp: options.date.toISOString(),
302 level: options.logLevel.toUpperCase(),
303 message: ["Relay client log entry omitted: exceeds 1 MiB", { bytes }],
304 })}\n`,
305 );
306 } catch {
307 if (!writeFailureReported) {
308 writeFailureReported = true;
309 for (const logger of fallbackLoggers) {
310 logger.log({
311 ...options,
312 logLevel: "Warn",
313 message: ["Relay client log unavailable", { filePath: relayClientLogPath }],
314 });
315 }
316 }
317 }
318 }),
319 ),
320 Effect.catch((error) =>
321 Effect.logWarning("Relay client log unavailable", {
322 filePath: relayClientLogPath,
323 cause: error,
324 }).pipe(Effect.as(undefined)),
325 ),
326 );
327 // Forked connector fibers inherit this logger after the applyConfig span ends.
328 const withRelayClientLog = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
329 relayClientLog ? Effect.withLogger(effect, relayClientLog) : effect;
330​
331 const stopActive = Effect.gen(function* () {
332 const active = yield* Ref.getAndSet(activeRef, null);
333 yield* stopConnector(active);
334 });
335​
336 // Lives until connector exit and starts replacements; avoid nested lifetime spans.
337 const superviseConnector = Effect.fnUntraced(
338 function* (connector: ActiveConnector) {
339 const result = yield* Effect.result(connector.child.exitCode);
340 const activeAtExit = yield* Ref.get(activeRef);
341 if (
342 activeAtExit?.child.pid !== connector.child.pid ||
343 activeAtExit.configKey !== connector.configKey
344 ) {
345 return;
346 }
347 const uptimeMillis = (yield* Clock.currentTimeMillis) - connector.startedAtMillis;
348 // Back off outside the semaphore so config changes remain responsive; recheck config afterwards.
349 const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
350 if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
351 return [0, 0];
352 }
353 return [
354 current,
355 current === 0
356 ? RELAY_RESTART_BACKOFF_BASE_MS
357 : Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
358 ];
359 });
360 if (restartDelayMillis > 0) {
361 yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
362 pid: Number(connector.child.pid),
363 uptimeMillis,
364 restartDelayMillis,
365 tunnelId: connector.config.tunnelId,
366 tunnelName: connector.config.tunnelName,
367 });
368 yield* Effect.sleep(Duration.millis(restartDelayMillis));
369 }
370 yield* reconcileSemaphore.withPermits(1)(
371 Effect.gen(function* () {
372 const active = yield* Ref.get(activeRef);
373 if (
374 active?.child.pid !== connector.child.pid ||
375 active.configKey !== connector.configKey
376 ) {
377 return;
378 }
379 yield* Ref.set(activeRef, null);
380 yield* stopConnector(connector);
381​
382 const desiredConfig = yield* Ref.get(desiredConfigRef);
383 if (
384 shutdownSignalReceived ||
385 !desiredConfig ||
386 desiredConfig.providerKind !== "cloudflare_tunnel" ||
387 runtimeConfigKey(desiredConfig) !== connector.configKey
388 ) {
389 return;
390 }
391​
392 yield* Effect.logWarning("Relay client exited; restarting", {
393 pid: Number(connector.child.pid),
394 ...(Result.isSuccess(result)
395 ? { exitCode: Number(result.success) }
396 : { cause: result.failure }),
397 tunnelId: connector.config.tunnelId,
398 tunnelName: connector.config.tunnelName,
399 });
400 yield* Queue.offer(recoveryRequests, connector.config);
401 yield* reconcileConfig(desiredConfig);
402 }),
403 );
404 },
405 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
406 );
407​
408 // Keep the old connector until its replacement registers, preserving the relay connection.
409 const installPinnedRelayClient = Effect.gen(function* () {
410 if (yield* Ref.getAndSet(installInFlightRef, true)) return;
411 yield* Effect.logInfo("Installing the pinned relay client", {
412 version: RelayClient.CLOUDFLARED_VERSION,
413 });
414 yield* relayClient.install.pipe(
415 Effect.tap(() => Ref.set(lastInstallFailureAtRef, null)),
416 Effect.flatMap((installed) =>
417 reconcileSemaphore.withPermits(1)(
418 Effect.gen(function* () {
419 const desiredConfig = yield* Ref.get(desiredConfigRef);
420 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
421 const active = yield* Ref.get(activeRef);
422 // Self-updated binaries share the pinned path; compare versions to detect replacements.
423 if (
424 active?.executable.executablePath === installed.executablePath &&
425 active.executable.version === installed.version
426 ) {
427 return;
428 }
429 // A scanner can block a fresh binary's probe; retry instead of restarting onto the older binary.
430 const resolved = yield* relayClient.resolve;
431 if (
432 resolved.status !== "available" ||
433 resolved.executablePath !== installed.executablePath ||
434 resolved.version !== installed.version
435 ) {
436 return;
437 }
438 yield* Effect.logInfo("Relay client installed; moving the connector to it", {
439 version: installed.version,
440 previousVersion: active?.executable.version,
441 });
442 const previous = yield* Ref.getAndSet(activeRef, null);
443 const status = yield* reconcileConfig(desiredConfig);
444 const next = yield* Ref.get(activeRef);
445 if (!next) {
446 yield* Effect.logWarning("Relay client did not start after the update", status);
447 // The supervisor skips exits while detached; request recovery explicitly.
448 const previousRunning = previous
449 ? yield* previous.child.isRunning.pipe(Effect.orElseSucceed(() => false))
450 : false;
451 if (previous && previousRunning) {
452 yield* Ref.set(activeRef, previous);
453 } else {
454 yield* stopConnector(previous);
455 yield* Queue.offer(recoveryRequests, desiredConfig);
456 }
457 return;
458 }
459 if (previous) {
460 yield* Deferred.await(next.registered).pipe(
461 Effect.ensuring(stopConnector(previous)),
462 Effect.forkIn(next.scope),
463 );
464 }
465 }),
466 ),
467 ),
468 Effect.catchTags({
469 RelayClientInstallError: (error) =>
470 Clock.currentTimeMillis.pipe(
471 Effect.flatMap((failedAt) => Ref.set(lastInstallFailureAtRef, failedAt)),
472 Effect.andThen(
473 Effect.logWarning("Could not install the pinned relay client", {
474 reason: error.reason,
475 message: error.message,
476 cause: error.cause,
477 }),
478 ),
479 ),
480 }),
481 Effect.ensuring(Ref.set(installInFlightRef, false)),
482 );
483 });
484​
485 const ensurePinnedRelayClient = Effect.gen(function* () {
486 const now = yield* Clock.currentTimeMillis;
487 const lastFailureAt = yield* Ref.get(lastInstallFailureAtRef);
488 if (lastFailureAt !== null && now - lastFailureAt < RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS) {
489 return;
490 }
491 yield* installPinnedRelayClient;
492 }).pipe(Effect.forkIn(runtimeScope), Effect.asVoid);
493​
494 // Retry installs skipped by applyConfig without the failure gate.
495 const retryPinnedRelayClientInstall = Effect.gen(function* () {
496 while (true) {
497 yield* Effect.sleep(Duration.millis(RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS));
498 const desiredConfig = yield* Ref.get(desiredConfigRef);
499 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
500 // An installed pin still needs activation after a failed probe or while an older connector runs.
501 const active = yield* Ref.get(activeRef);
502 if (active && !needsPinnedRelayClient(active.executable)) return;
503 yield* installPinnedRelayClient;
504 }
505 }).pipe(Effect.ensuring(Ref.set(retryLoopRunningRef, false)));
506​
507 const startPinnedRelayClientRetries = Effect.gen(function* () {
508 if (yield* Ref.getAndSet(retryLoopRunningRef, true)) return;
509 yield* Effect.forkIn(retryPinnedRelayClientInstall, runtimeScope);
510 });
511​
512 // Registration retries can last for the connector lifetime; keep this loop untraced.
513 const watchConnectorRegistration = Effect.fnUntraced(
514 function* (connector: ActiveConnector) {
515 yield* Effect.sleep(CONNECTOR_REGISTRATION_TIMEOUT);
516 if (yield* Deferred.isDone(connector.registered)) return true;
517 yield* Effect.logWarning(
518 "Relay client has not registered a tunnel connection; requesting recovery",
519 {
520 pid: Number(connector.child.pid),
521 tunnelId: connector.config.tunnelId,
522 tunnelName: connector.config.tunnelName,
523 },
524 );
525 yield* Queue.offer(recoveryRequests, connector.config);
526 return false;
527 },
528 Effect.repeat({ until: (connected) => connected }),
529 );
530​
531 // Only an explicit 503 counts: a failed request says nothing about the
532 // Readiness polling runs for the connector lifetime; keep this loop untraced.
533 const watchConnectorReadiness = Effect.fnUntraced(function* (connector: ActiveConnector) {
534 const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;
535 let notReadyChecks = 0;
536 let lastReady: boolean | null = null;
537 while (true) {
538 yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);
539 const status = yield* httpClient.get(readyUrl).pipe(
540 Effect.map((response) => response.status),
541 Effect.scoped,
542 Effect.withTracerEnabled(false),
543 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
544 Effect.orElseSucceed(() => Option.none<number>()),
545 );
546 if (Option.isNone(status)) continue;
547 if (status.value === 200 || status.value === 503) {
548 const ready = status.value === 200;
549 if (ready !== lastReady) yield* Queue.offer(readinessChanges, undefined);
550 lastReady = ready;
551 }
552 if (status.value === 200) {
553 notReadyChecks = 0;
554 yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
555 continue;
556 }
557 if (status.value !== 503) continue;
558 notReadyChecks += 1;
559 const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);
560 if (notReadyChecks < threshold) continue;
561 notReadyChecks = 0;
562 yield* Ref.set(
563 notReadyChecksBeforeRestartRef,
564 Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),
565 );
566 yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {
567 pid: Number(connector.child.pid),
568 notReadyChecks: threshold,
569 tunnelId: connector.config.tunnelId,
570 tunnelName: connector.config.tunnelName,
571 });
572 yield* connector.child.kill().pipe(Effect.ignore);
573 }
574 });
575​
576 const rememberHttp2Fallback = Effect.fnUntraced(function* () {
577 yield* Ref.set(http2Ref, true);
578 yield* secrets
579 .set(
580 HTTP2_FALLBACK_STATE,
581 new TextEncoder().encode(
582 encodeHttp2Fallback({ fellBackAt: yield* Clock.currentTimeMillis }),
583 ),
584 )
585 .pipe(
586 Effect.catch(() => Effect.logWarning("Could not persist the relay client HTTP/2 fallback")),
587 );
588 });
589​
590 const switchToHttp2 = Effect.fnUntraced(function* (connector: ActiveConnector) {
591 const active = yield* Ref.get(activeRef);
592 const desiredConfig = yield* Ref.get(desiredConfigRef);
593 if ((yield* Ref.get(http2Ref)) || active !== connector || !desiredConfig) return;
594 yield* rememberHttp2Fallback();
595 yield* Effect.logWarning("Relay client keeps losing QUIC connections; switching to HTTP/2", {
596 pid: Number(connector.child.pid),
597 tunnelId: connector.config.tunnelId,
598 tunnelName: connector.config.tunnelName,
599 });
600 // Shutdown must not interrupt cleanup after active ownership is cleared.
601 yield* Effect.uninterruptible(stopActive);
602 const status = yield* reconcileConfig(desiredConfig);
603 // A failed spawn has no supervisor to request recovery.
604 if (status.status !== "running") {
605 yield* Queue.offer(recoveryRequests, desiredConfig);
606 }
607 }, reconcileSemaphore.withPermits(1));
608​
609 const noteQuicStall = Effect.fnUntraced(function* (connector: ActiveConnector) {
610 if (transportChosenByUser || (yield* Ref.get(http2Ref))) return;
611 const now = yield* Clock.currentTimeMillis;
612 if ((yield* Ref.get(activeRef)) !== connector) return;
613 const stalls = yield* Ref.updateAndGet(quicStallsRef, (previous) => [
614 ...previous.filter((at) => now - at < QUIC_STALL_WINDOW_MS),
615 now,
616 ]);
617 if (stalls.length < QUIC_STALLS_BEFORE_HTTP2) return;
618 // Stopping the connector interrupts the output observer that called this.
619 yield* Effect.forkIn(switchToHttp2(connector), runtimeScope);
620 });
621​
622 const observeConnectorOutput = (connector: ActiveConnector) => {
623 let rejectedRegistrations = 0;
624​
625 return connector.child.all.pipe(
626 Stream.decodeText(),
627 Stream.splitLines,
628 Stream.map((line) => line.trim()),
629 Stream.filter((line) => line.length > 0),
630 Stream.runForEach((line) => {
631 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
632 const attributes = {
633 pid: Number(connector.child.pid),
634 tunnelId: connector.config.tunnelId,
635 tunnelName: connector.config.tunnelName,
636 output,
637 };
638 switch (classifyRelayClientOutput(line)) {
639 case "connected": {
640 rejectedRegistrations = 0;
641 const protocol = RELAY_CLIENT_PROTOCOL.exec(line)?.[1] ?? null;
642 return Deferred.succeed(connector.registered, undefined).pipe(
643 Effect.andThen(Ref.set(connector.protocol, protocol)),
644 // cloudflared started with `auto` fell back on its own; later starts skip QUIC too.
645 Effect.andThen(
646 protocol === "http2" && !transportChosenByUser
647 ? Ref.get(http2Ref).pipe(
648 Effect.flatMap((http2) => (http2 ? Effect.void : rememberHttp2Fallback())),
649 )
650 : Effect.void,
651 ),
652 Effect.andThen(
653 Effect.logInfo("Relay client tunnel connection registered", attributes),
654 ),
655 Effect.andThen(Queue.offer(tunnelConnections, undefined)),
656 Effect.andThen(Queue.offer(readinessChanges, undefined)),
657 Effect.andThen(
658 RelayClient.isPinnedManagedRelayClient(connector.executable)
659 ? Ref.getAndSet(prunedRef, true).pipe(
660 Effect.flatMap((pruned) =>
661 pruned ? Effect.void : relayClient.pruneManagedVersions,
662 ),
663 )
664 : Effect.void,
665 ),
666 Effect.asVoid,
667 );
668 }
669 case "unregistered":
670 return Effect.logInfo("Relay client tunnel connection unregistered", attributes);
671 case "warning":
672 if (/\btimeout: no recent network activity\b/u.test(line)) {
673 return noteQuicStall(connector).pipe(
674 Effect.andThen(
675 Effect.logWarning("Relay client reported a transport warning", attributes),
676 ),
677 );
678 }
679 if (isRejectedRelayClientTunnelOutput(line)) {
680 rejectedRegistrations += 1;
681 if (rejectedRegistrations >= TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY) {
682 rejectedRegistrations = 0;
683 return Effect.logWarning(
684 "Relay client tunnel was rejected; requesting recovery",
685 attributes,
686 ).pipe(
687 Effect.andThen(Queue.offer(recoveryRequests, connector.config)),
688 Effect.asVoid,
689 );
690 }
691 }
692 return Effect.logWarning("Relay client reported a transport warning", attributes);
693 case "debug": {
694 const metricsAddress = RELAY_CLIENT_METRICS_LINE.exec(line)?.[1];
695 return metricsAddress
696 ? Deferred.succeed(connector.metricsAddress, metricsAddress).pipe(
697 Effect.andThen(Effect.logDebug("Relay client output", attributes)),
698 )
699 : Effect.logDebug("Relay client output", attributes);
700 }
701 }
702 }),
703 Effect.catchCause((cause) =>
704 Effect.logWarning("Relay client output observer failed", {
705 cause,
706 pid: Number(connector.child.pid),
707 tunnelId: connector.config.tunnelId,
708 tunnelName: connector.config.tunnelName,
709 }),
710 ),
711 );
712 };
713​
714 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
715 if (!config || config.providerKind !== "cloudflare_tunnel") {
716 yield* stopActive;
717 return config
718 ? { status: "unsupported", providerKind: config.providerKind }
719 : { status: "disabled" };
720 }
721​
722 const nextConfigKey = runtimeConfigKey(config);
723 const active = yield* Ref.get(activeRef);
724 if (active?.configKey === nextConfigKey) {
725 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
726 if (isRunning) {
727 return {
728 status: "running",
729 providerKind: "cloudflare_tunnel",
730 pid: Number(active.child.pid),
731 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
732 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
733 } satisfies CloudManagedEndpointRuntimeStatus;
734 }
735 }
736​
737 yield* stopActive;
738​
739 const executable = yield* relayClient.resolve;
740 if (needsPinnedRelayClient(executable)) {
741 yield* ensurePinnedRelayClient;
742 yield* startPinnedRelayClientRetries;
743 }
744 if (executable.status !== "available") {
745 return {
746 status: "failed",
747 providerKind: "cloudflare_tunnel",
748 failure: executable.status === "unsupported" ? "unsupported-platform" : "not-installed",
749 reason:
750 executable.status === "unsupported"
751 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
752 : "The relay client is not installed.",
753 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
754 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
755 } satisfies CloudManagedEndpointRuntimeStatus;
756 }
757​
758 const http2 = yield* Ref.get(http2Ref);
759 const connectorScope = yield* Scope.make("sequential");
760 // Added before the spawn so it runs after the spawner's finalizer has stopped the client.
761 let forgetRelayClient: Effect.Effect<void> = Effect.void;
762 yield* Scope.addFinalizer(
763 connectorScope,
764 Effect.suspend(() => forgetRelayClient),
765 );
766 const child = yield* spawner
767 .spawn(
768 ChildProcess.make(
769 executable.executablePath,
770 [
771 "tunnel",
772 "--no-autoupdate",
773 "--loglevel",
774 "info",
775 "--output",
776 "default",
777 "--metrics",
778 "127.0.0.1:0",
779 ...(http2 ? ["--protocol", "http2"] : []),
780 "run",
781 ],
782 {
783 detached: false,
784 env: {
785 ...env,
786 TUNNEL_TOKEN: config.connectorToken,
787 },
788 shell: false,
789 stderr: "pipe",
790 stdout: "pipe",
791 },
792 ),
793 )
794 .pipe(
795 Effect.provideService(Scope.Scope, connectorScope),
796 Effect.tap((child) =>
797 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
798 pid: Number(child.pid),
799 source: executable.source,
800 version: executable.version,
801 protocol: http2 ? "http2" : "auto",
802 tunnelId: config.tunnelId,
803 tunnelName: config.tunnelName,
804 }),
805 ),
806 Effect.catch((cause) =>
807 Effect.logWarning("Failed to start relay client", {
808 cause,
809 tunnelId: config.tunnelId,
810 tunnelName: config.tunnelName,
811 }).pipe(
812 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
813 Effect.as({
814 status: "failed",
815 providerKind: "cloudflare_tunnel",
816 failure: "spawn-failed",
817 reason: String(cause),
818 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
819 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
820 } satisfies CloudManagedEndpointRuntimeStatus),
821 ),
822 ),
823 );
824​
825 if ("status" in child && child.status === "failed") {
826 return child;
827 }
828​
829 if (!("status" in child)) {
830 // An interrupt before activeRef owns a supervised connector would leave its client open or unwatched.
831 yield* Effect.uninterruptibleMask((restore) =>
832 Effect.gen(function* () {
833 forgetRelayClient = yield* relayClientLedger.track(Number(child.pid));
834 const connector = {
835 child,
836 executable,
837 scope: connectorScope,
838 configKey: nextConfigKey,
839 config,
840 startedAtMillis: yield* Clock.currentTimeMillis,
841 registered: yield* Deferred.make<void>(),
842 metricsAddress: yield* Deferred.make<string>(),
843 protocol: yield* Ref.make<string | null>(null),
844 } satisfies ActiveConnector;
845 yield* Ref.set(activeRef, connector);
846 yield* Effect.forkIn(restore(observeConnectorOutput(connector)), connectorScope);
847 yield* Effect.forkIn(restore(superviseConnector(connector)), connectorScope);
848 yield* Effect.forkIn(restore(watchConnectorRegistration(connector)), connectorScope);
849 yield* Effect.forkIn(restore(watchConnectorReadiness(connector)), connectorScope);
850 }),
851 );
852 return {
853 status: "running",
854 providerKind: "cloudflare_tunnel",
855 pid: Number(child.pid),
856 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
857 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
858 } satisfies CloudManagedEndpointRuntimeStatus;
859 }
860​
861 return {
862 status: "failed",
863 providerKind: "cloudflare_tunnel",
864 failure: "spawn-failed",
865 reason: "Relay client did not start.",
866 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
867 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
868 } satisfies CloudManagedEndpointRuntimeStatus;
869 });
870​
871 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
872 (requested: RelayManagedEndpointRuntimeConfig | null) =>
873 reconcileSemaphore.withPermits(1)(
874 Effect.gen(function* () {
875 const config = connectAllowed ? requested : null;
876 // Keep backoff when recovery returns the same tunnel/token, or every recovery respawns a crash loop.
877 const desired = yield* Ref.get(desiredConfigRef);
878 const unchanged =
879 desired !== null &&
880 config !== null &&
881 runtimeConfigKey(desired) === runtimeConfigKey(config);
882 if (!unchanged) {
883 yield* Ref.set(restartDelayRef, 0);
884 }
885 yield* Ref.set(desiredConfigRef, config);
886 return yield* reconcileConfig(config);
887 }),
888 ),
889 withRelayClientLog,
890 );
891​
892 const restartConnector = Effect.fn("CloudManagedEndpointRuntime.restartConnector")(function* (
893 pid: number,
894 stillDead: Effect.Effect<boolean>,
895 ) {
896 const active = yield* Ref.get(activeRef);
897 if (!active || Number(active.child.pid) !== pid || !(yield* stillDead)) return false;
898 yield* Effect.logWarning(
899 "Cloudflare has no live connection from the relay client; restarting it",
900 { pid, tunnelId: active.config.tunnelId, tunnelName: active.config.tunnelName },
901 );
902 // The supervisor starts the replacement with its usual crash-loop backoff.
903 return yield* active.child.kill().pipe(
904 Effect.as(true),
905 Effect.orElseSucceed(() => false),
906 );
907 }, reconcileSemaphore.withPermits(1));
908​
909 const readMetrics = <S extends Schema.Decoder<unknown>>(url: string, schema: S) =>
910 httpClient.get(url).pipe(
911 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
912 Effect.scoped,
913 Effect.withTracerEnabled(false),
914 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
915 Effect.map(Option.getOrNull),
916 Effect.orElseSucceed(() => null),
917 );
918​
919 const inspectConnector = Effect.gen(function* () {
920 const active = yield* Ref.get(activeRef);
921 if (!active || !(yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false)))) {
922 return null;
923 }
924 const pid = Number(active.child.pid);
925 const protocol = yield* Ref.get(active.protocol);
926 if (!(yield* Deferred.isDone(active.metricsAddress))) {
927 return { pid, readyConnections: null, hostname: null, protocol } satisfies ConnectorFacts;
928 }
929 const metricsUrl = `http://${yield* Deferred.await(active.metricsAddress)}`;
930 const [ready, config] = yield* Effect.all(
931 [
932 readMetrics(`${metricsUrl}/ready`, ConnectorReadyBody),
933 readMetrics(`${metricsUrl}/config`, ConnectorConfigBody),
934 ],
935 { concurrency: 2 },
936 );
937 return {
938 pid,
939 readyConnections: ready?.readyConnections ?? null,
940 hostname: config?.config.ingress?.find((rule) => rule.hostname)?.hostname ?? null,
941 protocol,
942 } satisfies ConnectorFacts;
943 });
944​
945 const runtime = CloudManagedEndpointRuntime.of({
946 applyConfig,
947 inspectConnector,
948 readinessChanged: Stream.fromQueue(readinessChanges),
949 recoveryRequests: Stream.fromQueue(recoveryRequests),
950 requestRecovery: Effect.fn("CloudManagedEndpointRuntime.requestRecovery")(function (config) {
951 return Queue.offer(recoveryRequests, config).pipe(Effect.asVoid);
952 }),
953 restartConnector,
954 tunnelConnected: Stream.fromQueue(tunnelConnections),
955 withLinkStateLock: linkStateSemaphore.withPermits(1),
956 });
957​
958 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
959 return runtime;
960});
961​
962export const layer = Layer.effect(CloudManagedEndpointRuntime, make);