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

ManagedEndpointRuntime.ts

800 lines32.8 KB

1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import * as RelayClient from "@t3tools/shared/relayClient";
3import * as Clock from "effect/Clock";
4import * as Context from "effect/Context";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as Exit from "effect/Exit";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
13import * as Result from "effect/Result";
14import * as Schema from "effect/Schema";
15import * as Semaphore from "effect/Semaphore";
16import * as Scope from "effect/Scope";
17import * as Stream from "effect/Stream";
18import { HttpClient, HttpClientResponse } from "effect/http";
19import * as ChildProcess from "effect/process/ChildProcess";
20import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
21​
22export type CloudManagedEndpointRuntimeStatus =
23 | {
24 readonly status: "disabled";
25 }
26 | {
27 readonly status: "failed";
28 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
29 readonly failure: "unsupported-platform" | "not-installed" | "spawn-failed";
30 readonly reason: string;
31 readonly tunnelId?: string;
32 readonly tunnelName?: string;
33 }
34 | {
35 readonly status: "running";
36 readonly providerKind: "cloudflare_tunnel";
37 readonly pid: number;
38 readonly tunnelId?: string;
39 readonly tunnelName?: string;
40 }
41 | {
42 readonly status: "unsupported";
43 readonly providerKind: RelayManagedEndpointRuntimeConfig["providerKind"];
44 };
45​
46/** What the running cloudflared reports about itself. `null` fields are not known yet. */
47export interface ConnectorFacts {
48 readonly readyConnections: number | null;
49 /** The public tunnel hostname from the remote config cloudflared receives once it connects. */
50 readonly hostname: string | null;
51 readonly protocol: string | null;
53​
54export class CloudManagedEndpointRuntime extends Context.Service<
55 CloudManagedEndpointRuntime,
56 {
57 readonly applyConfig: (
58 config: RelayManagedEndpointRuntimeConfig | null,
59 ) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;
60 /** `null` when no connector is running. */
61 readonly inspectConnector: Effect.Effect<ConnectorFacts | null>;
62 /** Emits when a connector registers a connection or its readiness changes. */
63 readonly readinessChanged: Stream.Stream<void>;
64 readonly recoveryRequests: Stream.Stream<RelayManagedEndpointRuntimeConfig>;
65 readonly requestRecovery: (config: RelayManagedEndpointRuntimeConfig) => Effect.Effect<void>;
66 readonly tunnelConnected: Stream.Stream<void>;
67 readonly withLinkStateLock: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
68 }
69>()("t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime") {}
70​
71interface ActiveConnector {
72 readonly child: ChildProcessSpawner.ChildProcessHandle;
73 readonly executable: RelayClient.AvailableRelayClient;
74 readonly scope: Scope.Closeable;
75 readonly configKey: string;
76 readonly config: RelayManagedEndpointRuntimeConfig;
77 readonly startedAtMillis: number;
78 readonly registered: Deferred.Deferred<void>;
79 readonly metricsAddress: Deferred.Deferred<string>;
80 readonly protocol: Ref.Ref<string | null>;
82​
83// Without the backoff below, a relay client that fails instantly (a stale
84// version-manager shim, a bad binary) respawns ~100 times per second until the
85// accumulated tracing exhausts the V8 heap.
86const RELAY_RESTART_STABLE_UPTIME_MS = 30_000;
87const RELAY_RESTART_BACKOFF_BASE_MS = 1_000;
88const RELAY_RESTART_BACKOFF_MAX_MS = 60_000;
89// Newly created tunnels can fail authorization briefly while Cloudflare propagates their token.
90const TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY = 4;
91// A connector that never registers a connection may hold a token for a tunnel
92// that no longer exists, rejected in wording the output check does not know.
93// Ask for recovery after this long, and again at this interval while it stays
94// unconnected; the relay hands back the same tunnel when it is still live.
95const CONNECTOR_REGISTRATION_TIMEOUT = Duration.minutes(3);
96// cloudflared resolves the edge only at startup, so after a network change it
97// can stay alive with zero connections, dialing addresses that no longer route.
98const CONNECTOR_READINESS_INTERVAL = Duration.seconds(30);
99const CONNECTOR_READINESS_REQUEST_TIMEOUT = Duration.seconds(5);
100const CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART = 6;
101const CONNECTOR_NOT_READY_CHECKS_MAX = 60;
102const RELAY_CLIENT_METRICS_LINE = /\bStarting metrics server on (127\.0\.0\.1:\d+)\/metrics\b/u;
103const RELAY_CLIENT_PROTOCOL = /\bprotocol=(\w+)/u;
104// cloudflared's metrics server: `/ready` answers 200 or 503 with this body, and
105// `/config` holds the ingress rules the edge pushed after the first connection.
106const ConnectorReadyBody = Schema.Struct({ readyConnections: Schema.Number });
107const ConnectorConfigBody = Schema.Struct({
108 config: Schema.Struct({
109 ingress: Schema.optional(
110 Schema.NullOr(Schema.Array(Schema.Struct({ hostname: Schema.optional(Schema.String) }))),
111 ),
112 }),
113});
114// Registration resets cloudflared's own fallback, even when QUIC stalls again
115// immediately. Keep that evidence across registrations and connector restarts.
116const QUIC_STALLS_BEFORE_HTTP2 = 30;
117const QUIC_STALL_WINDOW_MS = 5 * 60_000;
118// A failed background install of the pinned relay client is retried no sooner
119// than this, so a crash-looping connector or an offline host does not redownload
120// on every reconcile.
121const RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS = 10 * 60_000;
122​
123/**
124 * A PATH binary or an explicit override is the user's choice, and the CLI asks
125 * before downloading, so both stay put.
126 */
127function needsPinnedRelayClient(executable: RelayClient.RelayClientStatus): boolean {
128 return (
129 executable.status === "missing" ||
130 (executable.status === "available" &&
131 executable.source === "managed" &&
132 !RelayClient.isPinnedManagedRelayClient(executable))
133 );
135​
136export function classifyRelayClientOutput(line: string): "connected" | "warning" | "debug" {
137 if (/\bRegistered tunnel connection\b/iu.test(line)) {
138 return "connected";
139 }
140 // cloudflared uses zerolog level tokens. FTL (fatal) and PNC (panic) are more
141 // severe than ERR, so they must surface at least as loudly — without them a
142 // fatal connector failure would be logged at debug and hidden.
143 return /\b(?:ERR|WRN|FTL|PNC)\b/u.test(line) ? "warning" : "debug";
145​
146/**
147 * The edge words this differently over time (`Failed to get tunnel`, `Tunnel
148 * not found`, ...), sometimes prefixed with `Unauthorized:`. Treat any
149 * `Unauthorized:` registration error as a rejection, plus the unprefixed
150 * messages seen so far.
151 */
152export function isRejectedRelayClientTunnelOutput(line: string): boolean {
153 return (
154 /\bRegister tunnel error from server side\b/iu.test(line) &&
155 /error="(?:Unauthorized:[^"]*|Failed to get tunnel|Tunnel not found|Record for tunnel not found|Invalid tunnel secret)"/iu.test(
156 line,
157 )
158 );
160​
161export function isRetryableManagedEndpointRuntimeStatus(status: unknown): boolean {
162 if (typeof status !== "object" || status === null || !("status" in status)) {
163 return false;
164 }
165 if (status.status !== "failed" || !("failure" in status)) {
166 return false;
167 }
168 return status.failure === "not-installed" || status.failure === "spawn-failed";
170​
171function runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {
172 return JSON.stringify({
173 providerKind: config.providerKind,
174 connectorToken: config.connectorToken,
175 tunnelId: config.tunnelId ?? null,
176 tunnelName: config.tunnelName ?? null,
177 });
179​
180const stopConnector = (connector: ActiveConnector | null) =>
181 connector
182 ? Scope.close(connector.scope, Exit.void).pipe(
183 Effect.tap(() =>
184 Effect.logInfo("Relay client stopped", {
185 pid: Number(connector.child.pid),
186 }),
187 ),
188 Effect.ignore,
189 )
190 : Effect.void;
191​
192/** @public Service construction is part of the canonical Effect module API. */
193export const make = Effect.gen(function* () {
194 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
195 const relayClient = yield* RelayClient.RelayClient;
196 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
197 const activeRef = yield* Ref.make<ActiveConnector | null>(null);
198 const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);
199 const recoveryRequests = yield* Queue.sliding<RelayManagedEndpointRuntimeConfig>(1);
200 const tunnelConnections = yield* Queue.sliding<void>(1);
201 const readinessChanges = yield* Queue.sliding<void>(1);
202 const reconcileSemaphore = yield* Semaphore.make(1);
203 const restartDelayRef = yield* Ref.make(0);
204 const linkStateSemaphore = yield* Semaphore.make(1);
205 const runtimeScope = yield* Effect.scope;
206 const installInFlightRef = yield* Ref.make(false);
207 const lastInstallFailureAtRef = yield* Ref.make<number | null>(null);
208 const prunedRef = yield* Ref.make(false);
209 const retryLoopRunningRef = yield* Ref.make(false);
210 const notReadyChecksBeforeRestartRef = yield* Ref.make(CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
211 // An explicit cloudflared transport in the environment is the user's choice.
212 const transportChosenByUser = process.env.TUNNEL_TRANSPORT_PROTOCOL !== undefined;
213 const http2Ref = yield* Ref.make(false);
214 const quicStallsRef = yield* Ref.make<ReadonlyArray<number>>([]);
215 let reconcileConfig: CloudManagedEndpointRuntime["Service"]["applyConfig"];
216​
217 const stopActive = Effect.gen(function* () {
218 const active = yield* Ref.getAndSet(activeRef, null);
219 yield* stopConnector(active);
220 });
221​
222 // Lives until connector exit and starts replacements; avoid nested lifetime spans.
223 const superviseConnector = Effect.fnUntraced(
224 function* (connector: ActiveConnector) {
225 const result = yield* Effect.result(connector.child.exitCode);
226 const activeAtExit = yield* Ref.get(activeRef);
227 if (
228 activeAtExit?.child.pid !== connector.child.pid ||
229 activeAtExit.configKey !== connector.configKey
230 ) {
231 return;
232 }
233 const uptimeMillis = (yield* Clock.currentTimeMillis) - connector.startedAtMillis;
234 // The delay runs before the semaphore so a user config change is never
235 // blocked behind it, and reconcileConfig re-checks the desired config
236 // afterwards.
237 const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
238 if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
239 return [0, 0];
240 }
241 return [
242 current,
243 current === 0
244 ? RELAY_RESTART_BACKOFF_BASE_MS
245 : Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
246 ];
247 });
248 if (restartDelayMillis > 0) {
249 yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
250 pid: Number(connector.child.pid),
251 uptimeMillis,
252 restartDelayMillis,
253 tunnelId: connector.config.tunnelId,
254 tunnelName: connector.config.tunnelName,
255 });
256 yield* Effect.sleep(Duration.millis(restartDelayMillis));
257 }
258 yield* reconcileSemaphore.withPermits(1)(
259 Effect.gen(function* () {
260 const active = yield* Ref.get(activeRef);
261 if (
262 active?.child.pid !== connector.child.pid ||
263 active.configKey !== connector.configKey
264 ) {
265 return;
266 }
267 yield* Ref.set(activeRef, null);
268 yield* stopConnector(connector);
269​
270 const desiredConfig = yield* Ref.get(desiredConfigRef);
271 if (
272 !desiredConfig ||
273 desiredConfig.providerKind !== "cloudflare_tunnel" ||
274 runtimeConfigKey(desiredConfig) !== connector.configKey
275 ) {
276 return;
277 }
278​
279 yield* Effect.logWarning("Relay client exited; restarting", {
280 pid: Number(connector.child.pid),
281 ...(Result.isSuccess(result)
282 ? { exitCode: Number(result.success) }
283 : { cause: result.failure }),
284 tunnelId: connector.config.tunnelId,
285 tunnelName: connector.config.tunnelName,
286 });
287 yield* Queue.offer(recoveryRequests, connector.config);
288 yield* reconcileConfig(desiredConfig);
289 }),
290 );
291 },
292 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
293 );
294​
295 // The new connector starts next to the old one on the same tunnel, and the
296 // old one stops only once the new one registers, so clients never see the
297 // relay lose this host during the swap.
298 const installPinnedRelayClient = Effect.gen(function* () {
299 if (yield* Ref.getAndSet(installInFlightRef, true)) return;
300 yield* Effect.logInfo("Installing the pinned relay client", {
301 version: RelayClient.CLOUDFLARED_VERSION,
302 });
303 yield* relayClient.install.pipe(
304 Effect.tap(() => Ref.set(lastInstallFailureAtRef, null)),
305 Effect.flatMap((installed) =>
306 reconcileSemaphore.withPermits(1)(
307 Effect.gen(function* () {
308 const desiredConfig = yield* Ref.get(desiredConfigRef);
309 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
310 const active = yield* Ref.get(activeRef);
311 // A self-updated binary in the pinned folder shares the installed path,
312 // so the version decides whether the running connector is current.
313 if (
314 active?.executable.executablePath === installed.executablePath &&
315 active.executable.version === installed.version
316 ) {
317 return;
318 }
319 // A fresh binary can fail its probe while a scanner holds it; restarting
320 // then would land on the same older binary, so leave it to the retry.
321 const resolved = yield* relayClient.resolve;
322 if (
323 resolved.status !== "available" ||
324 resolved.executablePath !== installed.executablePath ||
325 resolved.version !== installed.version
326 ) {
327 return;
328 }
329 yield* Effect.logInfo("Relay client installed; moving the connector to it", {
330 version: installed.version,
331 previousVersion: active?.executable.version,
332 });
333 const previous = yield* Ref.getAndSet(activeRef, null);
334 const status = yield* reconcileConfig(desiredConfig);
335 const next = yield* Ref.get(activeRef);
336 if (!next) {
337 yield* Effect.logWarning("Relay client did not start after the update", status);
338 // One that exited while detached was skipped by its supervisor, so
339 // ask for recovery like an exited connector.
340 const previousRunning = previous
341 ? yield* previous.child.isRunning.pipe(Effect.orElseSucceed(() => false))
342 : false;
343 if (previous && previousRunning) {
344 yield* Ref.set(activeRef, previous);
345 } else {
346 yield* stopConnector(previous);
347 yield* Queue.offer(recoveryRequests, desiredConfig);
348 }
349 return;
350 }
351 if (previous) {
352 yield* Deferred.await(next.registered).pipe(
353 Effect.ensuring(stopConnector(previous)),
354 Effect.forkIn(next.scope),
355 );
356 }
357 }),
358 ),
359 ),
360 Effect.catchTags({
361 RelayClientInstallError: (error) =>
362 Clock.currentTimeMillis.pipe(
363 Effect.flatMap((failedAt) => Ref.set(lastInstallFailureAtRef, failedAt)),
364 Effect.andThen(
365 Effect.logWarning("Could not install the pinned relay client", {
366 reason: error.reason,
367 message: error.message,
368 cause: error.cause,
369 }),
370 ),
371 ),
372 }),
373 Effect.ensuring(Ref.set(installInFlightRef, false)),
374 );
375 });
376​
377 const ensurePinnedRelayClient = Effect.gen(function* () {
378 const now = yield* Clock.currentTimeMillis;
379 const lastFailureAt = yield* Ref.get(lastInstallFailureAtRef);
380 if (lastFailureAt !== null && now - lastFailureAt < RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS) {
381 return;
382 }
383 yield* installPinnedRelayClient;
384 }).pipe(Effect.forkIn(runtimeScope), Effect.asVoid);
385​
386 // applyConfig returns early while an older connector is healthy, and some
387 // activations never retry a missing client, so one runtime loop covers both.
388 // It paces itself, so it skips the failure gate above.
389 const retryPinnedRelayClientInstall = Effect.gen(function* () {
390 while (true) {
391 yield* Effect.sleep(Duration.millis(RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS));
392 const desiredConfig = yield* Ref.get(desiredConfigRef);
393 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
394 // The pin can be on disk while an older connector still runs, or while none
395 // runs because a post-install probe failed; another install call then finds
396 // it and starts the connector.
397 const active = yield* Ref.get(activeRef);
398 if (active && !needsPinnedRelayClient(active.executable)) return;
399 yield* installPinnedRelayClient;
400 }
401 }).pipe(Effect.ensuring(Ref.set(retryLoopRunningRef, false)));
402​
403 const startPinnedRelayClientRetries = Effect.gen(function* () {
404 if (yield* Ref.getAndSet(retryLoopRunningRef, true)) return;
405 yield* Effect.forkIn(retryPinnedRelayClientInstall, runtimeScope);
406 });
407​
408 // Registration retries can last for the connector lifetime; keep this loop untraced.
409 const watchConnectorRegistration = Effect.fnUntraced(
410 function* (connector: ActiveConnector) {
411 yield* Effect.sleep(CONNECTOR_REGISTRATION_TIMEOUT);
412 if (yield* Deferred.isDone(connector.registered)) return true;
413 yield* Effect.logWarning(
414 "Relay client has not registered a tunnel connection; requesting recovery",
415 {
416 pid: Number(connector.child.pid),
417 tunnelId: connector.config.tunnelId,
418 tunnelName: connector.config.tunnelName,
419 },
420 );
421 yield* Queue.offer(recoveryRequests, connector.config);
422 return false;
423 },
424 Effect.repeat({ until: (connected) => connected }),
425 );
426​
427 // Only an explicit 503 counts: a failed request says nothing about the
428 // Readiness polling runs for the connector lifetime; keep this loop untraced.
429 const watchConnectorReadiness = Effect.fnUntraced(function* (connector: ActiveConnector) {
430 const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;
431 let notReadyChecks = 0;
432 let lastReady: boolean | null = null;
433 while (true) {
434 yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);
435 const status = yield* httpClient.get(readyUrl).pipe(
436 Effect.map((response) => response.status),
437 Effect.scoped,
438 Effect.withTracerEnabled(false),
439 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
440 Effect.orElseSucceed(() => Option.none<number>()),
441 );
442 if (Option.isNone(status)) continue;
443 if (status.value === 200 || status.value === 503) {
444 const ready = status.value === 200;
445 if (ready !== lastReady) yield* Queue.offer(readinessChanges, undefined);
446 lastReady = ready;
447 }
448 if (status.value === 200) {
449 notReadyChecks = 0;
450 yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
451 continue;
452 }
453 if (status.value !== 503) continue;
454 notReadyChecks += 1;
455 const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);
456 if (notReadyChecks < threshold) continue;
457 notReadyChecks = 0;
458 yield* Ref.set(
459 notReadyChecksBeforeRestartRef,
460 Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),
461 );
462 yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {
463 pid: Number(connector.child.pid),
464 notReadyChecks: threshold,
465 tunnelId: connector.config.tunnelId,
466 tunnelName: connector.config.tunnelName,
467 });
468 yield* connector.child.kill().pipe(Effect.ignore);
469 }
470 });
471​
472 const switchToHttp2 = Effect.fnUntraced(function* (connector: ActiveConnector) {
473 const active = yield* Ref.get(activeRef);
474 const desiredConfig = yield* Ref.get(desiredConfigRef);
475 if ((yield* Ref.get(http2Ref)) || active !== connector || !desiredConfig) return;
476 yield* Ref.set(http2Ref, true);
477 yield* Effect.logWarning("Relay client keeps losing QUIC connections; switching to HTTP/2", {
478 pid: Number(connector.child.pid),
479 tunnelId: connector.config.tunnelId,
480 tunnelName: connector.config.tunnelName,
481 });
482 // Shutdown must not interrupt cleanup after active ownership is cleared.
483 yield* Effect.uninterruptible(stopActive);
484 const status = yield* reconcileConfig(desiredConfig);
485 // A failed spawn has no supervisor to request recovery.
486 if (status.status !== "running") {
487 yield* Queue.offer(recoveryRequests, desiredConfig);
488 }
489 }, reconcileSemaphore.withPermits(1));
490​
491 const noteQuicStall = Effect.fnUntraced(function* (connector: ActiveConnector) {
492 if (transportChosenByUser || (yield* Ref.get(http2Ref))) return;
493 const now = yield* Clock.currentTimeMillis;
494 if ((yield* Ref.get(activeRef)) !== connector) return;
495 const stalls = yield* Ref.updateAndGet(quicStallsRef, (previous) => [
496 ...previous.filter((at) => now - at < QUIC_STALL_WINDOW_MS),
497 now,
498 ]);
499 if (stalls.length < QUIC_STALLS_BEFORE_HTTP2) return;
500 // Stopping the connector interrupts the output observer that called this.
501 yield* Effect.forkIn(switchToHttp2(connector), runtimeScope);
502 });
503​
504 const observeConnectorOutput = (connector: ActiveConnector) => {
505 let rejectedRegistrations = 0;
506​
507 return connector.child.all.pipe(
508 Stream.decodeText(),
509 Stream.splitLines,
510 Stream.map((line) => line.trim()),
511 Stream.filter((line) => line.length > 0),
512 Stream.runForEach((line) => {
513 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
514 const attributes = {
515 pid: Number(connector.child.pid),
516 tunnelId: connector.config.tunnelId,
517 tunnelName: connector.config.tunnelName,
518 output,
519 };
520 switch (classifyRelayClientOutput(line)) {
521 case "connected":
522 rejectedRegistrations = 0;
523 return Deferred.succeed(connector.registered, undefined).pipe(
524 Effect.andThen(
525 Ref.set(connector.protocol, RELAY_CLIENT_PROTOCOL.exec(line)?.[1] ?? null),
526 ),
527 Effect.andThen(
528 Effect.logInfo("Relay client tunnel connection registered", attributes),
529 ),
530 Effect.andThen(Queue.offer(tunnelConnections, undefined)),
531 Effect.andThen(Queue.offer(readinessChanges, undefined)),
532 Effect.andThen(
533 RelayClient.isPinnedManagedRelayClient(connector.executable)
534 ? Ref.getAndSet(prunedRef, true).pipe(
535 Effect.flatMap((pruned) =>
536 pruned ? Effect.void : relayClient.pruneManagedVersions,
537 ),
538 )
539 : Effect.void,
540 ),
541 Effect.asVoid,
542 );
543 case "warning":
544 if (/\btimeout: no recent network activity\b/u.test(line)) {
545 return noteQuicStall(connector).pipe(
546 Effect.andThen(
547 Effect.logWarning("Relay client reported a transport warning", attributes),
548 ),
549 );
550 }
551 if (isRejectedRelayClientTunnelOutput(line)) {
552 rejectedRegistrations += 1;
553 if (rejectedRegistrations >= TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY) {
554 rejectedRegistrations = 0;
555 return Effect.logWarning(
556 "Relay client tunnel was rejected; requesting recovery",
557 attributes,
558 ).pipe(
559 Effect.andThen(Queue.offer(recoveryRequests, connector.config)),
560 Effect.asVoid,
561 );
562 }
563 }
564 return Effect.logWarning("Relay client reported a transport warning", attributes);
565 case "debug": {
566 const metricsAddress = RELAY_CLIENT_METRICS_LINE.exec(line)?.[1];
567 return metricsAddress
568 ? Deferred.succeed(connector.metricsAddress, metricsAddress).pipe(
569 Effect.andThen(Effect.logDebug("Relay client output", attributes)),
570 )
571 : Effect.logDebug("Relay client output", attributes);
572 }
573 }
574 }),
575 Effect.catchCause((cause) =>
576 Effect.logWarning("Relay client output observer failed", {
577 cause,
578 pid: Number(connector.child.pid),
579 tunnelId: connector.config.tunnelId,
580 tunnelName: connector.config.tunnelName,
581 }),
582 ),
583 );
584 };
585​
586 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
587 if (!config || config.providerKind !== "cloudflare_tunnel") {
588 yield* stopActive;
589 return config
590 ? { status: "unsupported", providerKind: config.providerKind }
591 : { status: "disabled" };
592 }
593​
594 const nextConfigKey = runtimeConfigKey(config);
595 const active = yield* Ref.get(activeRef);
596 if (active?.configKey === nextConfigKey) {
597 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
598 if (isRunning) {
599 return {
600 status: "running",
601 providerKind: "cloudflare_tunnel",
602 pid: Number(active.child.pid),
603 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
604 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
605 } satisfies CloudManagedEndpointRuntimeStatus;
606 }
607 }
608​
609 yield* stopActive;
610​
611 const executable = yield* relayClient.resolve;
612 if (needsPinnedRelayClient(executable)) {
613 yield* ensurePinnedRelayClient;
614 yield* startPinnedRelayClientRetries;
615 }
616 if (executable.status !== "available") {
617 return {
618 status: "failed",
619 providerKind: "cloudflare_tunnel",
620 failure: executable.status === "unsupported" ? "unsupported-platform" : "not-installed",
621 reason:
622 executable.status === "unsupported"
623 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
624 : "The relay client is not installed.",
625 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
626 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
627 } satisfies CloudManagedEndpointRuntimeStatus;
628 }
629​
630 const http2 = yield* Ref.get(http2Ref);
631 const connectorScope = yield* Scope.make("sequential");
632 const child = yield* spawner
633 .spawn(
634 ChildProcess.make(
635 executable.executablePath,
636 [
637 "tunnel",
638 "--no-autoupdate",
639 "--loglevel",
640 "info",
641 "--output",
642 "default",
643 "--metrics",
644 "127.0.0.1:0",
645 ...(http2 ? ["--protocol", "http2"] : []),
646 "run",
647 ],
648 {
649 detached: false,
650 env: {
651 ...process.env,
652 TUNNEL_TOKEN: config.connectorToken,
653 },
654 shell: false,
655 stderr: "pipe",
656 stdout: "pipe",
657 },
658 ),
659 )
660 .pipe(
661 Effect.provideService(Scope.Scope, connectorScope),
662 Effect.tap((child) =>
663 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
664 pid: Number(child.pid),
665 source: executable.source,
666 version: executable.version,
667 protocol: http2 ? "http2" : "auto",
668 tunnelId: config.tunnelId,
669 tunnelName: config.tunnelName,
670 }),
671 ),
672 Effect.catch((cause) =>
673 Effect.logWarning("Failed to start relay client", {
674 cause,
675 tunnelId: config.tunnelId,
676 tunnelName: config.tunnelName,
677 }).pipe(
678 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
679 Effect.as({
680 status: "failed",
681 providerKind: "cloudflare_tunnel",
682 failure: "spawn-failed",
683 reason: String(cause),
684 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
685 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
686 } satisfies CloudManagedEndpointRuntimeStatus),
687 ),
688 ),
689 );
690​
691 if ("status" in child && child.status === "failed") {
692 return child;
693 }
694​
695 if (!("status" in child)) {
696 const connector = {
697 child,
698 executable,
699 scope: connectorScope,
700 configKey: nextConfigKey,
701 config,
702 startedAtMillis: yield* Clock.currentTimeMillis,
703 registered: yield* Deferred.make<void>(),
704 metricsAddress: yield* Deferred.make<string>(),
705 protocol: yield* Ref.make<string | null>(null),
706 } satisfies ActiveConnector;
707 yield* Ref.set(activeRef, connector);
708 yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
709 yield* Effect.forkIn(superviseConnector(connector), connectorScope);
710 yield* Effect.forkIn(watchConnectorRegistration(connector), connectorScope);
711 yield* Effect.forkIn(watchConnectorReadiness(connector), connectorScope);
712 return {
713 status: "running",
714 providerKind: "cloudflare_tunnel",
715 pid: Number(child.pid),
716 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
717 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
718 } satisfies CloudManagedEndpointRuntimeStatus;
719 }
720​
721 return {
722 status: "failed",
723 providerKind: "cloudflare_tunnel",
724 failure: "spawn-failed",
725 reason: "Relay client did not start.",
726 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
727 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
728 } satisfies CloudManagedEndpointRuntimeStatus;
729 });
730​
731 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
732 (config: RelayManagedEndpointRuntimeConfig | null) =>
733 reconcileSemaphore.withPermits(1)(
734 Effect.gen(function* () {
735 // A real config change starts over with a fresh backoff. Recovery
736 // that hands back the same tunnel and token must keep the delay, or
737 // a crash-looping connector respawns on every recovery round trip.
738 const desired = yield* Ref.get(desiredConfigRef);
739 const unchanged =
740 desired !== null &&
741 config !== null &&
742 runtimeConfigKey(desired) === runtimeConfigKey(config);
743 if (!unchanged) {
744 yield* Ref.set(restartDelayRef, 0);
745 }
746 yield* Ref.set(desiredConfigRef, config);
747 return yield* reconcileConfig(config);
748 }),
749 ),
750 );
751​
752 const readMetrics = <S extends Schema.Decoder<unknown>>(url: string, schema: S) =>
753 httpClient.get(url).pipe(
754 Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
755 Effect.scoped,
756 Effect.withTracerEnabled(false),
757 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
758 Effect.map(Option.getOrNull),
759 Effect.orElseSucceed(() => null),
760 );
761​
762 const inspectConnector = Effect.gen(function* () {
763 const active = yield* Ref.get(activeRef);
764 if (!active || !(yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false)))) {
765 return null;
766 }
767 const protocol = yield* Ref.get(active.protocol);
768 if (!(yield* Deferred.isDone(active.metricsAddress))) {
769 return { readyConnections: null, hostname: null, protocol } satisfies ConnectorFacts;
770 }
771 const metricsUrl = `http://${yield* Deferred.await(active.metricsAddress)}`;
772 const [ready, config] = yield* Effect.all(
773 [
774 readMetrics(`${metricsUrl}/ready`, ConnectorReadyBody),
775 readMetrics(`${metricsUrl}/config`, ConnectorConfigBody),
776 ],
777 { concurrency: 2 },
778 );
779 return {
780 readyConnections: ready?.readyConnections ?? null,
781 hostname: config?.config.ingress?.find((rule) => rule.hostname)?.hostname ?? null,
782 protocol,
783 } satisfies ConnectorFacts;
784 });
785​
786 const runtime = CloudManagedEndpointRuntime.of({
787 applyConfig,
788 inspectConnector,
789 readinessChanged: Stream.fromQueue(readinessChanges),
790 recoveryRequests: Stream.fromQueue(recoveryRequests),
791 requestRecovery: (config) => Queue.offer(recoveryRequests, config).pipe(Effect.asVoid),
792 tunnelConnected: Stream.fromQueue(tunnelConnections),
793 withLinkStateLock: linkStateSemaphore.withPermits(1),
794 });
795​
796 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
797 return runtime;
798});
799​
800export const layer = Layer.effect(CloudManagedEndpointRuntime, make);