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

ManagedEndpointRuntime.ts

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