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

ManagedEndpointRuntime.ts

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