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

supervisor.ts

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