Open History to see the last commit
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 Option from "effect/Option";
9import * as Queue from "effect/Queue";
10import * as Ref from "effect/Ref";
11import * as Scope from "effect/Scope";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import * as Tracer from "effect/Tracer";
15
16import type { ConnectionCatalogEntry } from "./catalog.ts";
17import * as Connectivity from "./connectivity.ts";
18import * as ConnectionDriver from "./driver.ts";
19import {
20 type ConnectionAttemptError,
21 type ConnectionTarget,
22 ConnectionTransientError,
23 type NetworkStatus,
24 type PreparedConnection,
25 type SupervisorConnectionState,
26} from "./model.ts";
27import * as RpcSession from "../rpc/session.ts";
28import { safeErrorLogAttributes } from "../errors/safeLog.ts";
29import { NETWORK_BLOCKING_HINT } from "../errors/network.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;
41}
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"];
55}
56
57interface TracedAttemptFailure {
58 readonly error: ConnectionAttemptError;
59 readonly attemptSpan: Option.Option<Tracer.Span>;
60}
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 });
98}
99
100export interface EnvironmentSupervisorOptions {
101 readonly initiallyDesired?: boolean;
102}
103
104function retryDelayMs(failureCount: number): number {
105 return RETRY_DELAYS_MS[Math.min(failureCount, RETRY_DELAYS_MS.length - 1)] ?? 16_000;
106}
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 });
114}
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 };
127}
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 };
145}
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 };
164}
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 };
196}
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 const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
224 target._tag === "RelayConnectionTarget" ? ` ${NETWORK_BLOCKING_HINT}` : ""
225 }`;
226 yield* annotateTarget(target);
227
228 const connectivity = yield* Connectivity.Connectivity;
229 const driver = yield* ConnectionDriver.ConnectionDriver;
230 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
231 const initialIntent: SupervisorIntent = {
232 desired: options?.initiallyDesired ?? false,
233 network: yield* connectivity.status,
234 };
235 const intent = yield* Ref.make(initialIntent);
236 const signals = yield* Queue.unbounded<SupervisorSignal>();
237 const resetRetryState = yield* Ref.make(false);
238 // Set when a foreground wake probe fails or times out: the user is actively
239 // returning to the app on a dead transport, so the follow-up reconnect skips
240 // the first backoff rung instead of sleeping.
241 const wakeProbeFailed = yield* Ref.make(false);
242 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
243 !initialIntent.desired
244 ? availableState(initialIntent, 0)
245 : initialIntent.network === "offline"
246 ? offlineState(initialIntent, 0, 0, null)
247 : connectingState(initialIntent, 0, 1, null),
248 );
249 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
250 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
251
252 const clearLease = Effect.all(
253 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
254 { discard: true },
255 );
256
257 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
258 next: SupervisorConnectionState,
259 ) {
260 yield* SubscriptionRef.set(state, next);
261 });
262
263 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
264 yield* Queue.offer(signals, next);
265 });
266
267 const logManagedRelayAccountChange = Effect.logInfo(
268 "Managed relay account changed; restarting the environment connection.",
269 ).pipe(
270 Effect.annotateLogs({
271 "environment.id": target.environmentId,
272 "environment.label": target.label,
273 }),
274 );
275
276 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
277 attempt: number,
278 generation: number,
279 lastFailure: ConnectionAttemptError | null,
280 progress: ConnectionDriver.ConnectionDriverProgress,
281 ) {
282 if ("prepared" in progress) {
283 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
284 }
285 yield* setState(
286 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
287 );
288 });
289
290 const establishConnection = Effect.fnUntraced(function* (
291 attempt: number,
292 generation: number,
293 lastFailure: ConnectionAttemptError | null,
294 ) {
295 return yield* driver.connect(entry, (progress) =>
296 reportProgress(attempt, generation, lastFailure, progress),
297 );
298 });
299
300 const traceRelayEstablishment = (
301 effect: Effect.Effect<
302 ConnectionDriver.EnvironmentConnectionLease,
303 ConnectionAttemptError,
304 Scope.Scope
305 >,
306 attempt: number,
307 generation: number,
308 pendingRetry: Option.Option<PendingRetryTrace>,
309 ) => {
310 const traced = Effect.gen(function* () {
311 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
312 yield* annotateTarget(target);
313 yield* Effect.annotateCurrentSpan({
314 "connection.attempt": attempt,
315 "connection.generation": generation,
316 "connection.retry.failure_count": Option.match(pendingRetry, {
317 onNone: () => 0,
318 onSome: (retry) => retry.failureCount,
319 }),
320 });
321 const lease = yield* effect.pipe(
322 Effect.mapError((error): TracedAttemptFailure => ({
323 error,
324 attemptSpan: Option.some(attemptSpan),
325 })),
326 );
327 return { attemptSpan: Option.some(attemptSpan), lease };
328 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
329
330 return Option.match(pendingRetry, {
331 onNone: () => traced,
332 onSome: (retry) =>
333 traced.pipe(
334 Effect.linkSpans(retry.previousAttempt, {
335 "connection.retry.delay_ms": retry.delayMs,
336 "connection.retry.reason": retry.reason,
337 }),
338 ),
339 }).pipe(withRelayClientTracing);
340 };
341
342 const establishTracedConnection = Effect.fnUntraced(function* (
343 attempt: number,
344 generation: number,
345 lastFailure: ConnectionAttemptError | null,
346 pendingRetry: Option.Option<PendingRetryTrace>,
347 ) {
348 if (target._tag === "RelayConnectionTarget") {
349 return yield* traceRelayEstablishment(
350 establishConnection(attempt, generation, lastFailure),
351 attempt,
352 generation,
353 pendingRetry,
354 );
355 }
356 return yield* establishConnection(attempt, generation, lastFailure).pipe(
357 Effect.map((lease) => ({
358 attemptSpan: Option.none<Tracer.Span>(),
359 lease,
360 })),
361 Effect.mapError((error): TracedAttemptFailure => ({
362 error,
363 attemptSpan: Option.none(),
364 })),
365 );
366 });
367
368 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
369 for (;;) {
370 const next = yield* Queue.take(signals);
371 switch (next._tag) {
372 case "DisconnectRequested":
373 case "RetryRequested":
374 return false;
375 case "NetworkChanged":
376 if (next.network === "offline") {
377 return false;
378 }
379 break;
380 case "ConnectRequested":
381 break;
382 case "Wakeup":
383 if (next.reason === "application-active-reconnect") {
384 return true;
385 }
386 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
387 yield* logManagedRelayAccountChange;
388 return false;
389 }
390 break;
391 }
392 }
393 });
394
395 const monitorConnectedLease = Effect.fnUntraced(function* (
396 lease: ConnectionDriver.EnvironmentConnectionLease,
397 ) {
398 for (;;) {
399 const next = yield* Queue.take(signals);
400 switch (next._tag) {
401 case "DisconnectRequested":
402 case "RetryRequested":
403 return false;
404 case "NetworkChanged":
405 if (next.network === "offline") {
406 return false;
407 }
408 break;
409 case "Wakeup":
410 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
411 yield* logManagedRelayAccountChange;
412 return false;
413 }
414 if (next.reason === "application-active-reconnect") {
415 // Mobile operating systems commonly suspend sockets without
416 // delivering a close event. A long background resume deliberately
417 // replaces that lease and starts a fresh attempt without backoff.
418 return true;
419 }
420 if (next.reason === "application-active" || next.reason === "application-active-probe") {
421 const probe = yield* lease.session.probe.pipe(
422 Effect.timeoutOrElse({
423 duration:
424 next.reason === "application-active-probe"
425 ? MOBILE_CONNECTION_PROBE_TIMEOUT
426 : CONNECTION_PROBE_TIMEOUT,
427 orElse: () =>
428 Effect.fail(
429 new ConnectionTransientError({
430 reason: "timeout",
431 detail: `${target.label} did not respond to a connection health check.`,
432 }),
433 ),
434 }),
435 Effect.forkChild,
436 );
437 for (;;) {
438 const probeEvent = yield* Effect.raceFirst(
439 Fiber.await(probe).pipe(
440 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
441 ),
442 Queue.take(signals).pipe(
443 Effect.map((signal) => ({ _tag: "Signal" as const, signal })),
444 ),
445 );
446 if (probeEvent._tag === "ProbeCompleted") {
447 if (Exit.isFailure(probeEvent.exit)) {
448 yield* Ref.set(wakeProbeFailed, true);
449 }
450 yield* probeEvent.exit;
451 break;
452 }
453 switch (probeEvent.signal._tag) {
454 case "DisconnectRequested":
455 case "RetryRequested":
456 yield* Fiber.interrupt(probe);
457 return false;
458 case "NetworkChanged":
459 if (probeEvent.signal.network === "offline") {
460 yield* Fiber.interrupt(probe);
461 return false;
462 }
463 break;
464 case "Wakeup":
465 if (probeEvent.signal.reason === "application-active-reconnect") {
466 yield* Fiber.interrupt(probe);
467 return true;
468 }
469 if (
470 probeEvent.signal.reason === "credentials-changed" &&
471 target._tag === "RelayConnectionTarget"
472 ) {
473 yield* Fiber.interrupt(probe);
474 return false;
475 }
476 break;
477 case "ConnectRequested":
478 break;
479 }
480 }
481 }
482 break;
483 case "ConnectRequested":
484 break;
485 }
486 }
487 });
488
489 const runAttempt = Effect.fnUntraced(function* (
490 attempt: number,
491 generation: number,
492 lastFailure: ConnectionAttemptError | null,
493 pendingRetry: Option.Option<PendingRetryTrace>,
494 ) {
495 yield* SubscriptionRef.set(prepared, Option.none());
496 const establishment = yield* Effect.raceAllFirst([
497 exitUnlessInterrupted(
498 establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
499 ).pipe(
500 Effect.map((exit): EstablishmentEvent => ({
501 _tag: "Completed",
502 exit,
503 })),
504 ),
505 waitForEstablishmentInterrupt().pipe(
506 Effect.map((resetRetry): EstablishmentEvent => ({
507 _tag: "Interrupted",
508 resetRetry,
509 })),
510 ),
511 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
512 Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
513 ),
514 ]);
515
516 if (establishment._tag === "Interrupted") {
517 return {
518 _tag: "Interrupted",
519 established: false,
520 stable: false,
521 resetRetry: establishment.resetRetry,
522 } satisfies AttemptOutcome;
523 }
524 if (establishment._tag === "TimedOut") {
525 return {
526 _tag: "Failure",
527 established: false,
528 stable: false,
529 failure: {
530 error: new ConnectionTransientError({
531 reason: "timeout",
532 detail: setupTimeoutDetail,
533 }),
534 attemptSpan: Option.none(),
535 },
536 } satisfies AttemptOutcome;
537 }
538 if (Exit.isFailure(establishment.exit)) {
539 const isUnexpectedDefect =
540 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
541 !establishment.exit.cause.reasons.some(Cause.isFailReason);
542 const outcome = failureFromExit(target, establishment.exit, false, false);
543 if (isUnexpectedDefect) {
544 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
545 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
546 Effect.annotateLogs({
547 "environment.id": target.environmentId,
548 "environment.label": target.label,
549 "cause.reason_count": establishment.exit.cause.reasons.length,
550 ...safeErrorLogAttributes(defect),
551 }),
552 );
553 }
554 return outcome;
555 }
556
557 const active = establishment.exit.value;
558 const currentIntent = yield* Ref.get(intent);
559 if (!currentIntent.desired || currentIntent.network === "offline") {
560 return {
561 _tag: "Interrupted",
562 established: false,
563 stable: false,
564 resetRetry: false,
565 } satisfies AttemptOutcome;
566 }
567
568 const connectedAt = yield* Clock.currentTimeMillis;
569 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
570 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
571 yield* setState({
572 desired: true,
573 network: currentIntent.network,
574 phase: "connected",
575 stage: null,
576 attempt,
577 generation,
578 lastFailure: null,
579 retryAt: null,
580 });
581
582 const connectedExit = yield* Effect.raceFirst(
583 active.lease.session.closed.pipe(
584 Effect.mapError((error): TracedAttemptFailure => ({
585 error,
586 attemptSpan: active.attemptSpan,
587 })),
588 ),
589 monitorConnectedLease(active.lease).pipe(
590 Effect.mapError((error): TracedAttemptFailure => ({
591 error,
592 attemptSpan: active.attemptSpan,
593 })),
594 ),
595 ).pipe(exitUnlessInterrupted);
596 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
597 if (Exit.isSuccess(connectedExit)) {
598 return {
599 _tag: "Interrupted",
600 established: true,
601 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
602 resetRetry: connectedExit.value,
603 } satisfies AttemptOutcome;
604 }
605 return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
606 }, Effect.ensuring(clearLease));
607
608 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
609 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
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});