Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ManagedEndpointRuntime.ts

919 lines37.0 KB

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