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

supervisor.ts

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