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

supervisor.ts

1,282 lines46.3 KB

1import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Fiber from "effect/Fiber";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Random from "effect/Random";
12import * as Ref from "effect/Ref";
13import * as Scope from "effect/Scope";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import * as Tracer from "effect/Tracer";
17​
18import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
19import * as Connectivity from "./connectivity.ts";
20import * as ConnectionDriver from "./driver.ts";
21import {
22 type ConnectionAttemptError,
23 type ConnectionTarget,
24 ConnectionTransientError,
25 type NetworkStatus,
26 type PreparedConnection,
27 type SupervisorConnectionState,
28} from "./model.ts";
29import * as RpcSession from "../rpc/session.ts";
30import { safeErrorLogAttributes } from "../errors/safeLog.ts";
31import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
32import * as ConnectionWakeups from "./wakeups.ts";
33import {
34 connectionRouteId,
35 connectionRouteKind,
36 connectionRoutes,
37 type ConnectionRouteKind,
38 entryWithRoutes,
39 insertRoute,
40 type ReportedEndpoint,
41} from "./routes.ts";
42​
43const RETRY_BASE_DELAY_MS = 1_000;
44const RETRY_MAX_DELAY_MS = 300_000;
45const SESSION_LOSS_RETRY_DELAY_MS = 250;
46// A cold server with a large database can take longer than 15 seconds to
47// answer, and that is not a reason to drop a working connection.
48const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
49const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_TIMEOUT);
50const synchronizationTimeout = Duration.fromInputUnsafe("75 seconds");
51const CONNECTION_PROBE_TIMEOUT = "15 seconds";
52const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
53// After a long suspension pooled connections are often dead too, so the host
54// check can hang with the socket. A replacement is cheaper than the wait.
55const LONG_RESUME_PROBE_TIMEOUT = "1500 millis";
56// A probe still unanswered this long checks the host with a fresh request. If
57// the host answers while the socket stays silent, the socket is dead.
58const SILENT_SOCKET_CHECK_AFTER = "500 millis";
59const SILENT_SOCKET_RECHECK_EVERY = "1 second";
60const FRAME_CHECK_EVERY = "100 millis";
61// Off the LAN one lost packet can stall a live socket for a second, so a remote
62// socket must stay silent this long, except after a long resume. It must end
63// before QUICK_CONNECTION_PROBE_TIMEOUT so a resume replaces a silent socket
64// instead of timing out.
65const REMOTE_SILENT_SOCKET_AFTER = "2500 millis";
66const BACKOFF_RESET_AFTER_MS = 30_000;
67const BETTER_ROUTE_CHECK_INTERVAL_MS = 60_000;
68// Each check of a dead route can wait out the full probe timeout, so a route
69// that keeps failing is checked half as often each time, until the network
70// changes and it may answer again.
71const SILENT_ROUTE_BACKOFF_MAX_MS = 1_800_000;
72// A better route that answered the check but then failed to connect is not
73// tried again for this long, so a flaky LAN cannot bounce the connection.
74const BETTER_ROUTE_COOLDOWN_MS = 300_000;
75​
76interface SupervisorIntent {
77 readonly desired: boolean;
78 readonly network: NetworkStatus;
80​
81type SupervisorSignal =
82 | { readonly _tag: "ConnectRequested" }
83 | { readonly _tag: "DisconnectRequested" }
84 | { readonly _tag: "RetryRequested" }
85 | { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
86 | { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup }
87 | { readonly _tag: "BetterRouteAvailable"; readonly routeId: string };
88​
89interface PendingRetryTrace {
90 readonly previousAttempt: Tracer.Span;
91 readonly failureCount: number;
92 readonly delayMs: number;
93 readonly reason: ConnectionAttemptError["reason"];
95​
96type ConnectedLease = ConnectionDriver.EnvironmentConnectionLease & {
97 readonly activeRoute: ConnectionRoute | undefined;
98};
99​
100interface TracedAttemptFailure {
101 readonly error: ConnectionAttemptError;
102 readonly attemptSpan: Option.Option<Tracer.Span>;
104​
105type AttemptOutcome =
106 | {
107 readonly _tag: "Interrupted";
108 readonly established: boolean;
109 readonly stable: boolean;
110 readonly resetRetry: boolean;
111 }
112 | {
113 readonly _tag: "Failure";
114 readonly established: boolean;
115 readonly stable: boolean;
116 readonly failure: TracedAttemptFailure;
117 };
118​
119type EstablishmentEvent =
120 | {
121 readonly _tag: "Completed";
122 readonly exit: Exit.Exit<
123 {
124 readonly attemptSpan: Option.Option<Tracer.Span>;
125 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
126 },
127 TracedAttemptFailure
128 >;
129 }
130 | { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
131 | { readonly _tag: "TimedOut" };
132​
133function exitUnlessInterrupted<A, E, R>(
134 effect: Effect.Effect<A, E, R>,
135): Effect.Effect<Exit.Exit<A, E>, never, R> {
136 return Effect.matchCauseEffect(effect, {
137 onFailure: (cause) =>
138 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),
139 onSuccess: (value) => Effect.succeed(Exit.succeed(value)),
140 });
142​
143export interface EnvironmentSupervisorOptions {
144 readonly initiallyDesired?: boolean;
145 readonly learnRoutes?: (input: {
146 readonly activeRoute: ConnectionRoute;
147 readonly reported: ReadonlyArray<ReportedEndpoint>;
148 }) => Effect.Effect<Option.Option<ConnectionCatalogEntry>>;
150​
151function retryDelayMs(failureCount: number, random: number): number {
152 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failureCount + 1));
153 return Math.round(ceiling / 2 + (ceiling / 2) * random);
155​
156interface SilentRoute {
157 readonly failures: number;
158 readonly until: bigint;
160​
161function backOffSilentRoute(previous: SilentRoute | undefined, now: bigint): SilentRoute {
162 const failures = (previous?.failures ?? 0) + 1;
163 const delayMs = Math.min(
164 SILENT_ROUTE_BACKOFF_MAX_MS,
165 BETTER_ROUTE_CHECK_INTERVAL_MS * 2 ** failures,
166 );
167 return { failures, until: now + BigInt(delayMs) * 1_000_000n };
169​
170function annotateTarget(target: ConnectionTarget) {
171 return Effect.annotateCurrentSpan({
172 "environment.id": target.environmentId,
173 "environment.label": target.label,
174 "environment.target.kind": target._tag,
175 });
177​
178function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
179 return {
180 desired: false,
181 network: intent.network,
182 phase: "available",
183 stage: null,
184 attempt: 0,
185 generation,
186 lastFailure: null,
187 retryAt: null,
188 };
190​
191function offlineState(
192 intent: SupervisorIntent,
193 generation: number,
194 attempt: number,
195 lastFailure: ConnectionAttemptError | null,
196): SupervisorConnectionState {
197 return {
198 desired: true,
199 network: intent.network,
200 phase: "offline",
201 stage: null,
202 attempt,
203 generation,
204 lastFailure,
205 retryAt: null,
206 };
208​
209function connectingState(
210 intent: SupervisorIntent,
211 generation: number,
212 attempt: number,
213 lastFailure: ConnectionAttemptError | null,
214 stage: SupervisorConnectionState["stage"] = "preparing",
215): SupervisorConnectionState {
216 return {
217 desired: true,
218 network: intent.network,
219 phase: "connecting",
220 stage,
221 attempt,
222 generation,
223 lastFailure,
224 retryAt: null,
225 };
227​
228function failureFromExit<A>(
229 target: ConnectionTarget,
230 exit: Exit.Exit<A, TracedAttemptFailure>,
231 established: boolean,
232 stable: boolean,
233): AttemptOutcome {
234 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
235 return { _tag: "Interrupted", established, stable, resetRetry: false };
236 }
237 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
238 if (typedFailure) {
239 return {
240 _tag: "Failure",
241 established,
242 stable,
243 failure: typedFailure.error,
244 };
245 }
246 return {
247 _tag: "Failure",
248 established,
249 stable,
250 failure: {
251 error: new ConnectionTransientError({
252 reason: "transport",
253 detail: `${target.label} connection failed unexpectedly.`,
254 }),
255 attemptSpan: Option.none(),
256 },
257 };
259​
260export class EnvironmentSupervisor extends Context.Service<
261 EnvironmentSupervisor,
262 {
263 readonly target: ConnectionTarget;
264 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
265 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
266 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
267 readonly connect: Effect.Effect<void>;
268 readonly disconnect: Effect.Effect<void>;
269 readonly retryNow: Effect.Effect<void>;
270 }
271>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
272​
273export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
274 entry: ConnectionCatalogEntry,
275 options?: EnvironmentSupervisorOptions,
276): Effect.fn.Return<
277 EnvironmentSupervisor["Service"],
278 never,
279 | Connectivity.Connectivity
280 | ConnectionDriver.ConnectionDriver
281 | Scope.Scope
282 | ConnectionWakeups.ConnectionWakeups
283> {
284 const target = entry.target;
285 const usesRelay = connectionRoutes(entry).some(
286 (route) => route.target._tag === "RelayConnectionTarget",
287 );
288 const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
289 usesRelay ? ` ${NETWORK_BLOCKING_HINT}` : ""
290 }`;
291 yield* annotateTarget(target);
292​
293 const connectivity = yield* Connectivity.Connectivity;
294 const driver = yield* ConnectionDriver.ConnectionDriver;
295 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
296 // The primary environment served this client or runs beside it on loopback,
297 // so the device reporting offline (often wrongly) never parks it. The report
298 // still probes its live session, like any other network change.
299 const targetNetwork = (network: NetworkStatus): NetworkStatus =>
300 network === "offline" && target._tag === "PrimaryConnectionTarget" ? "unknown" : network;
301 const initialIntent: SupervisorIntent = {
302 desired: options?.initiallyDesired ?? false,
303 network: targetNetwork(yield* connectivity.status),
304 };
305 const intent = yield* Ref.make(initialIntent);
306 const signals = yield* Queue.unbounded<SupervisorSignal>();
307 const resetRetryState = yield* Ref.make(false);
308 const probeUnanswered = yield* Ref.make(false);
309 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
310 !initialIntent.desired
311 ? availableState(initialIntent, 0)
312 : initialIntent.network === "offline"
313 ? offlineState(initialIntent, 0, 0, null)
314 : connectingState(initialIntent, 0, 1, null),
315 );
316 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
317 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
318 // Learned routes arrive while a session is live, so the route list is read
319 // fresh by each attempt and check instead of being fixed at creation.
320 const currentEntry = yield* Ref.make(entry);
321 const currentRoutes = Ref.get(currentEntry).pipe(Effect.map(connectionRoutes));
322 const preferredRouteId = yield* Ref.make(Option.none<string>());
323 const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());
324 // The generation keeps a check that started before a reset from recording
325 // its stale failures after it.
326 const silentRoutes = yield* Ref.make({
327 generation: 0,
328 routes: new Map<string, SilentRoute>() as ReadonlyMap<string, SilentRoute>,
329 });
330 const forgetSilentRoutes = Ref.update(silentRoutes, ({ generation }) => ({
331 generation: generation + 1,
332 routes: new Map(),
333 }));
334​
335 const attemptEntry = Effect.gen(function* () {
336 const latest = yield* Ref.get(currentEntry);
337 const routes = connectionRoutes(latest);
338 const preferred = yield* Ref.getAndSet(preferredRouteId, Option.none());
339 if (Option.isNone(preferred)) return latest;
340 const route = routes.find(
341 (candidate) => connectionRouteId(candidate.target) === preferred.value,
342 );
343 return route === undefined
344 ? latest
345 : entryWithRoutes(latest, [route, ...routes.filter((candidate) => candidate !== route)]);
346 });
347​
348 const learnRoutesFrom = Effect.fnUntraced(function* (
349 learn: NonNullable<EnvironmentSupervisorOptions["learnRoutes"]>,
350 lease: ConnectedLease,
351 ) {
352 const activeRoute = lease.activeRoute;
353 if (activeRoute === undefined) return;
354 yield* lease.session.subscribeServerConfig().pipe(
355 Stream.filter((event) => event.type === "snapshot"),
356 Stream.map((event) => event.config.directEndpoints),
357 Stream.filter((reported) => reported !== undefined),
358 Stream.changesWith((previous, next) => JSON.stringify(previous) === JSON.stringify(next)),
359 Stream.runForEach((reported) =>
360 Effect.gen(function* () {
361 const updated = yield* learn({ activeRoute, reported });
362 if (Option.isSome(updated)) {
363 yield* Ref.set(currentEntry, updated.value);
364 yield* requestBetterRouteCheck(lease);
365 }
366 }),
367 ),
368 Effect.ignoreCause({ log: true }),
369 );
370 });
371​
372 const routeIndex = (lease: ConnectedLease) =>
373 currentRoutes.pipe(
374 Effect.map((routes) => {
375 const activeId = connectionRouteId(lease.prepared.target);
376 const index = routes.findIndex((route) => connectionRouteId(route.target) === activeId);
377 return index === -1 && lease.activeRoute !== undefined
378 ? insertRoute(routes, lease.activeRoute).findIndex(
379 (route) => connectionRouteId(route.target) === activeId,
380 )
381 : index;
382 }),
383 );
384​
385 const checkBetterRoutes = Effect.fnUntraced(function* (lease: ConnectedLease) {
386 const latest = yield* Ref.get(currentEntry);
387 const current = yield* routeIndex(lease);
388 if (current <= 0) return;
389 const now = yield* Clock.monotonicTimeNanos;
390 const cooldowns = yield* Ref.get(routeCooldowns);
391 const silent = yield* Ref.get(silentRoutes);
392 const better = connectionRoutes(latest)
393 .slice(0, current)
394 .filter((route) => {
395 const id = connectionRouteId(route.target);
396 return (cooldowns.get(id) ?? 0n) <= now && (silent.routes.get(id)?.until ?? 0n) <= now;
397 });
398 const results = yield* Effect.forEach(
399 better,
400 (route: ConnectionRoute) => driver.preflight(latest, route),
401 { concurrency: "unbounded" },
402 );
403 yield* Ref.update(silentRoutes, (previous) => {
404 if (previous.generation !== silent.generation) return previous;
405 const routes = new Map(previous.routes);
406 for (const [position, route] of better.entries()) {
407 const id = connectionRouteId(route.target);
408 if (results[position] !== "silent") routes.delete(id);
409 else routes.set(id, backOffSilentRoute(previous.routes.get(id), now));
410 }
411 return { generation: previous.generation, routes };
412 });
413 const index = results.indexOf("ready");
414 if (index === -1) return;
415 const live = yield* SubscriptionRef.get(session);
416 if (Option.isNone(live) || live.value !== lease.session) return;
417 yield* signal({
418 _tag: "BetterRouteAvailable",
419 routeId: connectionRouteId(better[index]!.target),
420 });
421 });
422​
423 const betterRouteChecks = yield* Queue.dropping<ConnectedLease>(1);
424 const requestBetterRouteCheck = (lease: ConnectedLease) =>
425 routeIndex(lease).pipe(
426 Effect.flatMap((index) =>
427 index > 0 ? Queue.offer(betterRouteChecks, lease).pipe(Effect.asVoid) : Effect.void,
428 ),
429 );
430​
431 const clearLease = Effect.all(
432 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
433 { discard: true },
434 );
435​
436 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
437 next: SupervisorConnectionState,
438 ) {
439 yield* SubscriptionRef.set(state, next);
440 });
441​
442 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
443 yield* Queue.offer(signals, next);
444 });
445​
446 const logManagedRelayAccountChange = Effect.logInfo(
447 "Managed relay account changed; restarting the environment connection.",
448 ).pipe(
449 Effect.annotateLogs({
450 "environment.id": target.environmentId,
451 "environment.label": target.label,
452 }),
453 );
454​
455 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
456 attempt: number,
457 generation: number,
458 lastFailure: ConnectionAttemptError | null,
459 progress: ConnectionDriver.ConnectionDriverProgress,
460 ) {
461 if ("prepared" in progress) {
462 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
463 }
464 yield* setState(
465 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
466 );
467 });
468​
469 const establishConnection = Effect.fnUntraced(function* (
470 attempt: number,
471 generation: number,
472 lastFailure: ConnectionAttemptError | null,
473 synchronizedRoutes: Ref.Ref<number>,
474 ) {
475 return yield* driver.connect(yield* attemptEntry, (progress) =>
476 (progress.stage === "synchronizing"
477 ? Ref.update(synchronizedRoutes, (count) => count + 1)
478 : Effect.void
479 ).pipe(Effect.andThen(reportProgress(attempt, generation, lastFailure, progress))),
480 );
481 });
482​
483 // Low-cardinality dimensions for time-to-connected dashboards; the error
484 // detail stays in the span status, never in an attribute.
485 const annotateAttemptOutcome = Effect.fnUntraced(function* (
486 exit: Exit.Exit<ConnectionDriver.EnvironmentConnectionLease, ConnectionAttemptError>,
487 ) {
488 if (Exit.isSuccess(exit)) {
489 const leaseTarget = exit.value.prepared.target;
490 const route = (yield* currentRoutes).find(
491 (candidate) => connectionRouteId(candidate.target) === connectionRouteId(leaseTarget),
492 );
493 return yield* Effect.annotateCurrentSpan({
494 "connection.outcome": "connected",
495 "connection.route": connectionRouteKind(
496 route ?? { target: leaseTarget, profile: Option.none() },
497 ),
498 });
499 }
500 if (Cause.hasInterruptsOnly(exit.cause)) {
501 return yield* Effect.annotateCurrentSpan("connection.outcome", "interrupted");
502 }
503 const failure = exit.cause.reasons.find(Cause.isFailReason)?.error;
504 yield* Effect.annotateCurrentSpan({
505 "connection.outcome": "failed",
506 "connection.failure.tag": failure?._tag ?? "defect",
507 "connection.failure.reason": failure?.reason ?? "defect",
508 });
509 });
510​
511 const traceRelayEstablishment = (
512 effect: Effect.Effect<
513 ConnectionDriver.EnvironmentConnectionLease,
514 ConnectionAttemptError,
515 Scope.Scope
516 >,
517 attempt: number,
518 generation: number,
519 pendingRetry: Option.Option<PendingRetryTrace>,
520 ) => {
521 // The span must end with the ConnectionAttemptError itself: the exporter
522 // can only describe an Error-like failure, and a TracedAttemptFailure
523 // wrapper reached it as "[object Object]". The wrapper is added outside.
524 let attemptSpan = Option.none<Tracer.Span>();
525 const traced = Effect.gen(function* () {
526 attemptSpan = Option.some(yield* Effect.currentSpan.pipe(Effect.orDie));
527 yield* annotateTarget(target);
528 yield* Effect.annotateCurrentSpan({
529 "connection.attempt": attempt,
530 "connection.generation": generation,
531 "connection.retry.failure_count": Option.match(pendingRetry, {
532 onNone: () => 0,
533 onSome: (retry) => retry.failureCount,
534 }),
535 });
536 return yield* effect.pipe(Effect.onExit(annotateAttemptOutcome));
537 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
538​
539 return Option.match(pendingRetry, {
540 onNone: () => traced,
541 onSome: (retry) =>
542 traced.pipe(
543 Effect.linkSpans(retry.previousAttempt, {
544 "connection.retry.delay_ms": retry.delayMs,
545 "connection.retry.reason": retry.reason,
546 }),
547 ),
548 }).pipe(
549 Effect.map((lease) => ({ attemptSpan, lease })),
550 Effect.mapError((error): TracedAttemptFailure => ({ error, attemptSpan })),
551 withRelayClientTracing,
552 );
553 };
554​
555 const establishTracedConnection = Effect.fnUntraced(function* (
556 attempt: number,
557 generation: number,
558 lastFailure: ConnectionAttemptError | null,
559 pendingRetry: Option.Option<PendingRetryTrace>,
560 synchronizedRoutes: Ref.Ref<number>,
561 ) {
562 if (usesRelay) {
563 return yield* traceRelayEstablishment(
564 establishConnection(attempt, generation, lastFailure, synchronizedRoutes),
565 attempt,
566 generation,
567 pendingRetry,
568 );
569 }
570 return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe(
571 Effect.map((lease) => ({
572 attemptSpan: Option.none<Tracer.Span>(),
573 lease,
574 })),
575 Effect.mapError((error): TracedAttemptFailure => ({
576 error,
577 attemptSpan: Option.none(),
578 })),
579 );
580 });
581​
582 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
583 // A primary attempt keeps running through an offline report, so the
584 // network returning restarts it in case it stalled meanwhile.
585 let deviceOffline = (yield* connectivity.status) === "offline";
586 for (;;) {
587 const next = yield* Queue.take(signals);
588 switch (next._tag) {
589 case "DisconnectRequested":
590 case "RetryRequested":
591 return false;
592 case "NetworkChanged":
593 if (target._tag !== "PrimaryConnectionTarget") {
594 if (next.network === "offline") {
595 return false;
596 }
597 } else if (next.network === "offline") {
598 deviceOffline = true;
599 } else if (deviceOffline) {
600 return true;
601 }
602 break;
603 case "ConnectRequested":
604 case "BetterRouteAvailable":
605 break;
606 case "Wakeup":
607 // An attempt that ran into a long suspension is likely stuck.
608 if (next.reason === "application-active-long") {
609 return true;
610 }
611 if (next.reason === "credentials-changed" && usesRelay) {
612 yield* logManagedRelayAccountChange;
613 return false;
614 }
615 break;
616 }
617 }
618 });
619​
620 const isRelayLease = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
621 lease.prepared.target._tag === "RelayConnectionTarget";
622​
623 const connectedLeaseEnd = Effect.fnUntraced(function* (
624 next: SupervisorSignal,
625 lease: ConnectionDriver.EnvironmentConnectionLease,
626 ) {
627 if (next._tag === "DisconnectRequested") {
628 return "end" as const;
629 }
630 if (next._tag === "BetterRouteAvailable") {
631 yield* Ref.set(preferredRouteId, Option.some(next.routeId));
632 return "reset" as const;
633 }
634 // Only a session over T3 Connect holds the old account's credential.
635 if (next._tag === "Wakeup" && next.reason === "credentials-changed" && isRelayLease(lease)) {
636 yield* logManagedRelayAccountChange;
637 return "end" as const;
638 }
639 return undefined;
640 });
641​
642 const leaseRouteKind = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
643 currentRoutes.pipe(
644 Effect.map((routes) => {
645 const route = routes.find(
646 (candidate) =>
647 connectionRouteId(candidate.target) === connectionRouteId(lease.prepared.target),
648 );
649 return route === undefined ? undefined : connectionRouteKind(route);
650 }),
651 );
652​
653 const isLongResume = (signal: SupervisorSignal) =>
654 signal._tag === "Wakeup" && signal.reason === "application-active-long";
655​
656 const answersQuickly = (routeKind: ConnectionRouteKind | undefined) =>
657 routeKind === "loopback" || routeKind === "lan";
658​
659 const probeTimeoutFor = (
660 next: SupervisorSignal,
661 routeKind: ConnectionRouteKind | undefined,
662 ): Duration.Input | undefined => {
663 switch (next._tag) {
664 case "RetryRequested":
665 return QUICK_CONNECTION_PROBE_TIMEOUT;
666 case "NetworkChanged":
667 return next.network === "offline" ? QUICK_CONNECTION_PROBE_TIMEOUT : undefined;
668 case "Wakeup":
669 if (next.reason === "application-active") {
670 return CONNECTION_PROBE_TIMEOUT;
671 }
672 // After a long suspension the data on screen is stale, so a slow
673 // answer reconnects as quickly as a missing one, even on a remote
674 // route where a reconnect takes longer than the wait it replaces.
675 if (next.reason === "application-active-long") {
676 return LONG_RESUME_PROBE_TIMEOUT;
677 }
678 if (next.reason !== "application-active-probe" && next.reason !== "network-changed") {
679 return undefined;
680 }
681 // Only loopback and LAN answer within 3 seconds reliably. A tailnet
682 // over DERP, a VPN, or the relay can spike past it on a live socket;
683 // a dead one is still caught early by the silent socket check.
684 return answersQuickly(routeKind)
685 ? QUICK_CONNECTION_PROBE_TIMEOUT
686 : CONNECTION_PROBE_TIMEOUT;
687 case "ConnectRequested":
688 case "DisconnectRequested":
689 case "BetterRouteAvailable":
690 return undefined;
691 }
692 };
693​
694 // Ends "silent" when the host answers a fresh request while the socket
695 // delivers nothing, as when iOS kills a suspended socket without a close
696 // event, and "alive" once the socket delivers a frame. A slow or
697 // unreachable host never ends it.
698 const awaitSilentSocket = Effect.fn("EnvironmentSupervisor.awaitSilentSocket")(function* (
699 lease: ConnectedLease,
700 routeKind: ConnectionRouteKind | undefined,
701 longResume: boolean,
702 ) {
703 const startedAt = yield* Clock.monotonicTimeNanos;
704 yield* Effect.sleep(SILENT_SOCKET_CHECK_AFTER);
705 const configLoaded = yield* lease.session.initialConfig.pipe(
706 Effect.as(true),
707 Effect.catchCause(() => Effect.succeed(false)),
708 );
709 if (!configLoaded) return yield* Effect.never;
710 // Frames that queued while the app was suspended have drained by now, so
711 // a later frame shows the path still works.
712 const framesBefore = yield* lease.session.inboundFrames;
713 const socketSilent = lease.session.inboundFrames.pipe(
714 Effect.map((frames) => frames === framesBefore),
715 );
716 // The session only counts frames, so a host check slower than the probe
717 // deadline would otherwise hide a frame until after the socket is replaced.
718 const frameArrives = Effect.sleep(FRAME_CHECK_EVERY).pipe(
719 Effect.andThen(socketSilent),
720 Effect.repeat({ while: (silent) => silent }),
721 Effect.as("alive" as const),
722 );
723 const hostAnswersWhileSilent = Effect.gen(function* () {
724 // A radio still waking up or a stale pooled connection can fail one check.
725 while ((yield* driver.checkHost(lease.prepared)) !== "answered") {
726 yield* Effect.sleep(SILENT_SOCKET_RECHECK_EVERY);
727 }
728 if (!answersQuickly(routeKind) && !longResume) {
729 const silentFor = (yield* Clock.monotonicTimeNanos) - startedAt;
730 const remaining = Duration.toNanosUnsafe(REMOTE_SILENT_SOCKET_AFTER) - silentFor;
731 if (remaining > 0n) yield* Effect.sleep(Duration.nanos(remaining));
732 }
733 return (yield* socketSilent) ? ("silent" as const) : ("alive" as const);
734 });
735 return yield* Effect.race(hostAnswersWhileSilent, frameArrives);
736 });
737​
738 // Returning to the app, an explicit retry, and the network reporting offline
739 // all probe the live session instead of replacing it, so a healthy socket is
740 // not torn down (the offline report is often wrong, for example for a
741 // loopback server).
742 const monitorConnectedLease = Effect.fnUntraced(function* (lease: ConnectedLease) {
743 // A probe answers an explicit retry here, so the retry must not also reset
744 // the backoff of a later, unrelated failure.
745 const takeSignal = Queue.take(signals).pipe(
746 Effect.tap((next) =>
747 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
748 ),
749 );
750 // Ticks always run: the check skips the preferred route itself, and the
751 // route list can grow while connected (learned routes).
752 yield* Stream.tick(Duration.millis(BETTER_ROUTE_CHECK_INTERVAL_MS)).pipe(
753 Stream.drop(1),
754 Stream.runForEach(() => requestBetterRouteCheck(lease)),
755 Effect.forkScoped,
756 );
757 const routeKind = yield* leaseRouteKind(lease);
758 for (;;) {
759 const next = yield* takeSignal;
760 const end = yield* connectedLeaseEnd(next, lease);
761 if (end !== undefined) {
762 return end === "reset";
763 }
764 if (
765 (next._tag === "NetworkChanged" && next.network !== "offline") ||
766 (next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
767 ) {
768 yield* requestBetterRouteCheck(lease);
769 }
770 const probeTimeout = probeTimeoutFor(next, routeKind);
771 if (probeTimeout === undefined) {
772 continue;
773 }
774 yield* Ref.set(probeUnanswered, true);
775 const probe = yield* Effect.forkChild(lease.session.probe);
776 let silentSocket: Fiber.Fiber<"silent" | "alive"> | undefined;
777 // A signal during a running check, such as a network change that kills
778 // the socket, needs a fresh check only if the running one sees a frame.
779 let recheck = false;
780 let longResume = isLongResume(next);
781 const startSilentSocketCheck = Effect.gen(function* () {
782 silentSocket = yield* Effect.forkChild(awaitSilentSocket(lease, routeKind, longResume));
783 recheck = false;
784 });
785 // The web and desktop foreground probe allows a busy host 15 seconds,
786 // and a busy host can answer a fresh request before a queued probe.
787 const armSilentSocketCheck = Effect.fnUntraced(function* (signal: SupervisorSignal) {
788 if (signal._tag === "Wakeup" && signal.reason === "application-active") return;
789 if (silentSocket !== undefined) {
790 recheck = true;
791 return;
792 }
793 yield* startSilentSocketCheck;
794 });
795 yield* armSilentSocketCheck(next);
796 const stopProbe = Effect.suspend(() =>
797 Effect.all(
798 [Fiber.interrupt(probe), silentSocket ? Fiber.interrupt(silentSocket) : Effect.void],
799 { discard: true },
800 ),
801 );
802 let longResumeStartedAt = yield* Clock.monotonicTimeNanos;
803 let deadline = longResumeStartedAt + Duration.toNanosUnsafe(probeTimeout);
804 for (;;) {
805 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
806 const probeEvent = yield* Effect.raceAllFirst([
807 Fiber.await(probe).pipe(
808 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
809 ),
810 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
811 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
812 Effect.as({ _tag: "TimedOut" as const }),
813 ),
814 (silentSocket ? Fiber.join(silentSocket) : Effect.never).pipe(
815 Effect.map((check) =>
816 check === "silent"
817 ? { _tag: "SocketSilent" as const }
818 : { _tag: "SocketAlive" as const },
819 ),
820 ),
821 ]);
822 if (probeEvent._tag === "SocketAlive") {
823 silentSocket = undefined;
824 // A frame shows the socket still works, so its probe gets the usual resume time.
825 if (longResume) {
826 const aliveDeadline =
827 longResumeStartedAt + Duration.toNanosUnsafe(QUICK_CONNECTION_PROBE_TIMEOUT);
828 if (aliveDeadline > deadline) deadline = aliveDeadline;
829 }
830 if (recheck) yield* startSilentSocketCheck;
831 continue;
832 }
833 if (probeEvent._tag === "SocketSilent") {
834 // The host is reachable, so replace the socket at once, even while
835 // the network reports offline.
836 yield* stopProbe;
837 return true;
838 }
839 if (probeEvent._tag === "TimedOut") {
840 yield* stopProbe;
841 // A long suspension leaves the socket suspect even when the network
842 // reports offline, so it is replaced like a silent one.
843 if (longResume) return true;
844 return yield* new ConnectionTransientError({
845 reason: "timeout",
846 detail: `${target.label} did not respond to a connection health check.`,
847 });
848 }
849 if (probeEvent._tag === "ProbeCompleted") {
850 if (silentSocket) yield* Fiber.interrupt(silentSocket);
851 if (Exit.isSuccess(probeEvent.exit)) {
852 yield* Ref.set(probeUnanswered, false);
853 }
854 yield* probeEvent.exit;
855 break;
856 }
857 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
858 if (endDuringProbe !== undefined) {
859 yield* stopProbe;
860 return endDuringProbe === "reset";
861 }
862 const signalTimeout = probeTimeoutFor(probeEvent.signal, routeKind);
863 if (signalTimeout !== undefined) {
864 if (isLongResume(probeEvent.signal) && !longResume) {
865 longResume = true;
866 longResumeStartedAt = yield* Clock.monotonicTimeNanos;
867 }
868 yield* armSilentSocketCheck(probeEvent.signal);
869 const signalDeadline =
870 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
871 if (signalDeadline < deadline) deadline = signalDeadline;
872 }
873 }
874 }
875 });
876​
877 const runAttempt = Effect.fnUntraced(function* (
878 attempt: number,
879 generation: number,
880 lastFailure: ConnectionAttemptError | null,
881 pendingRetry: Option.Option<PendingRetryTrace>,
882 ignoreOffline: boolean,
883 ) {
884 const switchingTo = yield* Ref.get(preferredRouteId);
885 yield* SubscriptionRef.set(prepared, Option.none());
886 const synchronizedRoutes = yield* Ref.make(0);
887 const establishment = yield* Effect.raceAllFirst([
888 exitUnlessInterrupted(
889 establishTracedConnection(
890 attempt,
891 generation,
892 lastFailure,
893 pendingRetry,
894 synchronizedRoutes,
895 ),
896 ).pipe(
897 Effect.map((exit): EstablishmentEvent => ({
898 _tag: "Completed",
899 exit,
900 })),
901 ),
902 waitForEstablishmentInterrupt().pipe(
903 Effect.map((resetRetry): EstablishmentEvent => ({
904 _tag: "Interrupted",
905 resetRetry,
906 })),
907 ),
908 // Each route may use the full setup time before the next is tried, and
909 // each route that reaches synchronizing adds its own snapshot budget, so
910 // a route that fails late does not eat the next route's time.
911 Effect.gen(function* () {
912 const routeCount = connectionRoutes(yield* Ref.get(currentEntry)).length;
913 const startedAt = yield* Clock.monotonicTimeNanos;
914 const setup = Duration.toNanosUnsafe(Duration.times(establishmentTimeout, routeCount));
915 while (true) {
916 const synchronized = BigInt(yield* Ref.get(synchronizedRoutes));
917 const deadline =
918 startedAt + setup + synchronized * Duration.toNanosUnsafe(synchronizationTimeout);
919 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
920 if (remaining <= 0n) {
921 return { _tag: "TimedOut" } as const satisfies EstablishmentEvent;
922 }
923 yield* Effect.sleep(Duration.nanos(remaining));
924 }
925 }),
926 ]);
927​
928 if (establishment._tag === "Interrupted") {
929 return {
930 _tag: "Interrupted",
931 established: false,
932 stable: false,
933 resetRetry: establishment.resetRetry,
934 } satisfies AttemptOutcome;
935 }
936 if (establishment._tag === "TimedOut") {
937 return {
938 _tag: "Failure",
939 established: false,
940 stable: false,
941 failure: {
942 error: new ConnectionTransientError({
943 reason: "timeout",
944 detail: setupTimeoutDetail,
945 }),
946 attemptSpan: Option.none(),
947 },
948 } satisfies AttemptOutcome;
949 }
950 if (Exit.isFailure(establishment.exit)) {
951 const isUnexpectedDefect =
952 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
953 !establishment.exit.cause.reasons.some(Cause.isFailReason);
954 const outcome = failureFromExit(target, establishment.exit, false, false);
955 if (isUnexpectedDefect) {
956 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
957 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
958 Effect.annotateLogs({
959 "environment.id": target.environmentId,
960 "environment.label": target.label,
961 "cause.reason_count": establishment.exit.cause.reasons.length,
962 ...safeErrorLogAttributes(defect),
963 }),
964 );
965 }
966 return outcome;
967 }
968​
969 const active = establishment.exit.value;
970 if (Option.isSome(switchingTo)) {
971 const landed = connectionRouteId(active.lease.prepared.target);
972 if (landed !== switchingTo.value) {
973 const until =
974 (yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
975 yield* Ref.update(routeCooldowns, (current) =>
976 new Map(current).set(switchingTo.value, until),
977 );
978 }
979 }
980 const currentIntent = yield* Ref.get(intent);
981 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
982 return {
983 _tag: "Interrupted",
984 established: false,
985 stable: false,
986 resetRetry: false,
987 } satisfies AttemptOutcome;
988 }
989​
990 const connectedLease: ConnectedLease = {
991 ...active.lease,
992 activeRoute: (yield* currentRoutes).find(
993 (route) =>
994 connectionRouteId(route.target) === connectionRouteId(active.lease.prepared.target),
995 ),
996 };
997 const connectedAt = yield* Clock.currentTimeMillis;
998 yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared));
999 yield* SubscriptionRef.set(session, Option.some(connectedLease.session));
1000 if (options?.learnRoutes !== undefined) {
1001 yield* learnRoutesFrom(options.learnRoutes, connectedLease).pipe(Effect.forkScoped);
1003 yield* setState({
1004 desired: true,
1005 network: currentIntent.network,
1006 phase: "connected",
1007 stage: null,
1008 attempt,
1009 generation,
1010 lastFailure: null,
1011 retryAt: null,
1012 });
1013​
1014 const connectedExit = yield* Effect.raceFirst(
1015 connectedLease.session.closed.pipe(
1016 Effect.mapError((error): TracedAttemptFailure => ({
1017 error,
1018 attemptSpan: active.attemptSpan,
1019 })),
1020 ),
1021 monitorConnectedLease(connectedLease).pipe(
1022 Effect.mapError((error): TracedAttemptFailure => ({
1023 error,
1024 attemptSpan: active.attemptSpan,
1025 })),
1026 ),
1027 ).pipe(exitUnlessInterrupted);
1028 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
1029 if (Exit.isSuccess(connectedExit)) {
1030 return {
1031 _tag: "Interrupted",
1032 established: true,
1033 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
1034 resetRetry: connectedExit.value,
1035 } satisfies AttemptOutcome;
1037 const outcome = failureFromExit(
1038 target,
1039 connectedExit,
1040 true,
1041 connectedForMs >= BACKOFF_RESET_AFTER_MS,
1042 );
1043 if (outcome._tag === "Failure") {
1044 yield* Effect.void.pipe(
1045 Effect.withSpan("EnvironmentSupervisor.connectionLost", {
1046 root: true,
1047 attributes: {
1048 "environment.id": target.environmentId,
1049 "environment.label": target.label,
1050 "environment.target.kind": target._tag,
1051 "connection.connected_ms": connectedForMs,
1052 "connection.failure.reason": outcome.failure.error.reason,
1053 "connection.failure.detail": outcome.failure.error.detail,
1054 },
1055 }),
1056 );
1058 return outcome;
1059 }, Effect.ensuring(clearLease));
1060​
1061 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
1062 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
1063 return yield* Effect.raceFirst(
1064 Effect.sleep(delayMs).pipe(Effect.as(false)),
1065 Effect.gen(function* () {
1066 for (;;) {
1067 const next = yield* Queue.take(signals);
1068 switch (next._tag) {
1069 case "Wakeup":
1070 return ConnectionWakeups.resetsRetryBackoff(next.reason);
1071 case "ConnectRequested":
1072 case "DisconnectRequested":
1073 case "RetryRequested":
1074 case "NetworkChanged":
1075 return false;
1076 case "BetterRouteAvailable":
1077 break;
1080 }),
1081 );
1082 });
1083​
1084 const waitForSignal = Queue.take(signals).pipe(
1085 Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
1086 Effect.map(
1087 (next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
1088 ),
1089 );
1090​
1091 const run = Effect.fnUntraced(function* () {
1092 let failureCount = 0;
1093 let generation = 0;
1094 let latestFailure: ConnectionAttemptError | null = null;
1095 let pendingRetry = Option.none<PendingRetryTrace>();
1096 const resetRetryLadder = () => {
1097 failureCount = 0;
1098 pendingRetry = Option.none();
1099 };
1100 let replacing = false;
1101​
1102 for (;;) {
1103 if (yield* Ref.getAndSet(resetRetryState, false)) {
1104 failureCount = 0;
1105 latestFailure = null;
1106 pendingRetry = Option.none();
1108 const currentIntent = yield* Ref.get(intent);
1109 if (!currentIntent.desired) {
1110 resetRetryLadder();
1111 latestFailure = null;
1112 yield* clearLease;
1113 yield* setState(availableState(currentIntent, generation));
1114 yield* waitForSignal;
1115 continue;
1117 if (currentIntent.network === "offline" && !replacing) {
1118 yield* clearLease;
1119 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
1120 const applicationActivated = yield* waitForSignal;
1121 if (applicationActivated) {
1122 resetRetryLadder();
1124 continue;
1126​
1127 const attempt = failureCount + 1;
1128 const nextGeneration = generation + 1;
1129 const outcome: AttemptOutcome = yield* Effect.scoped(
1130 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
1131 );
1132 replacing = false;
1133 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
1134 if (outcome.established) {
1135 generation = nextGeneration;
1136 // A session came up, so no earlier failure describes the connection.
1137 // Losing a live session is not a failed connection either, for example
1138 // a socket the OS killed while the app was suspended: its replacement
1139 // reports no failure until it fails itself.
1140 latestFailure = null;
1141 if (outcome.stable) {
1142 resetRetryLadder();
1145 if (outcome._tag === "Interrupted") {
1146 if (outcome.resetRetry) {
1147 resetRetryLadder();
1148 replacing = true;
1150 continue;
1152​
1153 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
1154 const error: ConnectionAttemptError = outcome.failure.error;
1155 if (!outcome.established) {
1156 latestFailure = error;
1158 if (error._tag === "ConnectionBlockedError") {
1159 const blockedIntent = yield* Ref.get(intent);
1160 yield* setState({
1161 desired: blockedIntent.desired,
1162 network: blockedIntent.network,
1163 phase: "blocked",
1164 stage: null,
1165 attempt,
1166 generation,
1167 lastFailure: error,
1168 retryAt: null,
1169 });
1170 const applicationActivated = yield* waitForSignal;
1171 if (applicationActivated) {
1172 resetRetryLadder();
1174 continue;
1176​
1177 if (failedProbe) {
1178 resetRetryLadder();
1179 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, latestFailure));
1180 continue;
1182​
1183 // The first loss of a live session retries almost at once; the ladder
1184 // still counts it, so a host that keeps dropping sessions backs off.
1185 const firstLoss = outcome.established && failureCount === 0;
1186 failureCount += 1;
1187 const delayMs = firstLoss
1188 ? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
1189 : retryDelayMs(failureCount - 1, yield* Random.next);
1190 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
1191 previousAttempt,
1192 failureCount,
1193 delayMs,
1194 reason: error.reason,
1195 }));
1196 const failedIntent = yield* Ref.get(intent);
1197 yield* setState({
1198 desired: failedIntent.desired,
1199 network: failedIntent.network,
1200 phase: "backoff",
1201 stage: null,
1202 attempt,
1203 generation,
1204 lastFailure: latestFailure,
1205 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
1206 });
1207 const applicationActivated = yield* waitForRetrySignal(delayMs);
1208 if (applicationActivated) {
1209 resetRetryLadder();
1212 });
1213​
1214 yield* connectivity.changes.pipe(
1215 Stream.runForEach((network) =>
1216 Ref.modify(intent, (current) => {
1217 const next = targetNetwork(network);
1218 return current.network === next
1219 ? [false, current]
1220 : ([true, { ...current, network: next }] as const);
1221 }).pipe(
1222 Effect.flatMap((changed) =>
1223 changed
1224 ? (network === "offline" ? Effect.void : forgetSilentRoutes).pipe(
1225 Effect.andThen(signal({ _tag: "NetworkChanged", network })),
1227 : Effect.void,
1228 ),
1229 ),
1230 ),
1231 Effect.forkScoped,
1232 );
1233 yield* wakeups.changes.pipe(
1234 Stream.runForEach((reason) =>
1235 // A long suspension can hide a network change the platform never reported.
1236 (reason === "network-changed" || reason === "application-active-long"
1237 ? forgetSilentRoutes
1238 : Effect.void
1239 ).pipe(Effect.andThen(signal({ _tag: "Wakeup", reason }))),
1240 ),
1241 Effect.forkScoped,
1242 );
1243 yield* Queue.take(betterRouteChecks).pipe(
1244 Effect.flatMap(checkBetterRoutes),
1245 Effect.forever,
1246 Effect.forkScoped,
1247 );
1248 yield* run().pipe(Effect.forkScoped);
1249​
1250 const connect = Ref.update(intent, (current) => ({
1251 ...current,
1252 desired: true,
1253 })).pipe(
1254 Effect.andThen(signal({ _tag: "ConnectRequested" })),
1255 Effect.withSpan("EnvironmentSupervisor.connect"),
1256 );
1257​
1258 const disconnect = Ref.update(intent, (current) => ({
1259 ...current,
1260 desired: false,
1261 })).pipe(
1262 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
1263 Effect.withSpan("EnvironmentSupervisor.disconnect"),
1264 );
1265​
1266 const retryNow = Ref.set(resetRetryState, true).pipe(
1267 Effect.andThen(signal({ _tag: "RetryRequested" })),
1268 Effect.withSpan("EnvironmentSupervisor.retryNow"),
1269 );
1270​
1271 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1272​
1273 return EnvironmentSupervisor.of({
1274 target,
1275 state,
1276 session,
1277 prepared,
1278 connect,
1279 disconnect,
1280 retryNow,
1281 });
1282});