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