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

ManagedEndpointRuntime.ts

875 lines35.4 KB

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