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 // Back off outside the semaphore so config changes remain responsive; recheck config afterwards.
368 const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
369 if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
370 return [0, 0];
371 }
372 return [
373 current,
374 current === 0
375 ? RELAY_RESTART_BACKOFF_BASE_MS
376 : Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
377 ];
378 });
379 if (restartDelayMillis > 0) {
380 yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
381 pid: Number(connector.child.pid),
382 uptimeMillis,
383 restartDelayMillis,
384 tunnelId: connector.config.tunnelId,
385 tunnelName: connector.config.tunnelName,
386 });
387 yield* Effect.sleep(Duration.millis(restartDelayMillis));
388 }
389 yield* reconcileSemaphore.withPermits(1)(
390 Effect.gen(function* () {
391 const active = yield* Ref.get(activeRef);
392 if (
393 active?.child.pid !== connector.child.pid ||
394 active.configKey !== connector.configKey
395 ) {
396 return;
397 }
398 yield* Ref.set(activeRef, null);
399 yield* stopConnector(connector);
400
401 const desiredConfig = yield* Ref.get(desiredConfigRef);
402 if (
403 shutdownSignalReceived ||
404 !desiredConfig ||
405 desiredConfig.providerKind !== "cloudflare_tunnel" ||
406 runtimeConfigKey(desiredConfig) !== connector.configKey
407 ) {
408 return;
409 }
410
411 yield* Effect.logWarning("Relay client exited; restarting", {
412 pid: Number(connector.child.pid),
413 ...(Result.isSuccess(result)
414 ? { exitCode: Number(result.success) }
415 : { cause: result.failure }),
416 tunnelId: connector.config.tunnelId,
417 tunnelName: connector.config.tunnelName,
418 });
419 yield* Queue.offer(recoveryRequests, connector.config);
420 yield* reconcileConfig(desiredConfig);
421 }),
422 );
423 },
424 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
425 );
426
427 // Keep the old connector until its replacement registers, preserving the relay connection.
428 const installPinnedRelayClient = Effect.gen(function* () {
429 if (yield* Ref.getAndSet(installInFlightRef, true)) return;
430 yield* Effect.logInfo("Installing the pinned relay client", {
431 version: RelayClient.CLOUDFLARED_VERSION,
432 });
433 yield* relayClient.install.pipe(
434 Effect.tap(() => Ref.set(lastInstallFailureAtRef, null)),
435 Effect.flatMap((installed) =>
436 reconcileSemaphore.withPermits(1)(
437 Effect.gen(function* () {
438 const desiredConfig = yield* Ref.get(desiredConfigRef);
439 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
440 const active = yield* Ref.get(activeRef);
441 // Self-updated binaries share the pinned path; compare versions to detect replacements.
442 if (
443 active?.executable.executablePath === installed.executablePath &&
444 active.executable.version === installed.version
445 ) {
446 return;
447 }
448 // A scanner can block a fresh binary's probe; retry instead of restarting onto the older binary.
449 const resolved = yield* relayClient.resolve;
450 if (
451 resolved.status !== "available" ||
452 resolved.executablePath !== installed.executablePath ||
453 resolved.version !== installed.version
454 ) {
455 return;
456 }
457 yield* Effect.logInfo("Relay client installed; moving the connector to it", {
458 version: installed.version,
459 previousVersion: active?.executable.version,
460 });
461 const previous = yield* Ref.getAndSet(activeRef, null);
462 const status = yield* reconcileConfig(desiredConfig);
463 const next = yield* Ref.get(activeRef);
464 if (!next) {
465 yield* Effect.logWarning("Relay client did not start after the update", status);
466 // The supervisor skips exits while detached; request recovery explicitly.
467 const previousRunning = previous
468 ? yield* previous.child.isRunning.pipe(Effect.orElseSucceed(() => false))
469 : false;
470 if (previous && previousRunning) {
471 yield* Ref.set(activeRef, previous);
472 } else {
473 yield* stopConnector(previous);
474 yield* Queue.offer(recoveryRequests, desiredConfig);
475 }
476 return;
477 }
478 if (previous) {
479 yield* Deferred.await(next.registered).pipe(
480 Effect.ensuring(stopConnector(previous)),
481 Effect.forkIn(next.scope),
482 );
483 }
484 }),
485 ),
486 ),
487 Effect.catchTags({
488 RelayClientInstallError: (error) =>
489 Clock.currentTimeMillis.pipe(
490 Effect.flatMap((failedAt) => Ref.set(lastInstallFailureAtRef, failedAt)),
491 Effect.andThen(
492 Effect.logWarning("Could not install the pinned relay client", {
493 reason: error.reason,
494 message: error.message,
495 cause: error.cause,
496 }),
497 ),
498 ),
499 }),
500 Effect.ensuring(Ref.set(installInFlightRef, false)),
501 );
502 });
503
504 const ensurePinnedRelayClient = Effect.gen(function* () {
505 const now = yield* Clock.currentTimeMillis;
506 const lastFailureAt = yield* Ref.get(lastInstallFailureAtRef);
507 if (lastFailureAt !== null && now - lastFailureAt < RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS) {
508 return;
509 }
510 yield* installPinnedRelayClient;
511 }).pipe(Effect.forkIn(runtimeScope), Effect.asVoid);
512
513 // Retry installs skipped by applyConfig without the failure gate.
514 const retryPinnedRelayClientInstall = Effect.gen(function* () {
515 while (true) {
516 yield* Effect.sleep(Duration.millis(RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS));
517 const desiredConfig = yield* Ref.get(desiredConfigRef);
518 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
519 // An installed pin still needs activation after a failed probe or while an older connector runs.
520 const active = yield* Ref.get(activeRef);
521 if (active && !needsPinnedRelayClient(active.executable)) return;
522 yield* installPinnedRelayClient;
523 }
524 }).pipe(Effect.ensuring(Ref.set(retryLoopRunningRef, false)));
525
526 const startPinnedRelayClientRetries = Effect.gen(function* () {
527 if (yield* Ref.getAndSet(retryLoopRunningRef, true)) return;
528 yield* Effect.forkIn(retryPinnedRelayClientInstall, runtimeScope);
529 });
530
531 // Registration retries can last for the connector lifetime; keep this loop untraced.
532 const watchConnectorRegistration = Effect.fnUntraced(
533 function* (connector: ActiveConnector) {
534 yield* Effect.sleep(CONNECTOR_REGISTRATION_TIMEOUT);
535 if (yield* Deferred.isDone(connector.registered)) return true;
536 yield* Effect.logWarning(
537 "Relay client has not registered a tunnel connection; requesting recovery",
538 {
539 pid: Number(connector.child.pid),
540 tunnelId: connector.config.tunnelId,
541 tunnelName: connector.config.tunnelName,
542 },
543 );
544 yield* Queue.offer(recoveryRequests, connector.config);
545 return false;
546 },
547 Effect.repeat({ until: (connected) => connected }),
548 );
549
550 // Only an explicit 503 counts: a failed request says nothing about the
551 // Readiness polling runs for the connector lifetime; keep this loop untraced.
552 const watchConnectorReadiness = Effect.fnUntraced(function* (connector: ActiveConnector) {
553 const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;
554 let notReadyChecks = 0;
555 let lastReady: boolean | null = null;
556 while (true) {
557 yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);
558 const status = yield* httpClient.get(readyUrl).pipe(
559 Effect.map((response) => response.status),
560 Effect.scoped,
561 Effect.withTracerEnabled(false),
562 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
563 Effect.orElseSucceed(() => Option.none<number>()),
564 );
565 if (Option.isNone(status)) continue;
566 if (status.value === 200 || status.value === 503) {
567 const ready = status.value === 200;
568 if (ready !== lastReady) yield* Queue.offer(readinessChanges, undefined);
569 lastReady = ready;
570 }
571 if (status.value === 200) {
572 notReadyChecks = 0;
573 yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
574 continue;
575 }
576 if (status.value !== 503) continue;
577 notReadyChecks += 1;
578 const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);
579 if (notReadyChecks < threshold) continue;
580 notReadyChecks = 0;
581 yield* Ref.set(
582 notReadyChecksBeforeRestartRef,
583 Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),
584 );
585 yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {
586 pid: Number(connector.child.pid),
587 notReadyChecks: threshold,
588 tunnelId: connector.config.tunnelId,
589 tunnelName: connector.config.tunnelName,
590 });
591 yield* connector.child
592 .kill({ forceKillAfter: RELAY_CLIENT_FORCE_KILL_AFTER })
593 .pipe(Effect.ignore);
594 }
595 });
596
597 const rememberHttp2Fallback = Effect.fnUntraced(function* () {
598 yield* Ref.set(http2Ref, true);
599 yield* secrets
600 .set(
601 HTTP2_FALLBACK_STATE,
602 new TextEncoder().encode(
603 encodeHttp2Fallback({ fellBackAt: yield* Clock.currentTimeMillis }),
604 ),
605 )
606 .pipe(
607 Effect.catch(() => Effect.logWarning("Could not persist the relay client HTTP/2 fallback")),
608 );
609 });
610
611 const switchToHttp2 = Effect.fnUntraced(function* (connector: ActiveConnector) {
612 const active = yield* Ref.get(activeRef);
613 const desiredConfig = yield* Ref.get(desiredConfigRef);
614 if ((yield* Ref.get(http2Ref)) || active !== connector || !desiredConfig) return;
615 yield* rememberHttp2Fallback();
616 yield* Effect.logWarning("Relay client keeps losing QUIC connections; switching to HTTP/2", {
617 pid: Number(connector.child.pid),
618 tunnelId: connector.config.tunnelId,
619 tunnelName: connector.config.tunnelName,
620 });
621 // Shutdown must not interrupt cleanup after active ownership is cleared.
622 yield* Effect.uninterruptible(stopActive);
623 const status = yield* reconcileConfig(desiredConfig);
624 // A failed spawn has no supervisor to request recovery.
625 if (status.status !== "running") {
626 yield* Queue.offer(recoveryRequests, desiredConfig);
627 }
628 }, reconcileSemaphore.withPermits(1));
629
630 const noteQuicStall = Effect.fnUntraced(function* (connector: ActiveConnector) {
631 if (transportChosenByUser || (yield* Ref.get(http2Ref))) return;
632 const now = yield* Clock.currentTimeMillis;
633 if ((yield* Ref.get(activeRef)) !== connector) return;
634 const stalls = yield* Ref.updateAndGet(quicStallsRef, (previous) => [
635 ...previous.filter((at) => now - at < QUIC_STALL_WINDOW_MS),
636 now,
637 ]);
638 if (stalls.length < QUIC_STALLS_BEFORE_HTTP2) return;
639 // Stopping the connector interrupts the output observer that called this.
640 yield* Effect.forkIn(switchToHttp2(connector), runtimeScope);
641 });
642
643 const observeConnectorOutput = (connector: ActiveConnector) => {
644 let rejectedRegistrations = 0;
645
646 return connector.child.all.pipe(
647 Stream.decodeText(),
648 Stream.splitLines,
649 Stream.map((line) => line.trim()),
650 Stream.filter((line) => line.length > 0),
651 Stream.runForEach((line) => {
652 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
653 const attributes = {
654 pid: Number(connector.child.pid),
655 tunnelId: connector.config.tunnelId,
656 tunnelName: connector.config.tunnelName,
657 output,
658 };
659 switch (classifyRelayClientOutput(line)) {
660 case "connected": {
661 rejectedRegistrations = 0;
662 const protocol = RELAY_CLIENT_PROTOCOL.exec(line)?.[1] ?? null;
663 return Deferred.succeed(connector.registered, undefined).pipe(
664 Effect.andThen(Ref.set(connector.protocol, protocol)),
665 // cloudflared started with `auto` fell back on its own; later starts skip QUIC too.
666 Effect.andThen(
667 protocol === "http2" && !transportChosenByUser
668 ? Ref.get(http2Ref).pipe(
669 Effect.flatMap((http2) => (http2 ? Effect.void : rememberHttp2Fallback())),
670 )
671 : Effect.void,
672 ),
673 Effect.andThen(
674 Effect.logInfo("Relay client tunnel connection registered", attributes),
675 ),
676 Effect.andThen(Queue.offer(tunnelConnections, undefined)),
677 Effect.andThen(Queue.offer(readinessChanges, undefined)),
678 Effect.andThen(
679 RelayClient.isPinnedManagedRelayClient(connector.executable)
680 ? Ref.getAndSet(prunedRef, true).pipe(
681 Effect.flatMap((pruned) =>
682 pruned ? Effect.void : relayClient.pruneManagedVersions,
683 ),
684 )
685 : Effect.void,
686 ),
687 Effect.asVoid,
688 );
689 }
690 case "unregistered":
691 return Effect.logInfo("Relay client tunnel connection unregistered", attributes);
692 case "warning":
693 if (/\btimeout: no recent network activity\b/u.test(line)) {
694 return noteQuicStall(connector).pipe(
695 Effect.andThen(
696 Effect.logWarning("Relay client reported a transport warning", attributes),
697 ),
698 );
699 }
700 if (isRejectedRelayClientTunnelOutput(line)) {
701 rejectedRegistrations += 1;
702 if (rejectedRegistrations >= TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY) {
703 rejectedRegistrations = 0;
704 return Effect.logWarning(
705 "Relay client tunnel was rejected; requesting recovery",
706 attributes,
707 ).pipe(
708 Effect.andThen(Queue.offer(recoveryRequests, connector.config)),
709 Effect.asVoid,
710 );
711 }
712 }
713 return Effect.logWarning("Relay client reported a transport warning", attributes);
714 case "debug": {
715 const metricsAddress = RELAY_CLIENT_METRICS_LINE.exec(line)?.[1];
716 return metricsAddress
717 ? Deferred.succeed(connector.metricsAddress, metricsAddress).pipe(
718 Effect.andThen(Effect.logDebug("Relay client output", attributes)),
719 )
720 : Effect.logDebug("Relay client output", attributes);
721 }
722 }
723 }),
724 Effect.catchCause((cause) =>
725 Effect.logWarning("Relay client output observer failed", {
726 cause,
727 pid: Number(connector.child.pid),
728 tunnelId: connector.config.tunnelId,
729 tunnelName: connector.config.tunnelName,
730 }),
731 ),
732 );
733 };
734
735 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
736 if (!config || config.providerKind !== "cloudflare_tunnel") {
737 yield* stopActive;
738 return config
739 ? { status: "unsupported", providerKind: config.providerKind }
740 : { status: "disabled" };
741 }
742
743 const nextConfigKey = runtimeConfigKey(config);
744 const active = yield* Ref.get(activeRef);
745 if (active?.configKey === nextConfigKey) {
746 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
747 if (isRunning) {
748 return {
749 status: "running",
750 providerKind: "cloudflare_tunnel",
751 pid: Number(active.child.pid),
752 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
753 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
754 } satisfies CloudManagedEndpointRuntimeStatus;
755 }
756 }
757
758 yield* stopActive;
759
760 const executable = yield* relayClient.resolve;
761 if (needsPinnedRelayClient(executable)) {
762 yield* ensurePinnedRelayClient;
763 yield* startPinnedRelayClientRetries;
764 }
765 if (executable.status !== "available") {
766 return {
767 status: "failed",
768 providerKind: "cloudflare_tunnel",
769 failure: executable.status === "unsupported" ? "unsupported-platform" : "not-installed",
770 reason:
771 executable.status === "unsupported"
772 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
773 : "The relay client is not installed.",
774 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
775 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
776 } satisfies CloudManagedEndpointRuntimeStatus;
777 }
778
779 const http2 = yield* Ref.get(http2Ref);
780 const connectorScope = yield* Scope.make("sequential");
781 // Added before the spawn so it runs after the spawner's finalizer has stopped the client.
782 let forgetRelayClient: Effect.Effect<void> = Effect.void;
783 yield* Scope.addFinalizer(
784 connectorScope,
785 Effect.suspend(() => forgetRelayClient),
786 );
787 const child = yield* spawner
788 .spawn(
789 ChildProcess.make(
790 executable.executablePath,
791 [
792 "tunnel",
793 "--no-autoupdate",
794 "--loglevel",
795 "info",
796 "--output",
797 "default",
798 "--metrics",
799 "127.0.0.1:0",
800 ...(http2 ? ["--protocol", "http2"] : []),
801 "run",
802 ],
803 {
804 detached: false,
805 forceKillAfter: RELAY_CLIENT_FORCE_KILL_AFTER,
806 env: {
807 ...env,
808 TUNNEL_TOKEN: config.connectorToken,
809 },
810 shell: false,
811 stderr: "pipe",
812 stdout: "pipe",
813 },
814 ),
815 )
816 .pipe(
817 Effect.provideService(Scope.Scope, connectorScope),
818 Effect.tap((child) =>
819 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
820 pid: Number(child.pid),
821 source: executable.source,
822 version: executable.version,
823 protocol: http2 ? "http2" : "auto",
824 tunnelId: config.tunnelId,
825 tunnelName: config.tunnelName,
826 }),
827 ),
828 Effect.catch((cause) =>
829 Effect.logWarning("Failed to start relay client", {
830 cause,
831 tunnelId: config.tunnelId,
832 tunnelName: config.tunnelName,
833 }).pipe(
834 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
835 Effect.as({
836 status: "failed",
837 providerKind: "cloudflare_tunnel",
838 failure: "spawn-failed",
839 reason: String(cause),
840 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
841 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
842 } satisfies CloudManagedEndpointRuntimeStatus),
843 ),
844 ),
845 );
846
847 if ("status" in child && child.status === "failed") {
848 return child;
849 }
850
851 if (!("status" in child)) {
852 // An interrupt before activeRef owns a supervised connector would leave its client open or unwatched.
853 yield* Effect.uninterruptibleMask((restore) =>
854 Effect.gen(function* () {
855 forgetRelayClient = yield* relayClientLedger.track(Number(child.pid));
856 const connector = {
857 child,
858 executable,
859 scope: connectorScope,
860 configKey: nextConfigKey,
861 config,
862 startedAtMillis: yield* Clock.currentTimeMillis,
863 registered: yield* Deferred.make<void>(),
864 metricsAddress: yield* Deferred.make<string>(),
865 protocol: yield* Ref.make<string | null>(null),
866 } satisfies ActiveConnector;
867 yield* Ref.set(activeRef, connector);
868 yield* Effect.forkIn(restore(observeConnectorOutput(connector)), connectorScope);
869 yield* Effect.forkIn(restore(superviseConnector(connector)), connectorScope);
870 yield* Effect.forkIn(restore(watchConnectorRegistration(connector)), connectorScope);
871 yield* Effect.forkIn(restore(watchConnectorReadiness(connector)), connectorScope);
872 }),
873 );
874 return {
875 status: "running",
876 providerKind: "cloudflare_tunnel",
877 pid: Number(child.pid),
878 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
879 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
880 } satisfies CloudManagedEndpointRuntimeStatus;
881 }
882
883 return {
884 status: "failed",
885 providerKind: "cloudflare_tunnel",
886 failure: "spawn-failed",
887 reason: "Relay client did not start.",
888 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
889 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
890 } satisfies CloudManagedEndpointRuntimeStatus;
891 });
892
893 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
894 (requested: RelayManagedEndpointRuntimeConfig | null) =>
895 reconcileSemaphore.withPermits(1)(
896 Effect.gen(function* () {
897 const config = connectAllowed ? requested : null;
898 // Keep backoff when recovery returns the same tunnel/token, or every recovery respawns a crash loop.
899 const desired = yield* Ref.get(desiredConfigRef);
900 const unchanged =
901 desired !== null &&
902 config !== null &&
903 runtimeConfigKey(desired) === runtimeConfigKey(config);
904 if (!unchanged) {
905 yield* Ref.set(restartDelayRef, 0);
906 }
907 yield* Ref.set(desiredConfigRef, config);
908 return yield* reconcileConfig(config);
909 }),
910 ),
911 withRelayClientLog,
912 );
913
914 const restartConnector = Effect.fn("CloudManagedEndpointRuntime.restartConnector")(function* (
915 pid: number,
916 stillDead: Effect.Effect<boolean>,
917 ) {
918 const active = yield* Ref.get(activeRef);
919 if (!active || Number(active.child.pid) !== pid || !(yield* stillDead)) return false;
920 yield* Effect.logWarning(
921 "Cloudflare has no live connection from the relay client; restarting it",
922 { pid, tunnelId: active.config.tunnelId, tunnelName: active.config.tunnelName },
923 );
924 // The supervisor starts the replacement with its usual crash-loop backoff.
925 return yield* active.child.kill({ forceKillAfter: RELAY_CLIENT_FORCE_KILL_AFTER }).pipe(
926 Effect.as(true),
927 Effect.orElseSucceed(() => false),
928 );
929 }, reconcileSemaphore.withPermits(1));
930
931 const readMetrics = <S extends Schema.Decoder<unknown>>(url: string, schema: S) =>
932 httpClient.get(url).pipe(
933 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
934 Effect.scoped,
935 Effect.withTracerEnabled(false),
936 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
937 Effect.map(Option.getOrNull),
938 Effect.orElseSucceed(() => null),
939 );
940
941 const inspectConnector = Effect.gen(function* () {
942 const active = yield* Ref.get(activeRef);
943 if (!active || !(yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false)))) {
944 return null;
945 }
946 const pid = Number(active.child.pid);
947 const protocol = yield* Ref.get(active.protocol);
948 if (!(yield* Deferred.isDone(active.metricsAddress))) {
949 return {
950 pid,
951 readyConnections: null,
952 hostname: null,
953 origin: null,
954 protocol,
955 } satisfies ConnectorFacts;
956 }
957 const metricsUrl = `http://${yield* Deferred.await(active.metricsAddress)}`;
958 const [ready, config] = yield* Effect.all(
959 [
960 readMetrics(`${metricsUrl}/ready`, ConnectorReadyBody),
961 readMetrics(`${metricsUrl}/config`, ConnectorConfigBody),
962 ],
963 { concurrency: 2 },
964 );
965 const hostnameRule = config?.config.ingress?.find((rule) => rule.hostname);
966 return {
967 pid,
968 readyConnections: ready?.readyConnections ?? null,
969 hostname: hostnameRule?.hostname ?? null,
970 origin: hostnameRule?.service ?? null,
971 protocol,
972 } satisfies ConnectorFacts;
973 });
974
975 const runtime = CloudManagedEndpointRuntime.of({
976 applyConfig,
977 inspectConnector,
978 readinessChanged: Stream.fromQueue(readinessChanges),
979 recoveryRequests: Stream.fromQueue(recoveryRequests),
980 requestRecovery: Effect.fn("CloudManagedEndpointRuntime.requestRecovery")(function (config) {
981 return Queue.offer(recoveryRequests, config).pipe(Effect.asVoid);
982 }),
983 restartConnector,
984 tunnelConnected: Stream.fromQueue(tunnelConnections),
985 withLinkStateLock: linkStateSemaphore.withPermits(1),
986 });
987
988 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
989 return runtime;
990});
991
992export const layer = Layer.effect(CloudManagedEndpointRuntime, make);