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

supervisor.ts

1,039 lines36.5 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 { connectionRouteId, connectionRoutes, entryWithRoutes } from "./routes.ts";
34​
35const RETRY_BASE_DELAY_MS = 1_000;
36const RETRY_MAX_DELAY_MS = 300_000;
37const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
38const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_TIMEOUT);
39const CONNECTION_PROBE_TIMEOUT = "15 seconds";
40// Mobile resumes, explicit retries, and offline events want a fast answer:
41// the user is waiting, or the network may be gone.
42const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
43const BACKOFF_RESET_AFTER_MS = 30_000;
44// While connected over a fallback route, how often to look for a better one.
45// Network changes and returning to the app also trigger a check.
46const BETTER_ROUTE_CHECK_INTERVAL = "60 seconds";
47// A better route that answered the check but then failed to connect is not
48// tried again for this long, so a flaky LAN cannot bounce the connection.
49const BETTER_ROUTE_COOLDOWN_MS = 300_000;
50​
51interface SupervisorIntent {
52 readonly desired: boolean;
53 readonly network: NetworkStatus;
55​
56type SupervisorSignal =
57 | { readonly _tag: "ConnectRequested" }
58 | { readonly _tag: "DisconnectRequested" }
59 | { readonly _tag: "RetryRequested" }
60 | { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
61 | { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup }
62 | { readonly _tag: "BetterRouteAvailable"; readonly routeId: string };
63​
64interface PendingRetryTrace {
65 readonly previousAttempt: Tracer.Span;
66 readonly failureCount: number;
67 readonly delayMs: number;
68 readonly reason: ConnectionAttemptError["reason"];
70​
71interface TracedAttemptFailure {
72 readonly error: ConnectionAttemptError;
73 readonly attemptSpan: Option.Option<Tracer.Span>;
75​
76type AttemptOutcome =
77 | {
78 readonly _tag: "Interrupted";
79 readonly established: boolean;
80 readonly stable: boolean;
81 readonly resetRetry: boolean;
82 }
83 | {
84 readonly _tag: "Failure";
85 readonly established: boolean;
86 readonly stable: boolean;
87 readonly failure: TracedAttemptFailure;
88 };
89​
90type EstablishmentEvent =
91 | {
92 readonly _tag: "Completed";
93 readonly exit: Exit.Exit<
94 {
95 readonly attemptSpan: Option.Option<Tracer.Span>;
96 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
97 },
98 TracedAttemptFailure
99 >;
100 }
101 | { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
102 | { readonly _tag: "TimedOut" };
103​
104function exitUnlessInterrupted<A, E, R>(
105 effect: Effect.Effect<A, E, R>,
106): Effect.Effect<Exit.Exit<A, E>, never, R> {
107 return Effect.matchCauseEffect(effect, {
108 onFailure: (cause) =>
109 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),
110 onSuccess: (value) => Effect.succeed(Exit.succeed(value)),
111 });
113​
114export interface EnvironmentSupervisorOptions {
115 readonly initiallyDesired?: boolean;
116 /**
117 * Saves the direct addresses the server reports once a session is ready and
118 * returns the entry with its updated routes, which later attempts use. The
119 * live session is left alone: it already works.
120 */
121 readonly learnRoutes?: (input: {
122 readonly activeRoute: ConnectionRoute;
123 readonly reported: ReadonlyArray<{ readonly httpBaseUrl: string }>;
124 }) => Effect.Effect<Option.Option<ConnectionCatalogEntry>>;
126​
127/**
128 * Delay before the next attempt after `failureCount` consecutive failures
129 * (0 for the first retry). The ceiling doubles from 2s up to 5 minutes, and
130 * the delay is a random point in its upper half: never quicker than half the
131 * ceiling, and spread out so clients that lost the same server do not all
132 * reconnect in the same second. `random` is in [0, 1).
133 *
134 * The long cap only applies to a connection that keeps failing. Returning to
135 * the app, the network coming back, and an explicit retry all skip the wait.
136 */
137export function retryDelayMs(failureCount: number, random: number): number {
138 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failureCount + 1));
139 return Math.round(ceiling / 2 + (ceiling / 2) * random);
141​
142function annotateTarget(target: ConnectionTarget) {
143 return Effect.annotateCurrentSpan({
144 "environment.id": target.environmentId,
145 "environment.label": target.label,
146 "environment.target.kind": target._tag,
147 });
149​
150function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
151 return {
152 desired: false,
153 network: intent.network,
154 phase: "available",
155 stage: null,
156 attempt: 0,
157 generation,
158 lastFailure: null,
159 retryAt: null,
160 };
162​
163function offlineState(
164 intent: SupervisorIntent,
165 generation: number,
166 attempt: number,
167 lastFailure: ConnectionAttemptError | null,
168): SupervisorConnectionState {
169 return {
170 desired: true,
171 network: intent.network,
172 phase: "offline",
173 stage: null,
174 attempt,
175 generation,
176 lastFailure,
177 retryAt: null,
178 };
180​
181function connectingState(
182 intent: SupervisorIntent,
183 generation: number,
184 attempt: number,
185 lastFailure: ConnectionAttemptError | null,
186 stage: SupervisorConnectionState["stage"] = "preparing",
187): SupervisorConnectionState {
188 return {
189 desired: true,
190 network: intent.network,
191 phase: "connecting",
192 stage,
193 attempt,
194 generation,
195 lastFailure,
196 retryAt: null,
197 };
199​
200function failureFromExit<A>(
201 target: ConnectionTarget,
202 exit: Exit.Exit<A, TracedAttemptFailure>,
203 established: boolean,
204 stable: boolean,
205): AttemptOutcome {
206 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
207 return { _tag: "Interrupted", established, stable, resetRetry: false };
208 }
209 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
210 if (typedFailure) {
211 return {
212 _tag: "Failure",
213 established,
214 stable,
215 failure: typedFailure.error,
216 };
217 }
218 return {
219 _tag: "Failure",
220 established,
221 stable,
222 failure: {
223 error: new ConnectionTransientError({
224 reason: "transport",
225 detail: `${target.label} connection failed unexpectedly.`,
226 }),
227 attemptSpan: Option.none(),
228 },
229 };
231​
232export class EnvironmentSupervisor extends Context.Service<
233 EnvironmentSupervisor,
234 {
235 readonly target: ConnectionTarget;
236 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
237 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
238 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
239 readonly connect: Effect.Effect<void>;
240 readonly disconnect: Effect.Effect<void>;
241 readonly retryNow: Effect.Effect<void>;
242 }
243>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
244​
245export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
246 entry: ConnectionCatalogEntry,
247 options?: EnvironmentSupervisorOptions,
248): Effect.fn.Return<
249 EnvironmentSupervisor["Service"],
250 never,
251 | Connectivity.Connectivity
252 | ConnectionDriver.ConnectionDriver
253 | Scope.Scope
254 | ConnectionWakeups.ConnectionWakeups
255> {
256 const target = entry.target;
257 // Relay-specific handling applies when any route is T3 Connect, since the
258 // attempt or the live session may be using it.
259 const usesRelay = connectionRoutes(entry).some(
260 (route) => route.target._tag === "RelayConnectionTarget",
261 );
262 const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
263 usesRelay ? ` ${NETWORK_BLOCKING_HINT}` : ""
264 }`;
265 yield* annotateTarget(target);
266​
267 const connectivity = yield* Connectivity.Connectivity;
268 const driver = yield* ConnectionDriver.ConnectionDriver;
269 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
270 const initialIntent: SupervisorIntent = {
271 desired: options?.initiallyDesired ?? false,
272 network: yield* connectivity.status,
273 };
274 const intent = yield* Ref.make(initialIntent);
275 const signals = yield* Queue.unbounded<SupervisorSignal>();
276 const resetRetryState = yield* Ref.make(false);
277 // Set while a probe of the live session is running, and kept when it fails
278 // or times out: something asked whether the connection still works and it
279 // closed or failed before answering, so the follow-up reconnect skips the
280 // first backoff rung instead of sleeping.
281 const probeUnanswered = yield* Ref.make(false);
282 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
283 !initialIntent.desired
284 ? availableState(initialIntent, 0)
285 : initialIntent.network === "offline"
286 ? offlineState(initialIntent, 0, 0, null)
287 : connectingState(initialIntent, 0, 1, null),
288 );
289 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
290 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
291 // Learned routes arrive while a session is live, so the route list is read
292 // fresh by each attempt and check instead of being fixed at creation.
293 const currentEntry = yield* Ref.make(entry);
294 const currentRoutes = Ref.get(currentEntry).pipe(Effect.map(connectionRoutes));
295 // Set when a better route answered while connected over a worse one; the
296 // replacement attempt tries it first. Cleared once an attempt starts.
297 const preferredRouteId = yield* Ref.make(Option.none<string>());
298 // Monotonic deadline per route that answered a check but failed to connect.
299 const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());
300​
301 const attemptEntry = Effect.gen(function* () {
302 const latest = yield* Ref.get(currentEntry);
303 const routes = connectionRoutes(latest);
304 const preferred = yield* Ref.getAndSet(preferredRouteId, Option.none());
305 if (Option.isNone(preferred)) return latest;
306 const route = routes.find(
307 (candidate) => connectionRouteId(candidate.target) === preferred.value,
308 );
309 return route === undefined
310 ? latest
311 : entryWithRoutes(latest, [route, ...routes.filter((candidate) => candidate !== route)]);
312 });
313​
314 const learnRoutesFrom = Effect.fnUntraced(function* (
315 learn: NonNullable<EnvironmentSupervisorOptions["learnRoutes"]>,
316 lease: ConnectionDriver.EnvironmentConnectionLease,
317 ) {
318 const config = yield* lease.session.initialConfig.pipe(Effect.option);
319 const reported = Option.getOrUndefined(config)?.directEndpoints;
320 if (reported === undefined) return;
321 const activeId = connectionRouteId(lease.prepared.target);
322 const activeRoute = (yield* currentRoutes).find(
323 (route) => connectionRouteId(route.target) === activeId,
324 );
325 if (activeRoute === undefined) return;
326 const updated = yield* learn({ activeRoute, reported });
327 if (Option.isSome(updated)) {
328 yield* Ref.set(currentEntry, updated.value);
329 // A learned route may rank above the one in use.
330 yield* requestBetterRouteCheck(lease);
331 }
332 });
333​
334 const routeIndex = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
335 currentRoutes.pipe(
336 Effect.map((routes) =>
337 routes.findIndex(
338 (route) => connectionRouteId(route.target) === connectionRouteId(lease.prepared.target),
339 ),
340 ),
341 );
342​
343 /**
344 * Preflights the routes ranked above the one in use and signals the best
345 * that would connect. Routes without a cheap check (T3 Connect, SSH) never
346 * pass, so they are fallbacks, not destinations.
347 */
348 const checkBetterRoutes = Effect.fnUntraced(function* (
349 lease: ConnectionDriver.EnvironmentConnectionLease,
350 ) {
351 const latest = yield* Ref.get(currentEntry);
352 const current = yield* routeIndex(lease);
353 if (current <= 0) return;
354 const now = yield* Clock.monotonicTimeNanos;
355 const cooldowns = yield* Ref.get(routeCooldowns);
356 const better = connectionRoutes(latest)
357 .slice(0, current)
358 .filter((route) => (cooldowns.get(connectionRouteId(route.target)) ?? 0n) <= now);
359 const passed = yield* Effect.forEach(
360 better,
361 (route: ConnectionRoute) => driver.preflight(latest, route),
362 { concurrency: "unbounded" },
363 );
364 const index = passed.indexOf(true);
365 if (index === -1) return;
366 // The check may outlive the session it was asked about.
367 const live = yield* SubscriptionRef.get(session);
368 if (Option.isNone(live) || live.value !== lease.session) return;
369 yield* signal({
370 _tag: "BetterRouteAvailable",
371 routeId: connectionRouteId(better[index]!.target),
372 });
373 });
374​
375 // One check at a time; a trigger during a check is dropped, not queued.
376 const betterRouteChecks = yield* Queue.dropping<ConnectionDriver.EnvironmentConnectionLease>(1);
377 const requestBetterRouteCheck = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
378 routeIndex(lease).pipe(
379 Effect.flatMap((index) =>
380 index > 0 ? Queue.offer(betterRouteChecks, lease).pipe(Effect.asVoid) : Effect.void,
381 ),
382 );
383​
384 const clearLease = Effect.all(
385 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
386 { discard: true },
387 );
388​
389 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
390 next: SupervisorConnectionState,
391 ) {
392 yield* SubscriptionRef.set(state, next);
393 });
394​
395 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
396 yield* Queue.offer(signals, next);
397 });
398​
399 const logManagedRelayAccountChange = Effect.logInfo(
400 "Managed relay account changed; restarting the environment connection.",
401 ).pipe(
402 Effect.annotateLogs({
403 "environment.id": target.environmentId,
404 "environment.label": target.label,
405 }),
406 );
407​
408 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
409 attempt: number,
410 generation: number,
411 lastFailure: ConnectionAttemptError | null,
412 progress: ConnectionDriver.ConnectionDriverProgress,
413 ) {
414 if ("prepared" in progress) {
415 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
416 }
417 yield* setState(
418 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
419 );
420 });
421​
422 const establishConnection = Effect.fnUntraced(function* (
423 attempt: number,
424 generation: number,
425 lastFailure: ConnectionAttemptError | null,
426 ) {
427 return yield* driver.connect(yield* attemptEntry, (progress) =>
428 reportProgress(attempt, generation, lastFailure, progress),
429 );
430 });
431​
432 const traceRelayEstablishment = (
433 effect: Effect.Effect<
434 ConnectionDriver.EnvironmentConnectionLease,
435 ConnectionAttemptError,
436 Scope.Scope
437 >,
438 attempt: number,
439 generation: number,
440 pendingRetry: Option.Option<PendingRetryTrace>,
441 ) => {
442 const traced = Effect.gen(function* () {
443 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
444 yield* annotateTarget(target);
445 yield* Effect.annotateCurrentSpan({
446 "connection.attempt": attempt,
447 "connection.generation": generation,
448 "connection.retry.failure_count": Option.match(pendingRetry, {
449 onNone: () => 0,
450 onSome: (retry) => retry.failureCount,
451 }),
452 });
453 const lease = yield* effect.pipe(
454 Effect.mapError((error): TracedAttemptFailure => ({
455 error,
456 attemptSpan: Option.some(attemptSpan),
457 })),
458 );
459 return { attemptSpan: Option.some(attemptSpan), lease };
460 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
461​
462 return Option.match(pendingRetry, {
463 onNone: () => traced,
464 onSome: (retry) =>
465 traced.pipe(
466 Effect.linkSpans(retry.previousAttempt, {
467 "connection.retry.delay_ms": retry.delayMs,
468 "connection.retry.reason": retry.reason,
469 }),
470 ),
471 }).pipe(withRelayClientTracing);
472 };
473​
474 const establishTracedConnection = Effect.fnUntraced(function* (
475 attempt: number,
476 generation: number,
477 lastFailure: ConnectionAttemptError | null,
478 pendingRetry: Option.Option<PendingRetryTrace>,
479 ) {
480 if (usesRelay) {
481 return yield* traceRelayEstablishment(
482 establishConnection(attempt, generation, lastFailure),
483 attempt,
484 generation,
485 pendingRetry,
486 );
487 }
488 return yield* establishConnection(attempt, generation, lastFailure).pipe(
489 Effect.map((lease) => ({
490 attemptSpan: Option.none<Tracer.Span>(),
491 lease,
492 })),
493 Effect.mapError((error): TracedAttemptFailure => ({
494 error,
495 attemptSpan: Option.none(),
496 })),
497 );
498 });
499​
500 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
501 for (;;) {
502 const next = yield* Queue.take(signals);
503 switch (next._tag) {
504 case "DisconnectRequested":
505 case "RetryRequested":
506 return false;
507 case "NetworkChanged":
508 if (next.network === "offline") {
509 return false;
510 }
511 break;
512 case "ConnectRequested":
513 case "BetterRouteAvailable":
514 break;
515 case "Wakeup":
516 if (next.reason === "application-active-reconnect") {
517 return true;
518 }
519 if (next.reason === "credentials-changed" && usesRelay) {
520 yield* logManagedRelayAccountChange;
521 return false;
522 }
523 break;
524 }
525 }
526 });
527​
528 // Signals that end a connected lease whatever its health: "reset" ends it
529 // and restarts the retry ladder, "end" ends it, undefined keeps it.
530 const isRelayLease = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
531 lease.prepared.target._tag === "RelayConnectionTarget";
532​
533 const connectedLeaseEnd = Effect.fnUntraced(function* (
534 next: SupervisorSignal,
535 lease: ConnectionDriver.EnvironmentConnectionLease,
536 ) {
537 if (next._tag === "DisconnectRequested") {
538 return "end" as const;
539 }
540 if (next._tag === "BetterRouteAvailable") {
541 // Replaced like a long resume: the new attempt prefers the better route
542 // and its session takes over the durable subscriptions.
543 yield* Ref.set(preferredRouteId, Option.some(next.routeId));
544 return "reset" as const;
545 }
546 if (next._tag !== "Wakeup") {
547 return undefined;
548 }
549 if (next.reason === "application-active-reconnect") {
550 // Mobile operating systems often kill a suspended socket without a close
551 // event. A probe would show a dead socket as "Resuming" until it times
552 // out, so a long background resume replaces the session at once.
553 return "reset" as const;
554 }
555 // Only a session over T3 Connect holds the old account's credential.
556 if (next.reason === "credentials-changed" && isRelayLease(lease)) {
557 yield* logManagedRelayAccountChange;
558 return "end" as const;
559 }
560 return undefined;
561 });
562​
563 // How long a signal waits for the live session to answer a probe, or
564 // undefined when the signal does not question the connection.
565 const probeTimeoutFor = (next: SupervisorSignal): Duration.Input | undefined => {
566 switch (next._tag) {
567 case "RetryRequested":
568 return QUICK_CONNECTION_PROBE_TIMEOUT;
569 case "NetworkChanged":
570 return next.network === "offline" ? QUICK_CONNECTION_PROBE_TIMEOUT : undefined;
571 case "Wakeup":
572 if (next.reason === "application-active") {
573 return CONNECTION_PROBE_TIMEOUT;
574 }
575 // A socket opened on the previous network may now be unroutable.
576 return next.reason === "application-active-probe" || next.reason === "network-changed"
577 ? QUICK_CONNECTION_PROBE_TIMEOUT
578 : undefined;
579 case "ConnectRequested":
580 case "DisconnectRequested":
581 case "BetterRouteAvailable":
582 return undefined;
583 }
584 };
585​
586 // Holds a connected lease until it must end, and returns whether to restart
587 // the retry ladder. Returning to the app, an explicit retry, and the network
588 // reporting offline all probe the live session instead of replacing it, so a
589 // healthy socket is not torn down (the offline report is often wrong, for
590 // example for a loopback server). Only a long mobile resume replaces the
591 // session without a probe. A failed probe fails this effect, and the
592 // supervisor reconnects.
593 const monitorConnectedLease = Effect.fnUntraced(function* (
594 lease: ConnectionDriver.EnvironmentConnectionLease,
595 ) {
596 // A probe answers an explicit retry here, so the retry must not also reset
597 // the backoff of a later, unrelated failure.
598 const takeSignal = Queue.take(signals).pipe(
599 Effect.tap((next) =>
600 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
601 ),
602 );
603 // Ticks always run: the check skips the preferred route itself, and the
604 // route list can grow while connected (learned routes).
605 yield* Stream.tick(BETTER_ROUTE_CHECK_INTERVAL).pipe(
606 Stream.drop(1),
607 Stream.runForEach(() => requestBetterRouteCheck(lease)),
608 Effect.forkScoped,
609 );
610 for (;;) {
611 const next = yield* takeSignal;
612 const end = yield* connectedLeaseEnd(next, lease);
613 if (end !== undefined) {
614 return end === "reset";
615 }
616 // A new network or a return to the app may have brought a better route back.
617 if (
618 (next._tag === "NetworkChanged" && next.network !== "offline") ||
619 (next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
620 ) {
621 yield* requestBetterRouteCheck(lease);
622 }
623 const probeTimeout = probeTimeoutFor(next);
624 if (probeTimeout === undefined) {
625 continue;
626 }
627 yield* Ref.set(probeUnanswered, true);
628 const probe = yield* Effect.forkChild(lease.session.probe);
629 // Monotonic nanoseconds, so a wall-clock correction cannot move the deadline.
630 let deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
631 for (;;) {
632 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
633 const probeEvent = yield* Effect.raceAllFirst([
634 Fiber.await(probe).pipe(
635 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
636 ),
637 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
638 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
639 Effect.as({ _tag: "TimedOut" as const }),
640 ),
641 ]);
642 if (probeEvent._tag === "TimedOut") {
643 yield* Fiber.interrupt(probe);
644 return yield* new ConnectionTransientError({
645 reason: "timeout",
646 detail: `${target.label} did not respond to a connection health check.`,
647 });
648 }
649 if (probeEvent._tag === "ProbeCompleted") {
650 if (Exit.isSuccess(probeEvent.exit)) {
651 yield* Ref.set(probeUnanswered, false);
652 }
653 yield* probeEvent.exit;
654 break;
655 }
656 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
657 if (endDuringProbe !== undefined) {
658 yield* Fiber.interrupt(probe);
659 return endDuringProbe === "reset";
660 }
661 // A retry or an offline report during a desktop foreground probe wants
662 // its quicker answer, so it shortens the running probe.
663 const signalTimeout = probeTimeoutFor(probeEvent.signal);
664 if (signalTimeout !== undefined) {
665 const signalDeadline =
666 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
667 if (signalDeadline < deadline) deadline = signalDeadline;
668 }
669 }
670 }
671 });
672​
673 const runAttempt = Effect.fnUntraced(function* (
674 attempt: number,
675 generation: number,
676 lastFailure: ConnectionAttemptError | null,
677 pendingRetry: Option.Option<PendingRetryTrace>,
678 ignoreOffline: boolean,
679 ) {
680 const switchingTo = yield* Ref.get(preferredRouteId);
681 yield* SubscriptionRef.set(prepared, Option.none());
682 const establishment = yield* Effect.raceAllFirst([
683 exitUnlessInterrupted(
684 establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
685 ).pipe(
686 Effect.map((exit): EstablishmentEvent => ({
687 _tag: "Completed",
688 exit,
689 })),
690 ),
691 waitForEstablishmentInterrupt().pipe(
692 Effect.map((resetRetry): EstablishmentEvent => ({
693 _tag: "Interrupted",
694 resetRetry,
695 })),
696 ),
697 // Each route may use the full setup time before the next is tried.
698 Effect.sleep(
699 Duration.times(establishmentTimeout, connectionRoutes(yield* Ref.get(currentEntry)).length),
700 ).pipe(Effect.as<EstablishmentEvent>({ _tag: "TimedOut" })),
701 ]);
702​
703 if (establishment._tag === "Interrupted") {
704 return {
705 _tag: "Interrupted",
706 established: false,
707 stable: false,
708 resetRetry: establishment.resetRetry,
709 } satisfies AttemptOutcome;
710 }
711 if (establishment._tag === "TimedOut") {
712 return {
713 _tag: "Failure",
714 established: false,
715 stable: false,
716 failure: {
717 error: new ConnectionTransientError({
718 reason: "timeout",
719 detail: setupTimeoutDetail,
720 }),
721 attemptSpan: Option.none(),
722 },
723 } satisfies AttemptOutcome;
724 }
725 if (Exit.isFailure(establishment.exit)) {
726 const isUnexpectedDefect =
727 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
728 !establishment.exit.cause.reasons.some(Cause.isFailReason);
729 const outcome = failureFromExit(target, establishment.exit, false, false);
730 if (isUnexpectedDefect) {
731 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
732 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
733 Effect.annotateLogs({
734 "environment.id": target.environmentId,
735 "environment.label": target.label,
736 "cause.reason_count": establishment.exit.cause.reasons.length,
737 ...safeErrorLogAttributes(defect),
738 }),
739 );
740 }
741 return outcome;
742 }
743​
744 const active = establishment.exit.value;
745 if (Option.isSome(switchingTo)) {
746 const landed = connectionRouteId(active.lease.prepared.target);
747 if (landed !== switchingTo.value) {
748 const until =
749 (yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
750 yield* Ref.update(routeCooldowns, (current) =>
751 new Map(current).set(switchingTo.value, until),
752 );
753 }
754 }
755 const currentIntent = yield* Ref.get(intent);
756 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
757 return {
758 _tag: "Interrupted",
759 established: false,
760 stable: false,
761 resetRetry: false,
762 } satisfies AttemptOutcome;
763 }
764​
765 const connectedAt = yield* Clock.currentTimeMillis;
766 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
767 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
768 if (options?.learnRoutes !== undefined) {
769 yield* learnRoutesFrom(options.learnRoutes, active.lease).pipe(Effect.forkScoped);
770 }
771 yield* setState({
772 desired: true,
773 network: currentIntent.network,
774 phase: "connected",
775 stage: null,
776 attempt,
777 generation,
778 lastFailure: null,
779 retryAt: null,
780 });
781​
782 const connectedExit = yield* Effect.raceFirst(
783 active.lease.session.closed.pipe(
784 Effect.mapError((error): TracedAttemptFailure => ({
785 error,
786 attemptSpan: active.attemptSpan,
787 })),
788 ),
789 monitorConnectedLease(active.lease).pipe(
790 Effect.mapError((error): TracedAttemptFailure => ({
791 error,
792 attemptSpan: active.attemptSpan,
793 })),
794 ),
795 ).pipe(exitUnlessInterrupted);
796 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
797 if (Exit.isSuccess(connectedExit)) {
798 return {
799 _tag: "Interrupted",
800 established: true,
801 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
802 resetRetry: connectedExit.value,
803 } satisfies AttemptOutcome;
804 }
805 const outcome = failureFromExit(
806 target,
807 connectedExit,
808 true,
809 connectedForMs >= BACKOFF_RESET_AFTER_MS,
810 );
811 if (outcome._tag === "Failure") {
812 // A live session ending is otherwise invisible in the client trace, so
813 // record why, and how long it lasted, as its own root span.
814 yield* Effect.void.pipe(
815 Effect.withSpan("EnvironmentSupervisor.connectionLost", {
816 root: true,
817 attributes: {
818 "environment.id": target.environmentId,
819 "environment.label": target.label,
820 "environment.target.kind": target._tag,
821 "connection.connected_ms": connectedForMs,
822 "connection.failure.reason": outcome.failure.error.reason,
823 "connection.failure.detail": outcome.failure.error.detail,
824 },
825 }),
826 );
827 }
828 return outcome;
829 }, Effect.ensuring(clearLease));
830​
831 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
832 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
833 return yield* Effect.raceFirst(
834 Effect.sleep(delayMs).pipe(Effect.as(false)),
835 Effect.gen(function* () {
836 for (;;) {
837 const next = yield* Queue.take(signals);
838 switch (next._tag) {
839 case "Wakeup":
840 return ConnectionWakeups.resetsRetryBackoff(next.reason);
841 case "ConnectRequested":
842 case "DisconnectRequested":
843 case "RetryRequested":
844 case "NetworkChanged":
845 return false;
846 case "BetterRouteAvailable":
847 break;
848 }
849 }
850 }),
851 );
852 });
853​
854 // A better route only matters to a live session, so idle states ignore it.
855 const waitForSignal = Queue.take(signals).pipe(
856 Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
857 Effect.map(
858 (next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
859 ),
860 );
861​
862 const run = Effect.fnUntraced(function* () {
863 let failureCount = 0;
864 let generation = 0;
865 let latestFailure: ConnectionAttemptError | null = null;
866 let pendingRetry = Option.none<PendingRetryTrace>();
867 const resetRetryLadder = () => {
868 failureCount = 0;
869 pendingRetry = Option.none();
870 };
871 // Set after a long resume ends an attempt or a session. The fresh attempt
872 // runs even while the network reports offline: the report is often wrong,
873 // and the replaced session must not leave the client offline.
874 let replacing = false;
875​
876 for (;;) {
877 if (yield* Ref.getAndSet(resetRetryState, false)) {
878 failureCount = 0;
879 latestFailure = null;
880 pendingRetry = Option.none();
881 }
882 const currentIntent = yield* Ref.get(intent);
883 if (!currentIntent.desired) {
884 resetRetryLadder();
885 latestFailure = null;
886 yield* clearLease;
887 yield* setState(availableState(currentIntent, generation));
888 yield* waitForSignal;
889 continue;
890 }
891 if (currentIntent.network === "offline" && !replacing) {
892 yield* clearLease;
893 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
894 const applicationActivated = yield* waitForSignal;
895 if (applicationActivated) {
896 resetRetryLadder();
897 }
898 continue;
899 }
900​
901 const attempt = failureCount + 1;
902 const nextGeneration = generation + 1;
903 const outcome: AttemptOutcome = yield* Effect.scoped(
904 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
905 );
906 replacing = false;
907 // Consumed on every iteration so a stale marker can never leak into a
908 // later, unrelated failure.
909 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
910 if (outcome.established) {
911 generation = nextGeneration;
912 if (outcome.stable) {
913 resetRetryLadder();
914 latestFailure = null;
915 }
916 }
917 if (outcome._tag === "Interrupted") {
918 if (outcome.resetRetry) {
919 resetRetryLadder();
920 replacing = true;
921 }
922 continue;
923 }
924​
925 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
926 const error: ConnectionAttemptError = outcome.failure.error;
927 latestFailure = error;
928 if (error._tag === "ConnectionBlockedError") {
929 const blockedIntent = yield* Ref.get(intent);
930 yield* setState({
931 desired: blockedIntent.desired,
932 network: blockedIntent.network,
933 phase: "blocked",
934 stage: null,
935 attempt,
936 generation,
937 lastFailure: error,
938 retryAt: null,
939 });
940 const applicationActivated = yield* waitForSignal;
941 if (applicationActivated) {
942 resetRetryLadder();
943 }
944 continue;
945 }
946​
947 if (failedProbe) {
948 // A probe found a dead transport, or the transport closed while a probe
949 // waited for an answer (the user returned to the app, asked to retry,
950 // or the network changed), so reconnect immediately instead
951 // of sleeping the first backoff rung. Only this first attempt skips the
952 // ladder; if it fails too, normal backoff resumes.
953 resetRetryLadder();
954 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, error));
955 continue;
956 }
957​
958 failureCount += 1;
959 const delayMs = retryDelayMs(failureCount - 1, yield* Random.next);
960 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
961 previousAttempt,
962 failureCount,
963 delayMs,
964 reason: error.reason,
965 }));
966 const failedIntent = yield* Ref.get(intent);
967 yield* setState({
968 desired: failedIntent.desired,
969 network: failedIntent.network,
970 phase: "backoff",
971 stage: null,
972 attempt,
973 generation,
974 lastFailure: error,
975 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
976 });
977 const applicationActivated = yield* waitForRetrySignal(delayMs);
978 if (applicationActivated) {
979 resetRetryLadder();
980 }
981 }
982 });
983​
984 yield* connectivity.changes.pipe(
985 Stream.runForEach((network) =>
986 Ref.modify(intent, (current) =>
987 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
988 ).pipe(
989 Effect.flatMap((changed) =>
990 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
991 ),
992 ),
993 ),
994 Effect.forkScoped,
995 );
996 yield* wakeups.changes.pipe(
997 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
998 Effect.forkScoped,
999 );
1000 yield* Queue.take(betterRouteChecks).pipe(
1001 Effect.flatMap(checkBetterRoutes),
1002 Effect.forever,
1003 Effect.forkScoped,
1004 );
1005 yield* run().pipe(Effect.forkScoped);
1006​
1007 const connect = Ref.update(intent, (current) => ({
1008 ...current,
1009 desired: true,
1010 })).pipe(
1011 Effect.andThen(signal({ _tag: "ConnectRequested" })),
1012 Effect.withSpan("EnvironmentSupervisor.connect"),
1013 );
1014​
1015 const disconnect = Ref.update(intent, (current) => ({
1016 ...current,
1017 desired: false,
1018 })).pipe(
1019 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
1020 Effect.withSpan("EnvironmentSupervisor.disconnect"),
1021 );
1022​
1023 const retryNow = Ref.set(resetRetryState, true).pipe(
1024 Effect.andThen(signal({ _tag: "RetryRequested" })),
1025 Effect.withSpan("EnvironmentSupervisor.retryNow"),
1026 );
1027​
1028 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1029​
1030 return EnvironmentSupervisor.of({
1031 target,
1032 state,
1033 session,
1034 prepared,
1035 connect,
1036 disconnect,
1037 retryNow,
1038 });
1039});