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 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>;
67}
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 );
105}
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";
115}
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 );
130}
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";
140}
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 });
149}
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 const superviseConnector = (connector: ActiveConnector) =>
189 Effect.gen(function* () {
190 const result = yield* Effect.result(connector.child.exitCode);
191 const activeAtExit = yield* Ref.get(activeRef);
192 if (
193 activeAtExit?.child.pid !== connector.child.pid ||
194 activeAtExit.configKey !== connector.configKey
195 ) {
196 return;
197 }
198 const uptimeMillis = (yield* Clock.currentTimeMillis) - connector.startedAtMillis;
199 // The delay runs before the semaphore so a user config change is never
200 // blocked behind it, and reconcileConfig re-checks the desired config
201 // afterwards.
202 const restartDelayMillis = yield* Ref.modify(restartDelayRef, (current) => {
203 if (uptimeMillis >= RELAY_RESTART_STABLE_UPTIME_MS) {
204 return [0, 0];
205 }
206 return [
207 current,
208 current === 0
209 ? RELAY_RESTART_BACKOFF_BASE_MS
210 : Math.min(current * 2, RELAY_RESTART_BACKOFF_MAX_MS),
211 ];
212 });
213 if (restartDelayMillis > 0) {
214 yield* Effect.logWarning("Relay client is crash-looping; delaying restart", {
215 pid: Number(connector.child.pid),
216 uptimeMillis,
217 restartDelayMillis,
218 tunnelId: connector.config.tunnelId,
219 tunnelName: connector.config.tunnelName,
220 });
221 yield* Effect.sleep(Duration.millis(restartDelayMillis));
222 }
223 yield* reconcileSemaphore.withPermits(1)(
224 Effect.gen(function* () {
225 const active = yield* Ref.get(activeRef);
226 if (
227 active?.child.pid !== connector.child.pid ||
228 active.configKey !== connector.configKey
229 ) {
230 return;
231 }
232 yield* Ref.set(activeRef, null);
233 yield* stopConnector(connector);
234
235 const desiredConfig = yield* Ref.get(desiredConfigRef);
236 if (
237 !desiredConfig ||
238 desiredConfig.providerKind !== "cloudflare_tunnel" ||
239 runtimeConfigKey(desiredConfig) !== connector.configKey
240 ) {
241 return;
242 }
243
244 yield* Effect.logWarning("Relay client exited; restarting", {
245 pid: Number(connector.child.pid),
246 ...(Result.isSuccess(result)
247 ? { exitCode: Number(result.success) }
248 : { cause: result.failure }),
249 tunnelId: connector.config.tunnelId,
250 tunnelName: connector.config.tunnelName,
251 });
252 yield* Queue.offer(recoveryRequests, connector.config);
253 yield* reconcileConfig(desiredConfig);
254 }),
255 );
256 }).pipe(
257 Effect.catchCause((cause) => Effect.logWarning("Relay client supervisor failed", { cause })),
258 );
259
260 // The new connector starts next to the old one on the same tunnel, and the
261 // old one stops only once the new one registers, so clients never see the
262 // relay lose this host during the swap.
263 const installPinnedRelayClient = Effect.gen(function* () {
264 if (yield* Ref.getAndSet(installInFlightRef, true)) return;
265 yield* Effect.logInfo("Installing the pinned relay client", {
266 version: RelayClient.CLOUDFLARED_VERSION,
267 });
268 yield* relayClient.install.pipe(
269 Effect.tap(() => Ref.set(lastInstallFailureAtRef, null)),
270 Effect.flatMap((installed) =>
271 reconcileSemaphore.withPermits(1)(
272 Effect.gen(function* () {
273 const desiredConfig = yield* Ref.get(desiredConfigRef);
274 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
275 const active = yield* Ref.get(activeRef);
276 // A self-updated binary in the pinned folder shares the installed path,
277 // so the version decides whether the running connector is current.
278 if (
279 active?.executable.executablePath === installed.executablePath &&
280 active.executable.version === installed.version
281 ) {
282 return;
283 }
284 // A fresh binary can fail its probe while a scanner holds it; restarting
285 // then would land on the same older binary, so leave it to the retry.
286 const resolved = yield* relayClient.resolve;
287 if (
288 resolved.status !== "available" ||
289 resolved.executablePath !== installed.executablePath ||
290 resolved.version !== installed.version
291 ) {
292 return;
293 }
294 yield* Effect.logInfo("Relay client installed; moving the connector to it", {
295 version: installed.version,
296 previousVersion: active?.executable.version,
297 });
298 const previous = yield* Ref.getAndSet(activeRef, null);
299 const status = yield* reconcileConfig(desiredConfig);
300 const next = yield* Ref.get(activeRef);
301 if (!next) {
302 yield* Effect.logWarning("Relay client did not start after the update", status);
303 // One that exited while detached was skipped by its supervisor, so
304 // 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 if (previous) {
317 yield* Deferred.await(next.registered).pipe(
318 Effect.ensuring(stopConnector(previous)),
319 Effect.forkIn(next.scope),
320 );
321 }
322 }),
323 ),
324 ),
325 Effect.catchTags({
326 RelayClientInstallError: (error) =>
327 Clock.currentTimeMillis.pipe(
328 Effect.flatMap((failedAt) => Ref.set(lastInstallFailureAtRef, failedAt)),
329 Effect.andThen(
330 Effect.logWarning("Could not install the pinned relay client", {
331 reason: error.reason,
332 message: error.message,
333 cause: error.cause,
334 }),
335 ),
336 ),
337 }),
338 Effect.ensuring(Ref.set(installInFlightRef, false)),
339 );
340 });
341
342 const ensurePinnedRelayClient = Effect.gen(function* () {
343 const now = yield* Clock.currentTimeMillis;
344 const lastFailureAt = yield* Ref.get(lastInstallFailureAtRef);
345 if (lastFailureAt !== null && now - lastFailureAt < RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS) {
346 return;
347 }
348 yield* installPinnedRelayClient;
349 }).pipe(Effect.forkIn(runtimeScope), Effect.asVoid);
350
351 // applyConfig returns early while an older connector is healthy, and some
352 // activations never retry a missing client, so one runtime loop covers both.
353 // It paces itself, so it skips the failure gate above.
354 const retryPinnedRelayClientInstall = Effect.gen(function* () {
355 while (true) {
356 yield* Effect.sleep(Duration.millis(RELAY_CLIENT_INSTALL_RETRY_INTERVAL_MS));
357 const desiredConfig = yield* Ref.get(desiredConfigRef);
358 if (!desiredConfig || desiredConfig.providerKind !== "cloudflare_tunnel") return;
359 // The pin can be on disk while an older connector still runs, or while none
360 // runs because a post-install probe failed; another install call then finds
361 // it and starts the connector.
362 const active = yield* Ref.get(activeRef);
363 if (active && !needsPinnedRelayClient(active.executable)) return;
364 yield* installPinnedRelayClient;
365 }
366 }).pipe(Effect.ensuring(Ref.set(retryLoopRunningRef, false)));
367
368 const startPinnedRelayClientRetries = Effect.gen(function* () {
369 if (yield* Ref.getAndSet(retryLoopRunningRef, true)) return;
370 yield* Effect.forkIn(retryPinnedRelayClientInstall, runtimeScope);
371 });
372
373 const watchConnectorRegistration = (connector: ActiveConnector) =>
374 Effect.gen(function* () {
375 yield* Effect.sleep(CONNECTOR_REGISTRATION_TIMEOUT);
376 if (yield* Deferred.isDone(connector.registered)) return true;
377 yield* Effect.logWarning(
378 "Relay client has not registered a tunnel connection; requesting recovery",
379 {
380 pid: Number(connector.child.pid),
381 tunnelId: connector.config.tunnelId,
382 tunnelName: connector.config.tunnelName,
383 },
384 );
385 yield* Queue.offer(recoveryRequests, connector.config);
386 return false;
387 }).pipe(Effect.repeat({ until: (connected) => connected }));
388
389 // Only an explicit 503 counts: a failed request says nothing about the
390 const watchConnectorReadiness = (connector: ActiveConnector) =>
391 Effect.gen(function* () {
392 const readyUrl = `http://${yield* Deferred.await(connector.metricsAddress)}/ready`;
393 let notReadyChecks = 0;
394 while (true) {
395 yield* Effect.sleep(CONNECTOR_READINESS_INTERVAL);
396 const status = yield* httpClient.get(readyUrl).pipe(
397 Effect.map((response) => response.status),
398 Effect.scoped,
399 Effect.withTracerEnabled(false),
400 Effect.timeoutOption(CONNECTOR_READINESS_REQUEST_TIMEOUT),
401 Effect.orElseSucceed(() => Option.none<number>()),
402 );
403 if (Option.isNone(status)) continue;
404 if (status.value === 200) {
405 notReadyChecks = 0;
406 yield* Ref.set(notReadyChecksBeforeRestartRef, CONNECTOR_NOT_READY_CHECKS_BEFORE_RESTART);
407 continue;
408 }
409 if (status.value !== 503) continue;
410 notReadyChecks += 1;
411 const threshold = yield* Ref.get(notReadyChecksBeforeRestartRef);
412 if (notReadyChecks < threshold) continue;
413 notReadyChecks = 0;
414 yield* Ref.set(
415 notReadyChecksBeforeRestartRef,
416 Math.min(threshold * 2, CONNECTOR_NOT_READY_CHECKS_MAX),
417 );
418 yield* Effect.logWarning("Relay client has no tunnel connection; restarting it", {
419 pid: Number(connector.child.pid),
420 notReadyChecks: threshold,
421 tunnelId: connector.config.tunnelId,
422 tunnelName: connector.config.tunnelName,
423 });
424 yield* connector.child.kill().pipe(Effect.ignore);
425 }
426 });
427
428 const observeConnectorOutput = (connector: ActiveConnector) => {
429 let rejectedRegistrations = 0;
430
431 return connector.child.all.pipe(
432 Stream.decodeText(),
433 Stream.splitLines,
434 Stream.map((line) => line.trim()),
435 Stream.filter((line) => line.length > 0),
436 Stream.runForEach((line) => {
437 const output = line.replaceAll(connector.config.connectorToken, "<redacted>");
438 const attributes = {
439 pid: Number(connector.child.pid),
440 tunnelId: connector.config.tunnelId,
441 tunnelName: connector.config.tunnelName,
442 output,
443 };
444 switch (classifyRelayClientOutput(line)) {
445 case "connected":
446 rejectedRegistrations = 0;
447 return Deferred.succeed(connector.registered, undefined).pipe(
448 Effect.andThen(
449 Effect.logInfo("Relay client tunnel connection registered", attributes),
450 ),
451 Effect.andThen(Queue.offer(tunnelConnections, undefined)),
452 Effect.andThen(
453 RelayClient.isPinnedManagedRelayClient(connector.executable)
454 ? Ref.getAndSet(prunedRef, true).pipe(
455 Effect.flatMap((pruned) =>
456 pruned ? Effect.void : relayClient.pruneManagedVersions,
457 ),
458 )
459 : Effect.void,
460 ),
461 Effect.asVoid,
462 );
463 case "warning":
464 if (isRejectedRelayClientTunnelOutput(line)) {
465 rejectedRegistrations += 1;
466 if (rejectedRegistrations >= TUNNEL_AUTHORIZATION_FAILURES_BEFORE_RECOVERY) {
467 rejectedRegistrations = 0;
468 return Effect.logWarning(
469 "Relay client tunnel was rejected; requesting recovery",
470 attributes,
471 ).pipe(
472 Effect.andThen(Queue.offer(recoveryRequests, connector.config)),
473 Effect.asVoid,
474 );
475 }
476 }
477 return Effect.logWarning("Relay client reported a transport warning", attributes);
478 case "debug": {
479 const metricsAddress = RELAY_CLIENT_METRICS_LINE.exec(line)?.[1];
480 return metricsAddress
481 ? Deferred.succeed(connector.metricsAddress, metricsAddress).pipe(
482 Effect.andThen(Effect.logDebug("Relay client output", attributes)),
483 )
484 : Effect.logDebug("Relay client output", attributes);
485 }
486 }
487 }),
488 Effect.catchCause((cause) =>
489 Effect.logWarning("Relay client output observer failed", {
490 cause,
491 pid: Number(connector.child.pid),
492 tunnelId: connector.config.tunnelId,
493 tunnelName: connector.config.tunnelName,
494 }),
495 ),
496 );
497 };
498
499 reconcileConfig = Effect.fn("CloudManagedEndpointRuntime.reconcileConfig")(function* (config) {
500 if (!config || config.providerKind !== "cloudflare_tunnel") {
501 yield* stopActive;
502 return config
503 ? { status: "unsupported", providerKind: config.providerKind }
504 : { status: "disabled" };
505 }
506
507 const nextConfigKey = runtimeConfigKey(config);
508 const active = yield* Ref.get(activeRef);
509 if (active?.configKey === nextConfigKey) {
510 const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));
511 if (isRunning) {
512 return {
513 status: "running",
514 providerKind: "cloudflare_tunnel",
515 pid: Number(active.child.pid),
516 ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),
517 ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),
518 } satisfies CloudManagedEndpointRuntimeStatus;
519 }
520 }
521
522 yield* stopActive;
523
524 const executable = yield* relayClient.resolve;
525 if (needsPinnedRelayClient(executable)) {
526 yield* ensurePinnedRelayClient;
527 yield* startPinnedRelayClientRetries;
528 }
529 if (executable.status !== "available") {
530 return {
531 status: "failed",
532 providerKind: "cloudflare_tunnel",
533 failure: executable.status === "unsupported" ? "unsupported-platform" : "not-installed",
534 reason:
535 executable.status === "unsupported"
536 ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`
537 : "The relay client is not installed.",
538 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
539 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
540 } satisfies CloudManagedEndpointRuntimeStatus;
541 }
542
543 const connectorScope = yield* Scope.make("sequential");
544 const child = yield* spawner
545 .spawn(
546 ChildProcess.make(
547 executable.executablePath,
548 [
549 "tunnel",
550 "--no-autoupdate",
551 "--loglevel",
552 "info",
553 "--output",
554 "default",
555 "--metrics",
556 "127.0.0.1:0",
557 "run",
558 ],
559 {
560 detached: false,
561 env: {
562 ...process.env,
563 TUNNEL_TOKEN: config.connectorToken,
564 },
565 shell: false,
566 stderr: "pipe",
567 stdout: "pipe",
568 },
569 ),
570 )
571 .pipe(
572 Effect.provideService(Scope.Scope, connectorScope),
573 Effect.tap((child) =>
574 Effect.logInfo("Relay client process started; waiting for tunnel connection", {
575 pid: Number(child.pid),
576 source: executable.source,
577 version: executable.version,
578 tunnelId: config.tunnelId,
579 tunnelName: config.tunnelName,
580 }),
581 ),
582 Effect.catch((cause) =>
583 Effect.logWarning("Failed to start relay client", {
584 cause,
585 tunnelId: config.tunnelId,
586 tunnelName: config.tunnelName,
587 }).pipe(
588 Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),
589 Effect.as({
590 status: "failed",
591 providerKind: "cloudflare_tunnel",
592 failure: "spawn-failed",
593 reason: String(cause),
594 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
595 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
596 } satisfies CloudManagedEndpointRuntimeStatus),
597 ),
598 ),
599 );
600
601 if ("status" in child && child.status === "failed") {
602 return child;
603 }
604
605 if (!("status" in child)) {
606 const connector = {
607 child,
608 executable,
609 scope: connectorScope,
610 configKey: nextConfigKey,
611 config,
612 startedAtMillis: yield* Clock.currentTimeMillis,
613 registered: yield* Deferred.make<void>(),
614 metricsAddress: yield* Deferred.make<string>(),
615 } satisfies ActiveConnector;
616 yield* Ref.set(activeRef, connector);
617 yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);
618 yield* Effect.forkIn(superviseConnector(connector), connectorScope);
619 yield* Effect.forkIn(watchConnectorRegistration(connector), connectorScope);
620 yield* Effect.forkIn(watchConnectorReadiness(connector), connectorScope);
621 return {
622 status: "running",
623 providerKind: "cloudflare_tunnel",
624 pid: Number(child.pid),
625 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
626 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
627 } satisfies CloudManagedEndpointRuntimeStatus;
628 }
629
630 return {
631 status: "failed",
632 providerKind: "cloudflare_tunnel",
633 failure: "spawn-failed",
634 reason: "Relay client did not start.",
635 ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),
636 ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),
637 } satisfies CloudManagedEndpointRuntimeStatus;
638 });
639
640 const applyConfig = Effect.fn("CloudManagedEndpointRuntime.applyConfig")(
641 (config: RelayManagedEndpointRuntimeConfig | null) =>
642 reconcileSemaphore.withPermits(1)(
643 Effect.gen(function* () {
644 // A real config change starts over with a fresh backoff. Recovery
645 // that hands back the same tunnel and token must keep the delay, or
646 // a crash-looping connector respawns on every recovery round trip.
647 const desired = yield* Ref.get(desiredConfigRef);
648 const unchanged =
649 desired !== null &&
650 config !== null &&
651 runtimeConfigKey(desired) === runtimeConfigKey(config);
652 if (!unchanged) {
653 yield* Ref.set(restartDelayRef, 0);
654 }
655 yield* Ref.set(desiredConfigRef, config);
656 return yield* reconcileConfig(config);
657 }),
658 ),
659 );
660
661 const runtime = CloudManagedEndpointRuntime.of({
662 applyConfig,
663 recoveryRequests: Stream.fromQueue(recoveryRequests),
664 requestRecovery: (config) => Queue.offer(recoveryRequests, config).pipe(Effect.asVoid),
665 tunnelConnected: Stream.fromQueue(tunnelConnections),
666 withLinkStateLock: linkStateSemaphore.withPermits(1),
667 });
668
669 yield* Effect.addFinalizer(() => runtime.applyConfig(null));
670 return runtime;
671});
672
673export const layer = Layer.effect(CloudManagedEndpointRuntime, make);