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