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

ManagedEndpointRuntime.ts

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