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