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

supervisor.ts

838 lines27.4 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 type * 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 } 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";
33​
34const RETRY_BASE_DELAY_MS = 1_000;
35const RETRY_MAX_DELAY_MS = 300_000;
36const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
37const CONNECTION_PROBE_TIMEOUT = "15 seconds";
38// Mobile resumes, explicit retries, and offline events want a fast answer:
39// the user is waiting, or the network may be gone.
40const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
41const BACKOFF_RESET_AFTER_MS = 30_000;
42​
43interface SupervisorIntent {
44 readonly desired: boolean;
45 readonly network: NetworkStatus;
47​
48type SupervisorSignal =
49 | { readonly _tag: "ConnectRequested" }
50 | { readonly _tag: "DisconnectRequested" }
51 | { readonly _tag: "RetryRequested" }
52 | { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
53 | { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup };
54​
55interface PendingRetryTrace {
56 readonly previousAttempt: Tracer.Span;
57 readonly failureCount: number;
58 readonly delayMs: number;
59 readonly reason: ConnectionAttemptError["reason"];
61​
62interface TracedAttemptFailure {
63 readonly error: ConnectionAttemptError;
64 readonly attemptSpan: Option.Option<Tracer.Span>;
66​
67type AttemptOutcome =
68 | {
69 readonly _tag: "Interrupted";
70 readonly established: boolean;
71 readonly stable: boolean;
72 readonly resetRetry: boolean;
73 }
74 | {
75 readonly _tag: "Failure";
76 readonly established: boolean;
77 readonly stable: boolean;
78 readonly failure: TracedAttemptFailure;
79 };
80​
81type EstablishmentEvent =
82 | {
83 readonly _tag: "Completed";
84 readonly exit: Exit.Exit<
85 {
86 readonly attemptSpan: Option.Option<Tracer.Span>;
87 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
88 },
89 TracedAttemptFailure
90 >;
91 }
92 | { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
93 | { readonly _tag: "TimedOut" };
94​
95function exitUnlessInterrupted<A, E, R>(
96 effect: Effect.Effect<A, E, R>,
97): Effect.Effect<Exit.Exit<A, E>, never, R> {
98 return Effect.matchCauseEffect(effect, {
99 onFailure: (cause) =>
100 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),
101 onSuccess: (value) => Effect.succeed(Exit.succeed(value)),
102 });
104​
105export interface EnvironmentSupervisorOptions {
106 readonly initiallyDesired?: boolean;
108​
109/**
110 * Delay before the next attempt after `failureCount` consecutive failures
111 * (0 for the first retry). The ceiling doubles from 2s up to 5 minutes, and
112 * the delay is a random point in its upper half: never quicker than half the
113 * ceiling, and spread out so clients that lost the same server do not all
114 * reconnect in the same second. `random` is in [0, 1).
115 *
116 * The long cap only applies to a connection that keeps failing. Returning to
117 * the app, the network coming back, and an explicit retry all skip the wait.
118 */
119export function retryDelayMs(failureCount: number, random: number): number {
120 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failureCount + 1));
121 return Math.round(ceiling / 2 + (ceiling / 2) * random);
123​
124function annotateTarget(target: ConnectionTarget) {
125 return Effect.annotateCurrentSpan({
126 "environment.id": target.environmentId,
127 "environment.label": target.label,
128 "environment.target.kind": target._tag,
129 });
131​
132function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
133 return {
134 desired: false,
135 network: intent.network,
136 phase: "available",
137 stage: null,
138 attempt: 0,
139 generation,
140 lastFailure: null,
141 retryAt: null,
142 };
144​
145function offlineState(
146 intent: SupervisorIntent,
147 generation: number,
148 attempt: number,
149 lastFailure: ConnectionAttemptError | null,
150): SupervisorConnectionState {
151 return {
152 desired: true,
153 network: intent.network,
154 phase: "offline",
155 stage: null,
156 attempt,
157 generation,
158 lastFailure,
159 retryAt: null,
160 };
162​
163function connectingState(
164 intent: SupervisorIntent,
165 generation: number,
166 attempt: number,
167 lastFailure: ConnectionAttemptError | null,
168 stage: SupervisorConnectionState["stage"] = "preparing",
169): SupervisorConnectionState {
170 return {
171 desired: true,
172 network: intent.network,
173 phase: "connecting",
174 stage,
175 attempt,
176 generation,
177 lastFailure,
178 retryAt: null,
179 };
181​
182function failureFromExit<A>(
183 target: ConnectionTarget,
184 exit: Exit.Exit<A, TracedAttemptFailure>,
185 established: boolean,
186 stable: boolean,
187): AttemptOutcome {
188 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
189 return { _tag: "Interrupted", established, stable, resetRetry: false };
190 }
191 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
192 if (typedFailure) {
193 return {
194 _tag: "Failure",
195 established,
196 stable,
197 failure: typedFailure.error,
198 };
199 }
200 return {
201 _tag: "Failure",
202 established,
203 stable,
204 failure: {
205 error: new ConnectionTransientError({
206 reason: "transport",
207 detail: `${target.label} connection failed unexpectedly.`,
208 }),
209 attemptSpan: Option.none(),
210 },
211 };
213​
214export class EnvironmentSupervisor extends Context.Service<
215 EnvironmentSupervisor,
216 {
217 readonly target: ConnectionTarget;
218 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
219 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
220 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
221 readonly connect: Effect.Effect<void>;
222 readonly disconnect: Effect.Effect<void>;
223 readonly retryNow: Effect.Effect<void>;
224 }
225>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
226​
227export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
228 entry: ConnectionCatalogEntry,
229 options?: EnvironmentSupervisorOptions,
230): Effect.fn.Return<
231 EnvironmentSupervisor["Service"],
232 never,
233 | Connectivity.Connectivity
234 | ConnectionDriver.ConnectionDriver
235 | Scope.Scope
236 | ConnectionWakeups.ConnectionWakeups
237> {
238 const target = entry.target;
239 const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
240 target._tag === "RelayConnectionTarget" ? ` ${NETWORK_BLOCKING_HINT}` : ""
241 }`;
242 yield* annotateTarget(target);
243​
244 const connectivity = yield* Connectivity.Connectivity;
245 const driver = yield* ConnectionDriver.ConnectionDriver;
246 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
247 const initialIntent: SupervisorIntent = {
248 desired: options?.initiallyDesired ?? false,
249 network: yield* connectivity.status,
250 };
251 const intent = yield* Ref.make(initialIntent);
252 const signals = yield* Queue.unbounded<SupervisorSignal>();
253 const resetRetryState = yield* Ref.make(false);
254 // Set while a probe of the live session is running, and kept when it fails
255 // or times out: something asked whether the connection still works and it
256 // closed or failed before answering, so the follow-up reconnect skips the
257 // first backoff rung instead of sleeping.
258 const probeUnanswered = yield* Ref.make(false);
259 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
260 !initialIntent.desired
261 ? availableState(initialIntent, 0)
262 : initialIntent.network === "offline"
263 ? offlineState(initialIntent, 0, 0, null)
264 : connectingState(initialIntent, 0, 1, null),
265 );
266 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
267 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
268​
269 const clearLease = Effect.all(
270 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
271 { discard: true },
272 );
273​
274 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
275 next: SupervisorConnectionState,
276 ) {
277 yield* SubscriptionRef.set(state, next);
278 });
279​
280 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
281 yield* Queue.offer(signals, next);
282 });
283​
284 const logManagedRelayAccountChange = Effect.logInfo(
285 "Managed relay account changed; restarting the environment connection.",
286 ).pipe(
287 Effect.annotateLogs({
288 "environment.id": target.environmentId,
289 "environment.label": target.label,
290 }),
291 );
292​
293 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
294 attempt: number,
295 generation: number,
296 lastFailure: ConnectionAttemptError | null,
297 progress: ConnectionDriver.ConnectionDriverProgress,
298 ) {
299 if ("prepared" in progress) {
300 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
301 }
302 yield* setState(
303 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
304 );
305 });
306​
307 const establishConnection = Effect.fnUntraced(function* (
308 attempt: number,
309 generation: number,
310 lastFailure: ConnectionAttemptError | null,
311 ) {
312 return yield* driver.connect(entry, (progress) =>
313 reportProgress(attempt, generation, lastFailure, progress),
314 );
315 });
316​
317 const traceRelayEstablishment = (
318 effect: Effect.Effect<
319 ConnectionDriver.EnvironmentConnectionLease,
320 ConnectionAttemptError,
321 Scope.Scope
322 >,
323 attempt: number,
324 generation: number,
325 pendingRetry: Option.Option<PendingRetryTrace>,
326 ) => {
327 const traced = Effect.gen(function* () {
328 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
329 yield* annotateTarget(target);
330 yield* Effect.annotateCurrentSpan({
331 "connection.attempt": attempt,
332 "connection.generation": generation,
333 "connection.retry.failure_count": Option.match(pendingRetry, {
334 onNone: () => 0,
335 onSome: (retry) => retry.failureCount,
336 }),
337 });
338 const lease = yield* effect.pipe(
339 Effect.mapError((error): TracedAttemptFailure => ({
340 error,
341 attemptSpan: Option.some(attemptSpan),
342 })),
343 );
344 return { attemptSpan: Option.some(attemptSpan), lease };
345 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
346​
347 return Option.match(pendingRetry, {
348 onNone: () => traced,
349 onSome: (retry) =>
350 traced.pipe(
351 Effect.linkSpans(retry.previousAttempt, {
352 "connection.retry.delay_ms": retry.delayMs,
353 "connection.retry.reason": retry.reason,
354 }),
355 ),
356 }).pipe(withRelayClientTracing);
357 };
358​
359 const establishTracedConnection = Effect.fnUntraced(function* (
360 attempt: number,
361 generation: number,
362 lastFailure: ConnectionAttemptError | null,
363 pendingRetry: Option.Option<PendingRetryTrace>,
364 ) {
365 if (target._tag === "RelayConnectionTarget") {
366 return yield* traceRelayEstablishment(
367 establishConnection(attempt, generation, lastFailure),
368 attempt,
369 generation,
370 pendingRetry,
371 );
372 }
373 return yield* establishConnection(attempt, generation, lastFailure).pipe(
374 Effect.map((lease) => ({
375 attemptSpan: Option.none<Tracer.Span>(),
376 lease,
377 })),
378 Effect.mapError((error): TracedAttemptFailure => ({
379 error,
380 attemptSpan: Option.none(),
381 })),
382 );
383 });
384​
385 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
386 for (;;) {
387 const next = yield* Queue.take(signals);
388 switch (next._tag) {
389 case "DisconnectRequested":
390 case "RetryRequested":
391 return false;
392 case "NetworkChanged":
393 if (next.network === "offline") {
394 return false;
395 }
396 break;
397 case "ConnectRequested":
398 break;
399 case "Wakeup":
400 if (next.reason === "application-active-reconnect") {
401 return true;
402 }
403 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
404 yield* logManagedRelayAccountChange;
405 return false;
406 }
407 break;
408 }
409 }
410 });
411​
412 // Signals that end a connected lease whatever its health: "reset" ends it
413 // and restarts the retry ladder, "end" ends it, undefined keeps it.
414 const connectedLeaseEnd = Effect.fnUntraced(function* (next: SupervisorSignal) {
415 if (next._tag === "DisconnectRequested") {
416 return "end" as const;
417 }
418 if (next._tag !== "Wakeup") {
419 return undefined;
420 }
421 if (next.reason === "application-active-reconnect") {
422 // Mobile operating systems often kill a suspended socket without a close
423 // event. A probe would show a dead socket as "Resuming" until it times
424 // out, so a long background resume replaces the session at once.
425 return "reset" as const;
426 }
427 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
428 yield* logManagedRelayAccountChange;
429 return "end" as const;
430 }
431 return undefined;
432 });
433​
434 // How long a signal waits for the live session to answer a probe, or
435 // undefined when the signal does not question the connection.
436 const probeTimeoutFor = (next: SupervisorSignal): Duration.Input | undefined => {
437 switch (next._tag) {
438 case "RetryRequested":
439 return QUICK_CONNECTION_PROBE_TIMEOUT;
440 case "NetworkChanged":
441 return next.network === "offline" ? QUICK_CONNECTION_PROBE_TIMEOUT : undefined;
442 case "Wakeup":
443 if (next.reason === "application-active") {
444 return CONNECTION_PROBE_TIMEOUT;
445 }
446 return next.reason === "application-active-probe"
447 ? QUICK_CONNECTION_PROBE_TIMEOUT
448 : undefined;
449 case "ConnectRequested":
450 case "DisconnectRequested":
451 return undefined;
452 }
453 };
454​
455 // Holds a connected lease until it must end, and returns whether to restart
456 // the retry ladder. Returning to the app, an explicit retry, and the network
457 // reporting offline all probe the live session instead of replacing it, so a
458 // healthy socket is not torn down (the offline report is often wrong, for
459 // example for a loopback server). Only a long mobile resume replaces the
460 // session without a probe. A failed probe fails this effect, and the
461 // supervisor reconnects.
462 const monitorConnectedLease = Effect.fnUntraced(function* (
463 lease: ConnectionDriver.EnvironmentConnectionLease,
464 ) {
465 // A probe answers an explicit retry here, so the retry must not also reset
466 // the backoff of a later, unrelated failure.
467 const takeSignal = Queue.take(signals).pipe(
468 Effect.tap((next) =>
469 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
470 ),
471 );
472 for (;;) {
473 const next = yield* takeSignal;
474 const end = yield* connectedLeaseEnd(next);
475 if (end !== undefined) {
476 return end === "reset";
477 }
478 const probeTimeout = probeTimeoutFor(next);
479 if (probeTimeout === undefined) {
480 continue;
481 }
482 yield* Ref.set(probeUnanswered, true);
483 const probe = yield* lease.session.probe.pipe(
484 Effect.timeoutOrElse({
485 duration: probeTimeout,
486 orElse: () =>
487 Effect.fail(
488 new ConnectionTransientError({
489 reason: "timeout",
490 detail: `${target.label} did not respond to a connection health check.`,
491 }),
492 ),
493 }),
494 Effect.forkChild,
495 );
496 for (;;) {
497 const probeEvent = yield* Effect.raceFirst(
498 Fiber.await(probe).pipe(
499 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
500 ),
501 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
502 );
503 if (probeEvent._tag === "ProbeCompleted") {
504 if (Exit.isSuccess(probeEvent.exit)) {
505 yield* Ref.set(probeUnanswered, false);
506 }
507 yield* probeEvent.exit;
508 break;
509 }
510 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal);
511 if (endDuringProbe !== undefined) {
512 yield* Fiber.interrupt(probe);
513 return endDuringProbe === "reset";
514 }
515 }
516 }
517 });
518​
519 const runAttempt = Effect.fnUntraced(function* (
520 attempt: number,
521 generation: number,
522 lastFailure: ConnectionAttemptError | null,
523 pendingRetry: Option.Option<PendingRetryTrace>,
524 ignoreOffline: boolean,
525 ) {
526 yield* SubscriptionRef.set(prepared, Option.none());
527 const establishment = yield* Effect.raceAllFirst([
528 exitUnlessInterrupted(
529 establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
530 ).pipe(
531 Effect.map((exit): EstablishmentEvent => ({
532 _tag: "Completed",
533 exit,
534 })),
535 ),
536 waitForEstablishmentInterrupt().pipe(
537 Effect.map((resetRetry): EstablishmentEvent => ({
538 _tag: "Interrupted",
539 resetRetry,
540 })),
541 ),
542 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
543 Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
544 ),
545 ]);
546​
547 if (establishment._tag === "Interrupted") {
548 return {
549 _tag: "Interrupted",
550 established: false,
551 stable: false,
552 resetRetry: establishment.resetRetry,
553 } satisfies AttemptOutcome;
554 }
555 if (establishment._tag === "TimedOut") {
556 return {
557 _tag: "Failure",
558 established: false,
559 stable: false,
560 failure: {
561 error: new ConnectionTransientError({
562 reason: "timeout",
563 detail: setupTimeoutDetail,
564 }),
565 attemptSpan: Option.none(),
566 },
567 } satisfies AttemptOutcome;
568 }
569 if (Exit.isFailure(establishment.exit)) {
570 const isUnexpectedDefect =
571 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
572 !establishment.exit.cause.reasons.some(Cause.isFailReason);
573 const outcome = failureFromExit(target, establishment.exit, false, false);
574 if (isUnexpectedDefect) {
575 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
576 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
577 Effect.annotateLogs({
578 "environment.id": target.environmentId,
579 "environment.label": target.label,
580 "cause.reason_count": establishment.exit.cause.reasons.length,
581 ...safeErrorLogAttributes(defect),
582 }),
583 );
584 }
585 return outcome;
586 }
587​
588 const active = establishment.exit.value;
589 const currentIntent = yield* Ref.get(intent);
590 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
591 return {
592 _tag: "Interrupted",
593 established: false,
594 stable: false,
595 resetRetry: false,
596 } satisfies AttemptOutcome;
597 }
598​
599 const connectedAt = yield* Clock.currentTimeMillis;
600 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
601 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
602 yield* setState({
603 desired: true,
604 network: currentIntent.network,
605 phase: "connected",
606 stage: null,
607 attempt,
608 generation,
609 lastFailure: null,
610 retryAt: null,
611 });
612​
613 const connectedExit = yield* Effect.raceFirst(
614 active.lease.session.closed.pipe(
615 Effect.mapError((error): TracedAttemptFailure => ({
616 error,
617 attemptSpan: active.attemptSpan,
618 })),
619 ),
620 monitorConnectedLease(active.lease).pipe(
621 Effect.mapError((error): TracedAttemptFailure => ({
622 error,
623 attemptSpan: active.attemptSpan,
624 })),
625 ),
626 ).pipe(exitUnlessInterrupted);
627 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
628 if (Exit.isSuccess(connectedExit)) {
629 return {
630 _tag: "Interrupted",
631 established: true,
632 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
633 resetRetry: connectedExit.value,
634 } satisfies AttemptOutcome;
635 }
636 return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
637 }, Effect.ensuring(clearLease));
638​
639 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
640 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
641 return yield* Effect.raceFirst(
642 Effect.sleep(delayMs).pipe(Effect.as(false)),
643 Effect.gen(function* () {
644 for (;;) {
645 const next = yield* Queue.take(signals);
646 switch (next._tag) {
647 case "Wakeup":
648 return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
649 case "ConnectRequested":
650 case "DisconnectRequested":
651 case "RetryRequested":
652 case "NetworkChanged":
653 return false;
654 }
655 }
656 }),
657 );
658 });
659​
660 const waitForSignal = Queue.take(signals).pipe(
661 Effect.map(
662 (next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
663 ),
664 );
665​
666 const run = Effect.fnUntraced(function* () {
667 let failureCount = 0;
668 let generation = 0;
669 let latestFailure: ConnectionAttemptError | null = null;
670 let pendingRetry = Option.none<PendingRetryTrace>();
671 const resetRetryLadder = () => {
672 failureCount = 0;
673 pendingRetry = Option.none();
674 };
675 // Set after a long resume ends an attempt or a session. The fresh attempt
676 // runs even while the network reports offline: the report is often wrong,
677 // and the replaced session must not leave the client offline.
678 let replacing = false;
679​
680 for (;;) {
681 if (yield* Ref.getAndSet(resetRetryState, false)) {
682 failureCount = 0;
683 latestFailure = null;
684 pendingRetry = Option.none();
685 }
686 const currentIntent = yield* Ref.get(intent);
687 if (!currentIntent.desired) {
688 resetRetryLadder();
689 latestFailure = null;
690 yield* clearLease;
691 yield* setState(availableState(currentIntent, generation));
692 yield* waitForSignal;
693 continue;
694 }
695 if (currentIntent.network === "offline" && !replacing) {
696 yield* clearLease;
697 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
698 const applicationActivated = yield* waitForSignal;
699 if (applicationActivated) {
700 resetRetryLadder();
701 }
702 continue;
703 }
704​
705 const attempt = failureCount + 1;
706 const nextGeneration = generation + 1;
707 const outcome: AttemptOutcome = yield* Effect.scoped(
708 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
709 );
710 replacing = false;
711 // Consumed on every iteration so a stale marker can never leak into a
712 // later, unrelated failure.
713 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
714 if (outcome.established) {
715 generation = nextGeneration;
716 if (outcome.stable) {
717 resetRetryLadder();
718 latestFailure = null;
719 }
720 }
721 if (outcome._tag === "Interrupted") {
722 if (outcome.resetRetry) {
723 resetRetryLadder();
724 replacing = true;
725 }
726 continue;
727 }
728​
729 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
730 const error: ConnectionAttemptError = outcome.failure.error;
731 latestFailure = error;
732 if (error._tag === "ConnectionBlockedError") {
733 const blockedIntent = yield* Ref.get(intent);
734 yield* setState({
735 desired: blockedIntent.desired,
736 network: blockedIntent.network,
737 phase: "blocked",
738 stage: null,
739 attempt,
740 generation,
741 lastFailure: error,
742 retryAt: null,
743 });
744 const applicationActivated = yield* waitForSignal;
745 if (applicationActivated) {
746 resetRetryLadder();
747 }
748 continue;
749 }
750​
751 if (failedProbe) {
752 // A probe found a dead transport, or the transport closed while a probe
753 // waited for an answer (the user returned to the app, asked to retry,
754 // or the network changed), so reconnect immediately instead
755 // of sleeping the first backoff rung. Only this first attempt skips the
756 // ladder; if it fails too, normal backoff resumes.
757 resetRetryLadder();
758 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, error));
759 continue;
760 }
761​
762 failureCount += 1;
763 const delayMs = retryDelayMs(failureCount - 1, yield* Random.next);
764 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
765 previousAttempt,
766 failureCount,
767 delayMs,
768 reason: error.reason,
769 }));
770 const failedIntent = yield* Ref.get(intent);
771 yield* setState({
772 desired: failedIntent.desired,
773 network: failedIntent.network,
774 phase: "backoff",
775 stage: null,
776 attempt,
777 generation,
778 lastFailure: error,
779 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
780 });
781 const applicationActivated = yield* waitForRetrySignal(delayMs);
782 if (applicationActivated) {
783 resetRetryLadder();
784 }
785 }
786 });
787​
788 yield* connectivity.changes.pipe(
789 Stream.runForEach((network) =>
790 Ref.modify(intent, (current) =>
791 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
792 ).pipe(
793 Effect.flatMap((changed) =>
794 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
795 ),
796 ),
797 ),
798 Effect.forkScoped,
799 );
800 yield* wakeups.changes.pipe(
801 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
802 Effect.forkScoped,
803 );
804 yield* run().pipe(Effect.forkScoped);
805​
806 const connect = Ref.update(intent, (current) => ({
807 ...current,
808 desired: true,
809 })).pipe(
810 Effect.andThen(signal({ _tag: "ConnectRequested" })),
811 Effect.withSpan("EnvironmentSupervisor.connect"),
812 );
813​
814 const disconnect = Ref.update(intent, (current) => ({
815 ...current,
816 desired: false,
817 })).pipe(
818 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
819 Effect.withSpan("EnvironmentSupervisor.disconnect"),
820 );
821​
822 const retryNow = Ref.set(resetRetryState, true).pipe(
823 Effect.andThen(signal({ _tag: "RetryRequested" })),
824 Effect.withSpan("EnvironmentSupervisor.retryNow"),
825 );
826​
827 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
828​
829 return EnvironmentSupervisor.of({
830 target,
831 state,
832 session,
833 prepared,
834 connect,
835 disconnect,
836 retryNow,
837 });
838});