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

supervisor.ts

847 lines28.2 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 } 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* Effect.forkChild(lease.session.probe);
484 // Monotonic nanoseconds, so a wall-clock correction cannot move the deadline.
485 let deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
486 for (;;) {
487 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
488 const probeEvent = yield* Effect.raceAllFirst([
489 Fiber.await(probe).pipe(
490 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
491 ),
492 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
493 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
494 Effect.as({ _tag: "TimedOut" as const }),
495 ),
496 ]);
497 if (probeEvent._tag === "TimedOut") {
498 yield* Fiber.interrupt(probe);
499 return yield* new ConnectionTransientError({
500 reason: "timeout",
501 detail: `${target.label} did not respond to a connection health check.`,
502 });
503 }
504 if (probeEvent._tag === "ProbeCompleted") {
505 if (Exit.isSuccess(probeEvent.exit)) {
506 yield* Ref.set(probeUnanswered, false);
507 }
508 yield* probeEvent.exit;
509 break;
510 }
511 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal);
512 if (endDuringProbe !== undefined) {
513 yield* Fiber.interrupt(probe);
514 return endDuringProbe === "reset";
515 }
516 // A retry or an offline report during a desktop foreground probe wants
517 // its quicker answer, so it shortens the running probe.
518 const signalTimeout = probeTimeoutFor(probeEvent.signal);
519 if (signalTimeout !== undefined) {
520 const signalDeadline =
521 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
522 if (signalDeadline < deadline) deadline = signalDeadline;
523 }
524 }
525 }
526 });
527​
528 const runAttempt = Effect.fnUntraced(function* (
529 attempt: number,
530 generation: number,
531 lastFailure: ConnectionAttemptError | null,
532 pendingRetry: Option.Option<PendingRetryTrace>,
533 ignoreOffline: boolean,
534 ) {
535 yield* SubscriptionRef.set(prepared, Option.none());
536 const establishment = yield* Effect.raceAllFirst([
537 exitUnlessInterrupted(
538 establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
539 ).pipe(
540 Effect.map((exit): EstablishmentEvent => ({
541 _tag: "Completed",
542 exit,
543 })),
544 ),
545 waitForEstablishmentInterrupt().pipe(
546 Effect.map((resetRetry): EstablishmentEvent => ({
547 _tag: "Interrupted",
548 resetRetry,
549 })),
550 ),
551 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
552 Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
553 ),
554 ]);
555​
556 if (establishment._tag === "Interrupted") {
557 return {
558 _tag: "Interrupted",
559 established: false,
560 stable: false,
561 resetRetry: establishment.resetRetry,
562 } satisfies AttemptOutcome;
563 }
564 if (establishment._tag === "TimedOut") {
565 return {
566 _tag: "Failure",
567 established: false,
568 stable: false,
569 failure: {
570 error: new ConnectionTransientError({
571 reason: "timeout",
572 detail: setupTimeoutDetail,
573 }),
574 attemptSpan: Option.none(),
575 },
576 } satisfies AttemptOutcome;
577 }
578 if (Exit.isFailure(establishment.exit)) {
579 const isUnexpectedDefect =
580 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
581 !establishment.exit.cause.reasons.some(Cause.isFailReason);
582 const outcome = failureFromExit(target, establishment.exit, false, false);
583 if (isUnexpectedDefect) {
584 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
585 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
586 Effect.annotateLogs({
587 "environment.id": target.environmentId,
588 "environment.label": target.label,
589 "cause.reason_count": establishment.exit.cause.reasons.length,
590 ...safeErrorLogAttributes(defect),
591 }),
592 );
593 }
594 return outcome;
595 }
596​
597 const active = establishment.exit.value;
598 const currentIntent = yield* Ref.get(intent);
599 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
600 return {
601 _tag: "Interrupted",
602 established: false,
603 stable: false,
604 resetRetry: false,
605 } satisfies AttemptOutcome;
606 }
607​
608 const connectedAt = yield* Clock.currentTimeMillis;
609 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
610 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
611 yield* setState({
612 desired: true,
613 network: currentIntent.network,
614 phase: "connected",
615 stage: null,
616 attempt,
617 generation,
618 lastFailure: null,
619 retryAt: null,
620 });
621​
622 const connectedExit = yield* Effect.raceFirst(
623 active.lease.session.closed.pipe(
624 Effect.mapError((error): TracedAttemptFailure => ({
625 error,
626 attemptSpan: active.attemptSpan,
627 })),
628 ),
629 monitorConnectedLease(active.lease).pipe(
630 Effect.mapError((error): TracedAttemptFailure => ({
631 error,
632 attemptSpan: active.attemptSpan,
633 })),
634 ),
635 ).pipe(exitUnlessInterrupted);
636 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
637 if (Exit.isSuccess(connectedExit)) {
638 return {
639 _tag: "Interrupted",
640 established: true,
641 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
642 resetRetry: connectedExit.value,
643 } satisfies AttemptOutcome;
644 }
645 return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
646 }, Effect.ensuring(clearLease));
647​
648 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
649 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
650 return yield* Effect.raceFirst(
651 Effect.sleep(delayMs).pipe(Effect.as(false)),
652 Effect.gen(function* () {
653 for (;;) {
654 const next = yield* Queue.take(signals);
655 switch (next._tag) {
656 case "Wakeup":
657 return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
658 case "ConnectRequested":
659 case "DisconnectRequested":
660 case "RetryRequested":
661 case "NetworkChanged":
662 return false;
663 }
664 }
665 }),
666 );
667 });
668​
669 const waitForSignal = Queue.take(signals).pipe(
670 Effect.map(
671 (next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
672 ),
673 );
674​
675 const run = Effect.fnUntraced(function* () {
676 let failureCount = 0;
677 let generation = 0;
678 let latestFailure: ConnectionAttemptError | null = null;
679 let pendingRetry = Option.none<PendingRetryTrace>();
680 const resetRetryLadder = () => {
681 failureCount = 0;
682 pendingRetry = Option.none();
683 };
684 // Set after a long resume ends an attempt or a session. The fresh attempt
685 // runs even while the network reports offline: the report is often wrong,
686 // and the replaced session must not leave the client offline.
687 let replacing = false;
688​
689 for (;;) {
690 if (yield* Ref.getAndSet(resetRetryState, false)) {
691 failureCount = 0;
692 latestFailure = null;
693 pendingRetry = Option.none();
694 }
695 const currentIntent = yield* Ref.get(intent);
696 if (!currentIntent.desired) {
697 resetRetryLadder();
698 latestFailure = null;
699 yield* clearLease;
700 yield* setState(availableState(currentIntent, generation));
701 yield* waitForSignal;
702 continue;
703 }
704 if (currentIntent.network === "offline" && !replacing) {
705 yield* clearLease;
706 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
707 const applicationActivated = yield* waitForSignal;
708 if (applicationActivated) {
709 resetRetryLadder();
710 }
711 continue;
712 }
713​
714 const attempt = failureCount + 1;
715 const nextGeneration = generation + 1;
716 const outcome: AttemptOutcome = yield* Effect.scoped(
717 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
718 );
719 replacing = false;
720 // Consumed on every iteration so a stale marker can never leak into a
721 // later, unrelated failure.
722 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
723 if (outcome.established) {
724 generation = nextGeneration;
725 if (outcome.stable) {
726 resetRetryLadder();
727 latestFailure = null;
728 }
729 }
730 if (outcome._tag === "Interrupted") {
731 if (outcome.resetRetry) {
732 resetRetryLadder();
733 replacing = true;
734 }
735 continue;
736 }
737​
738 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
739 const error: ConnectionAttemptError = outcome.failure.error;
740 latestFailure = error;
741 if (error._tag === "ConnectionBlockedError") {
742 const blockedIntent = yield* Ref.get(intent);
743 yield* setState({
744 desired: blockedIntent.desired,
745 network: blockedIntent.network,
746 phase: "blocked",
747 stage: null,
748 attempt,
749 generation,
750 lastFailure: error,
751 retryAt: null,
752 });
753 const applicationActivated = yield* waitForSignal;
754 if (applicationActivated) {
755 resetRetryLadder();
756 }
757 continue;
758 }
759​
760 if (failedProbe) {
761 // A probe found a dead transport, or the transport closed while a probe
762 // waited for an answer (the user returned to the app, asked to retry,
763 // or the network changed), so reconnect immediately instead
764 // of sleeping the first backoff rung. Only this first attempt skips the
765 // ladder; if it fails too, normal backoff resumes.
766 resetRetryLadder();
767 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, error));
768 continue;
769 }
770​
771 failureCount += 1;
772 const delayMs = retryDelayMs(failureCount - 1, yield* Random.next);
773 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
774 previousAttempt,
775 failureCount,
776 delayMs,
777 reason: error.reason,
778 }));
779 const failedIntent = yield* Ref.get(intent);
780 yield* setState({
781 desired: failedIntent.desired,
782 network: failedIntent.network,
783 phase: "backoff",
784 stage: null,
785 attempt,
786 generation,
787 lastFailure: error,
788 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
789 });
790 const applicationActivated = yield* waitForRetrySignal(delayMs);
791 if (applicationActivated) {
792 resetRetryLadder();
793 }
794 }
795 });
796​
797 yield* connectivity.changes.pipe(
798 Stream.runForEach((network) =>
799 Ref.modify(intent, (current) =>
800 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
801 ).pipe(
802 Effect.flatMap((changed) =>
803 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
804 ),
805 ),
806 ),
807 Effect.forkScoped,
808 );
809 yield* wakeups.changes.pipe(
810 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
811 Effect.forkScoped,
812 );
813 yield* run().pipe(Effect.forkScoped);
814​
815 const connect = Ref.update(intent, (current) => ({
816 ...current,
817 desired: true,
818 })).pipe(
819 Effect.andThen(signal({ _tag: "ConnectRequested" })),
820 Effect.withSpan("EnvironmentSupervisor.connect"),
821 );
822​
823 const disconnect = Ref.update(intent, (current) => ({
824 ...current,
825 desired: false,
826 })).pipe(
827 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
828 Effect.withSpan("EnvironmentSupervisor.disconnect"),
829 );
830​
831 const retryNow = Ref.set(resetRetryState, true).pipe(
832 Effect.andThen(signal({ _tag: "RetryRequested" })),
833 Effect.withSpan("EnvironmentSupervisor.retryNow"),
834 );
835​
836 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
837​
838 return EnvironmentSupervisor.of({
839 target,
840 state,
841 session,
842 prepared,
843 connect,
844 disconnect,
845 retryNow,
846 });
847});