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

ManagedEndpointRuntime.ts

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