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 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 DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS,
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 * 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;
42}
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"];
56}
57
58interface TracedAttemptFailure {
59 readonly error: ConnectionAttemptError;
60 readonly attemptSpan: Option.Option<Tracer.Span>;
61}
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 });
99}
100
101export interface EnvironmentSupervisorOptions {
102 readonly initiallyDesired?: boolean;
103}
104
105function retryDelayMs(failureCount: number): number {
106 return RETRY_DELAYS_MS[Math.min(failureCount, RETRY_DELAYS_MS.length - 1)] ?? 16_000;
107}
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 });
115}
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 };
128}
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 };
146}
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 };
165}
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 };
197}
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 yield* annotateTarget(target);
225
226 const connectivity = yield* Connectivity.Connectivity;
227 const driver = yield* ConnectionDriver.ConnectionDriver;
228 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
229 const initialIntent: SupervisorIntent = {
230 desired: options?.initiallyDesired ?? false,
231 network: yield* connectivity.status,
232 };
233 const intent = yield* Ref.make(initialIntent);
234 const signals = yield* Queue.unbounded<SupervisorSignal>();
235 const resetRetryState = yield* Ref.make(false);
236 // Set when a foreground wake probe fails or times out: the user is actively
237 // returning to the app on a dead transport, so the follow-up reconnect skips
238 // the first backoff rung instead of sleeping.
239 const wakeProbeFailed = yield* Ref.make(false);
240 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
241 !initialIntent.desired
242 ? availableState(initialIntent, 0)
243 : initialIntent.network === "offline"
244 ? offlineState(initialIntent, 0, 0, null)
245 : connectingState(initialIntent, 0, 1, null),
246 );
247 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
248 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
249
250 const clearLease = Effect.all(
251 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
252 { discard: true },
253 );
254
255 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
256 next: SupervisorConnectionState,
257 ) {
258 yield* SubscriptionRef.set(state, next);
259 });
260
261 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
262 yield* Queue.offer(signals, next);
263 });
264
265 const logManagedRelayAccountChange = Effect.logInfo(
266 "Managed relay account changed; restarting the environment connection.",
267 ).pipe(
268 Effect.annotateLogs({
269 "environment.id": target.environmentId,
270 "environment.label": target.label,
271 }),
272 );
273
274 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
275 attempt: number,
276 generation: number,
277 lastFailure: ConnectionAttemptError | null,
278 progress: ConnectionDriver.ConnectionDriverProgress,
279 ) {
280 if ("prepared" in progress) {
281 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
282 }
283 yield* setState(
284 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
285 );
286 });
287
288 const establishConnection = Effect.fnUntraced(function* (
289 attempt: number,
290 generation: number,
291 lastFailure: ConnectionAttemptError | null,
292 ) {
293 return yield* driver.connect(entry, (progress) =>
294 reportProgress(attempt, generation, lastFailure, progress),
295 );
296 });
297
298 const traceRelayEstablishment = (
299 effect: Effect.Effect<
300 ConnectionDriver.EnvironmentConnectionLease,
301 ConnectionAttemptError,
302 Scope.Scope
303 >,
304 attempt: number,
305 generation: number,
306 pendingRetry: Option.Option<PendingRetryTrace>,
307 ) => {
308 const traced = Effect.gen(function* () {
309 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
310 yield* annotateTarget(target);
311 yield* Effect.annotateCurrentSpan({
312 "connection.attempt": attempt,
313 "connection.generation": generation,
314 "connection.retry.failure_count": Option.match(pendingRetry, {
315 onNone: () => 0,
316 onSome: (retry) => retry.failureCount,
317 }),
318 });
319 const lease = yield* effect.pipe(
320 Effect.mapError((error): TracedAttemptFailure => ({
321 error,
322 attemptSpan: Option.some(attemptSpan),
323 })),
324 );
325 return { attemptSpan: Option.some(attemptSpan), lease };
326 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
327
328 return Option.match(pendingRetry, {
329 onNone: () => traced,
330 onSome: (retry) =>
331 traced.pipe(
332 Effect.linkSpans(retry.previousAttempt, {
333 "connection.retry.delay_ms": retry.delayMs,
334 "connection.retry.reason": retry.reason,
335 }),
336 ),
337 }).pipe(withRelayClientTracing);
338 };
339
340 const establishTracedConnection = Effect.fnUntraced(function* (
341 attempt: number,
342 generation: number,
343 lastFailure: ConnectionAttemptError | null,
344 pendingRetry: Option.Option<PendingRetryTrace>,
345 ) {
346 if (target._tag === "RelayConnectionTarget") {
347 return yield* traceRelayEstablishment(
348 establishConnection(attempt, generation, lastFailure),
349 attempt,
350 generation,
351 pendingRetry,
352 );
353 }
354 return yield* establishConnection(attempt, generation, lastFailure).pipe(
355 Effect.map((lease) => ({
356 attemptSpan: Option.none<Tracer.Span>(),
357 lease,
358 })),
359 Effect.mapError((error): TracedAttemptFailure => ({
360 error,
361 attemptSpan: Option.none(),
362 })),
363 );
364 });
365
366 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
367 for (;;) {
368 const next = yield* Queue.take(signals);
369 switch (next._tag) {
370 case "DisconnectRequested":
371 case "RetryRequested":
372 return false;
373 case "NetworkChanged":
374 if (next.network === "offline") {
375 return false;
376 }
377 break;
378 case "ConnectRequested":
379 break;
380 case "Wakeup":
381 if (next.reason === "application-active-reconnect") {
382 return true;
383 }
384 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
385 yield* logManagedRelayAccountChange;
386 return false;
387 }
388 break;
389 }
390 }
391 });
392
393 const monitorConnectedLease = Effect.fnUntraced(function* (
394 lease: ConnectionDriver.EnvironmentConnectionLease,
395 ) {
396 for (;;) {
397 const next = yield* Queue.take(signals);
398 switch (next._tag) {
399 case "DisconnectRequested":
400 case "RetryRequested":
401 return false;
402 case "NetworkChanged":
403 if (next.network === "offline") {
404 return false;
405 }
406 break;
407 case "Wakeup":
408 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
409 yield* logManagedRelayAccountChange;
410 return false;
411 }
412 if (next.reason === "application-active-reconnect") {
413 // Mobile operating systems commonly suspend sockets without
414 // delivering a close event. A long background resume deliberately
415 // replaces that lease and starts a fresh attempt without backoff.
416 return true;
417 }
418 if (next.reason === "application-active" || next.reason === "application-active-probe") {
419 const probe = yield* lease.session.probe.pipe(
420 Effect.timeoutOrElse({
421 duration:
422 next.reason === "application-active-probe"
423 ? MOBILE_CONNECTION_PROBE_TIMEOUT
424 : CONNECTION_PROBE_TIMEOUT,
425 orElse: () =>
426 Effect.fail(
427 new ConnectionTransientError({
428 reason: "timeout",
429 detail: `${target.label} did not respond to a connection health check.`,
430 }),
431 ),
432 }),
433 Effect.forkChild,
434 );
435 for (;;) {
436 const probeEvent = yield* Effect.raceFirst(
437 Fiber.await(probe).pipe(
438 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
439 ),
440 Queue.take(signals).pipe(
441 Effect.map((signal) => ({ _tag: "Signal" as const, signal })),
442 ),
443 );
444 if (probeEvent._tag === "ProbeCompleted") {
445 if (Exit.isFailure(probeEvent.exit)) {
446 yield* Ref.set(wakeProbeFailed, true);
447 }
448 yield* probeEvent.exit;
449 break;
450 }
451 switch (probeEvent.signal._tag) {
452 case "DisconnectRequested":
453 case "RetryRequested":
454 yield* Fiber.interrupt(probe);
455 return false;
456 case "NetworkChanged":
457 if (probeEvent.signal.network === "offline") {
458 yield* Fiber.interrupt(probe);
459 return false;
460 }
461 break;
462 case "Wakeup":
463 if (probeEvent.signal.reason === "application-active-reconnect") {
464 yield* Fiber.interrupt(probe);
465 return true;
466 }
467 if (
468 probeEvent.signal.reason === "credentials-changed" &&
469 target._tag === "RelayConnectionTarget"
470 ) {
471 yield* Fiber.interrupt(probe);
472 return false;
473 }
474 break;
475 case "ConnectRequested":
476 break;
477 }
478 }
479 }
480 break;
481 case "ConnectRequested":
482 break;
483 }
484 }
485 });
486
487 const waitForAuthorizationRefresh = Effect.fnUntraced(function* (
488 preparedConnection: PreparedConnection,
489 ) {
490 const authorization = preparedConnection.httpAuthorization;
491 if (authorization?._tag !== "Dpop") {
492 return yield* Effect.never;
493 }
494 const now = yield* Clock.currentTimeMillis;
495 yield* Effect.sleep(
496 Math.max(0, authorization.expiresAtEpochMs - now - DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS),
497 );
498 yield* Effect.logDebug("Refreshing the environment connection before its DPoP token expires.");
499 return true;
500 });
501
502 const runAttempt = Effect.fnUntraced(function* (
503 attempt: number,
504 generation: number,
505 lastFailure: ConnectionAttemptError | null,
506 pendingRetry: Option.Option<PendingRetryTrace>,
507 ) {
508 yield* SubscriptionRef.set(prepared, Option.none());
509 const establishment = yield* Effect.raceAllFirst([
510 exitUnlessInterrupted(
511 establishTracedConnection(attempt, generation, lastFailure, pendingRetry),
512 ).pipe(
513 Effect.map((exit): EstablishmentEvent => ({
514 _tag: "Completed",
515 exit,
516 })),
517 ),
518 waitForEstablishmentInterrupt().pipe(
519 Effect.map((resetRetry): EstablishmentEvent => ({
520 _tag: "Interrupted",
521 resetRetry,
522 })),
523 ),
524 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
525 Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
526 ),
527 ]);
528
529 if (establishment._tag === "Interrupted") {
530 return {
531 _tag: "Interrupted",
532 established: false,
533 stable: false,
534 resetRetry: establishment.resetRetry,
535 } satisfies AttemptOutcome;
536 }
537 if (establishment._tag === "TimedOut") {
538 return {
539 _tag: "Failure",
540 established: false,
541 stable: false,
542 failure: {
543 error: new ConnectionTransientError({
544 reason: "timeout",
545 detail: `${target.label} did not respond during connection setup.`,
546 }),
547 attemptSpan: Option.none(),
548 },
549 } satisfies AttemptOutcome;
550 }
551 if (Exit.isFailure(establishment.exit)) {
552 const isUnexpectedDefect =
553 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
554 !establishment.exit.cause.reasons.some(Cause.isFailReason);
555 const outcome = failureFromExit(target, establishment.exit, false, false);
556 if (isUnexpectedDefect) {
557 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
558 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
559 Effect.annotateLogs({
560 "environment.id": target.environmentId,
561 "environment.label": target.label,
562 "cause.reason_count": establishment.exit.cause.reasons.length,
563 ...safeErrorLogAttributes(defect),
564 }),
565 );
566 }
567 return outcome;
568 }
569
570 const active = establishment.exit.value;
571 const currentIntent = yield* Ref.get(intent);
572 if (!currentIntent.desired || currentIntent.network === "offline") {
573 return {
574 _tag: "Interrupted",
575 established: false,
576 stable: false,
577 resetRetry: false,
578 } satisfies AttemptOutcome;
579 }
580
581 const connectedAt = yield* Clock.currentTimeMillis;
582 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
583 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
584 yield* setState({
585 desired: true,
586 network: currentIntent.network,
587 phase: "connected",
588 stage: null,
589 attempt,
590 generation,
591 lastFailure: null,
592 retryAt: null,
593 });
594
595 const connectedExit = yield* Effect.raceAllFirst([
596 active.lease.session.closed.pipe(
597 Effect.mapError((error): TracedAttemptFailure => ({
598 error,
599 attemptSpan: active.attemptSpan,
600 })),
601 ),
602 monitorConnectedLease(active.lease).pipe(
603 Effect.mapError((error): TracedAttemptFailure => ({
604 error,
605 attemptSpan: active.attemptSpan,
606 })),
607 ),
608 waitForAuthorizationRefresh(active.lease.prepared),
609 ]).pipe(exitUnlessInterrupted);
610 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
611 if (Exit.isSuccess(connectedExit)) {
612 return {
613 _tag: "Interrupted",
614 established: true,
615 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
616 resetRetry: connectedExit.value,
617 } satisfies AttemptOutcome;
618 }
619 return failureFromExit(target, connectedExit, true, connectedForMs >= BACKOFF_RESET_AFTER_MS);
620 }, Effect.ensuring(clearLease));
621
622 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
623 return yield* Effect.raceFirst(
624 Effect.sleep(delayMs).pipe(Effect.as(false)),
625 Effect.gen(function* () {
626 for (;;) {
627 const next = yield* Queue.take(signals);
628 switch (next._tag) {
629 case "Wakeup":
630 return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
631 case "ConnectRequested":
632 case "DisconnectRequested":
633 case "RetryRequested":
634 case "NetworkChanged":
635 return false;
636 }
637 }
638 }),
639 );
640 });
641
642 const waitForSignal = Queue.take(signals).pipe(
643 Effect.map(
644 (next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
645 ),
646 );
647
648 const run = Effect.fnUntraced(function* () {
649 let failureCount = 0;
650 let generation = 0;
651 let latestFailure: ConnectionAttemptError | null = null;
652 let pendingRetry = Option.none<PendingRetryTrace>();
653 const resetRetryLadder = () => {
654 failureCount = 0;
655 pendingRetry = Option.none();
656 };
657
658 for (;;) {
659 if (yield* Ref.getAndSet(resetRetryState, false)) {
660 failureCount = 0;
661 latestFailure = null;
662 pendingRetry = Option.none();
663 }
664 const currentIntent = yield* Ref.get(intent);
665 if (!currentIntent.desired) {
666 resetRetryLadder();
667 latestFailure = null;
668 yield* clearLease;
669 yield* setState(availableState(currentIntent, generation));
670 yield* waitForSignal;
671 continue;
672 }
673 if (currentIntent.network === "offline") {
674 yield* clearLease;
675 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
676 const applicationActivated = yield* waitForSignal;
677 if (applicationActivated) {
678 resetRetryLadder();
679 }
680 continue;
681 }
682
683 const attempt = failureCount + 1;
684 const nextGeneration = generation + 1;
685 const outcome: AttemptOutcome = yield* Effect.scoped(
686 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry),
687 );
688 // Consumed on every iteration so a stale marker can never leak into a
689 // later, unrelated failure.
690 const failedWakeProbe = yield* Ref.getAndSet(wakeProbeFailed, false);
691 if (outcome.established) {
692 generation = nextGeneration;
693 if (outcome.stable) {
694 resetRetryLadder();
695 latestFailure = null;
696 }
697 }
698 if (outcome._tag === "Interrupted") {
699 if (outcome.resetRetry) {
700 resetRetryLadder();
701 }
702 continue;
703 }
704
705 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
706 const error: ConnectionAttemptError = outcome.failure.error;
707 latestFailure = error;
708 if (error._tag === "ConnectionBlockedError") {
709 const blockedIntent = yield* Ref.get(intent);
710 yield* setState({
711 desired: blockedIntent.desired,
712 network: blockedIntent.network,
713 phase: "blocked",
714 stage: null,
715 attempt,
716 generation,
717 lastFailure: error,
718 retryAt: null,
719 });
720 const applicationActivated = yield* waitForSignal;
721 if (applicationActivated) {
722 resetRetryLadder();
723 }
724 continue;
725 }
726
727 if (failedWakeProbe) {
728 // The wake probe found a dead transport while the user is returning to
729 // the app, so reconnect immediately instead of sleeping the first
730 // backoff rung. Only this first attempt skips the ladder; if it fails
731 // too, normal backoff resumes.
732 resetRetryLadder();
733 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, error));
734 continue;
735 }
736
737 failureCount += 1;
738 const delayMs = retryDelayMs(failureCount - 1);
739 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
740 previousAttempt,
741 failureCount,
742 delayMs,
743 reason: error.reason,
744 }));
745 const failedIntent = yield* Ref.get(intent);
746 yield* setState({
747 desired: failedIntent.desired,
748 network: failedIntent.network,
749 phase: "backoff",
750 stage: null,
751 attempt,
752 generation,
753 lastFailure: error,
754 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
755 });
756 const applicationActivated = yield* waitForRetrySignal(delayMs);
757 if (applicationActivated) {
758 resetRetryLadder();
759 }
760 }
761 });
762
763 yield* connectivity.changes.pipe(
764 Stream.runForEach((network) =>
765 Ref.modify(intent, (current) =>
766 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
767 ).pipe(
768 Effect.flatMap((changed) =>
769 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
770 ),
771 ),
772 ),
773 Effect.forkScoped,
774 );
775 yield* wakeups.changes.pipe(
776 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
777 Effect.forkScoped,
778 );
779 yield* run().pipe(Effect.forkScoped);
780
781 const connect = Ref.update(intent, (current) => ({
782 ...current,
783 desired: true,
784 })).pipe(
785 Effect.andThen(signal({ _tag: "ConnectRequested" })),
786 Effect.withSpan("EnvironmentSupervisor.connect"),
787 );
788
789 const disconnect = Ref.update(intent, (current) => ({
790 ...current,
791 desired: false,
792 })).pipe(
793 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
794 Effect.withSpan("EnvironmentSupervisor.disconnect"),
795 );
796
797 const retryNow = Ref.set(resetRetryState, true).pipe(
798 Effect.andThen(signal({ _tag: "RetryRequested" })),
799 Effect.withSpan("EnvironmentSupervisor.retryNow"),
800 );
801
802 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
803
804 return EnvironmentSupervisor.of({
805 target,
806 state,
807 session,
808 prepared,
809 connect,
810 disconnect,
811 retryNow,
812 });
813});
814
815export const layer = (
816 entry: ConnectionCatalogEntry,
817 options?: EnvironmentSupervisorOptions,
818): Layer.Layer<
819 EnvironmentSupervisor,
820 never,
821 | Connectivity.Connectivity
822 | ConnectionDriver.ConnectionDriver
823 | ConnectionWakeups.ConnectionWakeups
824> => Layer.effect(EnvironmentSupervisor, make(entry, options));