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