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

supervisor.ts

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