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