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