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