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