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
63interface ScopedConnection {
64 readonly attemptSpan: Option.Option<Tracer.Span>;
65 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
66 readonly scope: Scope.Closeable;
67}
68
69type AttemptOutcome =
70 | {
71 readonly _tag: "Interrupted";
72 readonly established: boolean;
73 readonly generation: number;
74 readonly stable: boolean;
75 readonly resetRetry: boolean;
76 }
77 | {
78 readonly _tag: "Failure";
79 readonly established: boolean;
80 readonly generation: number;
81 readonly stable: boolean;
82 readonly failure: TracedAttemptFailure;
83 };
84
85type EstablishmentEvent =
86 | {
87 readonly _tag: "Completed";
88 readonly exit: Exit.Exit<ScopedConnection, TracedAttemptFailure>;
89 }
90 | { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
91 | { readonly _tag: "TimedOut" };
92
93type ReplacementPreparationEvent =
94 | { readonly _tag: "Completed"; readonly exit: Exit.Exit<ScopedConnection, TracedAttemptFailure> }
95 | { readonly _tag: "TimedOut" }
96 | { readonly _tag: "AuthorizationExpired" };
97
98type ConnectedLeaseEvent =
99 | {
100 readonly _tag: "ActiveCompleted";
101 readonly exit: Exit.Exit<boolean, TracedAttemptFailure>;
102 }
103 | {
104 readonly _tag: "ReplacementCompleted";
105 readonly exit: Exit.Exit<Option.Option<ScopedConnection>, TracedAttemptFailure>;
106 };
107
108function exitUnlessInterrupted<A, E, R>(
109 effect: Effect.Effect<A, E, R>,
110): Effect.Effect<Exit.Exit<A, E>, never, R> {
111 return Effect.matchCauseEffect(effect, {
112 onFailure: (cause) =>
113 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),
114 onSuccess: (value) => Effect.succeed(Exit.succeed(value)),
115 });
116}
117
118export interface EnvironmentSupervisorOptions {
119 readonly initiallyDesired?: boolean;
120}
121
122function retryDelayMs(failureCount: number): number {
123 return RETRY_DELAYS_MS[Math.min(failureCount, RETRY_DELAYS_MS.length - 1)] ?? 16_000;
124}
125
126function annotateTarget(target: ConnectionTarget) {
127 return Effect.annotateCurrentSpan({
128 "environment.id": target.environmentId,
129 "environment.label": target.label,
130 "environment.target.kind": target._tag,
131 });
132}
133
134function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
135 return {
136 desired: false,
137 network: intent.network,
138 phase: "available",
139 stage: null,
140 attempt: 0,
141 generation,
142 lastFailure: null,
143 retryAt: null,
144 };
145}
146
147function offlineState(
148 intent: SupervisorIntent,
149 generation: number,
150 attempt: number,
151 lastFailure: ConnectionAttemptError | null,
152): SupervisorConnectionState {
153 return {
154 desired: true,
155 network: intent.network,
156 phase: "offline",
157 stage: null,
158 attempt,
159 generation,
160 lastFailure,
161 retryAt: null,
162 };
163}
164
165function connectingState(
166 intent: SupervisorIntent,
167 generation: number,
168 attempt: number,
169 lastFailure: ConnectionAttemptError | null,
170 stage: SupervisorConnectionState["stage"] = "preparing",
171): SupervisorConnectionState {
172 return {
173 desired: true,
174 network: intent.network,
175 phase: "connecting",
176 stage,
177 attempt,
178 generation,
179 lastFailure,
180 retryAt: null,
181 };
182}
183
184function failureFromExit<A>(
185 target: ConnectionTarget,
186 exit: Exit.Exit<A, TracedAttemptFailure>,
187 established: boolean,
188 generation: number,
189 stable: boolean,
190): AttemptOutcome {
191 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
192 return { _tag: "Interrupted", established, generation, stable, resetRetry: false };
193 }
194 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
195 if (typedFailure) {
196 return {
197 _tag: "Failure",
198 established,
199 generation,
200 stable,
201 failure: typedFailure.error,
202 };
203 }
204 return {
205 _tag: "Failure",
206 established,
207 generation,
208 stable,
209 failure: {
210 error: new ConnectionTransientError({
211 reason: "transport",
212 detail: `${target.label} connection failed unexpectedly.`,
213 }),
214 attemptSpan: Option.none(),
215 },
216 };
217}
218
219export class EnvironmentSupervisor extends Context.Service<
220 EnvironmentSupervisor,
221 {
222 readonly target: ConnectionTarget;
223 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
224 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
225 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
226 readonly connect: Effect.Effect<void>;
227 readonly disconnect: Effect.Effect<void>;
228 readonly retryNow: Effect.Effect<void>;
229 }
230>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
231
232export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
233 entry: ConnectionCatalogEntry,
234 options?: EnvironmentSupervisorOptions,
235): Effect.fn.Return<
236 EnvironmentSupervisor["Service"],
237 never,
238 | Connectivity.Connectivity
239 | ConnectionDriver.ConnectionDriver
240 | Scope.Scope
241 | ConnectionWakeups.ConnectionWakeups
242> {
243 const target = entry.target;
244 yield* annotateTarget(target);
245
246 const connectivity = yield* Connectivity.Connectivity;
247 const driver = yield* ConnectionDriver.ConnectionDriver;
248 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
249 const initialIntent: SupervisorIntent = {
250 desired: options?.initiallyDesired ?? false,
251 network: yield* connectivity.status,
252 };
253 const intent = yield* Ref.make(initialIntent);
254 const signals = yield* Queue.unbounded<SupervisorSignal>();
255 const resetRetryState = yield* Ref.make(false);
256 // Set when a foreground wake probe fails or times out: the user is actively
257 // returning to the app on a dead transport, so the follow-up reconnect skips
258 // the first backoff rung instead of sleeping.
259 const wakeProbeFailed = yield* Ref.make(false);
260 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
261 !initialIntent.desired
262 ? availableState(initialIntent, 0)
263 : initialIntent.network === "offline"
264 ? offlineState(initialIntent, 0, 0, null)
265 : connectingState(initialIntent, 0, 1, null),
266 );
267 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
268 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
269
270 const clearLease = Effect.all(
271 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
272 { discard: true },
273 );
274
275 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
276 next: SupervisorConnectionState,
277 ) {
278 yield* SubscriptionRef.set(state, next);
279 });
280
281 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
282 yield* Queue.offer(signals, next);
283 });
284
285 const logManagedRelayAccountChange = Effect.logInfo(
286 "Managed relay account changed; restarting the environment connection.",
287 ).pipe(
288 Effect.annotateLogs({
289 "environment.id": target.environmentId,
290 "environment.label": target.label,
291 }),
292 );
293
294 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
295 attempt: number,
296 generation: number,
297 lastFailure: ConnectionAttemptError | null,
298 progress: ConnectionDriver.ConnectionDriverProgress,
299 ) {
300 if ("prepared" in progress) {
301 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
302 }
303 yield* setState(
304 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
305 );
306 });
307
308 const establishConnection = Effect.fnUntraced(function* (
309 attempt: number,
310 generation: number,
311 lastFailure: ConnectionAttemptError | null,
312 publishProgress: boolean,
313 ) {
314 return yield* driver.connect(entry, (progress) =>
315 publishProgress ? reportProgress(attempt, generation, lastFailure, progress) : Effect.void,
316 );
317 });
318
319 const traceRelayEstablishment = (
320 effect: Effect.Effect<
321 ConnectionDriver.EnvironmentConnectionLease,
322 ConnectionAttemptError,
323 Scope.Scope
324 >,
325 attempt: number,
326 generation: number,
327 pendingRetry: Option.Option<PendingRetryTrace>,
328 ) => {
329 const traced = Effect.gen(function* () {
330 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
331 yield* annotateTarget(target);
332 yield* Effect.annotateCurrentSpan({
333 "connection.attempt": attempt,
334 "connection.generation": generation,
335 "connection.retry.failure_count": Option.match(pendingRetry, {
336 onNone: () => 0,
337 onSome: (retry) => retry.failureCount,
338 }),
339 });
340 const lease = yield* effect.pipe(
341 Effect.mapError((error): TracedAttemptFailure => ({
342 error,
343 attemptSpan: Option.some(attemptSpan),
344 })),
345 );
346 return { attemptSpan: Option.some(attemptSpan), lease };
347 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
348
349 return Option.match(pendingRetry, {
350 onNone: () => traced,
351 onSome: (retry) =>
352 traced.pipe(
353 Effect.linkSpans(retry.previousAttempt, {
354 "connection.retry.delay_ms": retry.delayMs,
355 "connection.retry.reason": retry.reason,
356 }),
357 ),
358 }).pipe(withRelayClientTracing);
359 };
360
361 const establishTracedConnection = Effect.fnUntraced(function* (
362 attempt: number,
363 generation: number,
364 lastFailure: ConnectionAttemptError | null,
365 pendingRetry: Option.Option<PendingRetryTrace>,
366 publishProgress: boolean,
367 ) {
368 if (target._tag === "RelayConnectionTarget") {
369 return yield* traceRelayEstablishment(
370 establishConnection(attempt, generation, lastFailure, publishProgress),
371 attempt,
372 generation,
373 pendingRetry,
374 );
375 }
376 return yield* establishConnection(attempt, generation, lastFailure, publishProgress).pipe(
377 Effect.map((lease) => ({
378 attemptSpan: Option.none<Tracer.Span>(),
379 lease,
380 })),
381 Effect.mapError((error): TracedAttemptFailure => ({
382 error,
383 attemptSpan: Option.none(),
384 })),
385 );
386 });
387
388 const forkScopedTracedConnection = Effect.fnUntraced(function* (
389 attempt: number,
390 generation: number,
391 lastFailure: ConnectionAttemptError | null,
392 pendingRetry: Option.Option<PendingRetryTrace>,
393 publishProgress: boolean,
394 ) {
395 const parentScope = yield* Scope.Scope;
396 return yield* Effect.uninterruptibleMask((restore) =>
397 Effect.gen(function* () {
398 const connectionScope = yield* Scope.fork(parentScope, "sequential");
399 const fiber = yield* restore(
400 establishTracedConnection(
401 attempt,
402 generation,
403 lastFailure,
404 pendingRetry,
405 publishProgress,
406 ).pipe(
407 Scope.provide(connectionScope),
408 Effect.map(
409 (established) =>
410 ({ ...established, scope: connectionScope }) satisfies ScopedConnection,
411 ),
412 ),
413 ).pipe(Effect.forkChild);
414 return { fiber, scope: connectionScope };
415 }),
416 );
417 });
418
419 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
420 for (;;) {
421 const next = yield* Queue.take(signals);
422 switch (next._tag) {
423 case "DisconnectRequested":
424 case "RetryRequested":
425 return false;
426 case "NetworkChanged":
427 if (next.network === "offline") {
428 return false;
429 }
430 break;
431 case "ConnectRequested":
432 break;
433 case "Wakeup":
434 if (next.reason === "application-active-reconnect") {
435 return true;
436 }
437 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
438 yield* logManagedRelayAccountChange;
439 return false;
440 }
441 break;
442 }
443 }
444 });
445
446 const monitorConnectedLease = Effect.fnUntraced(function* (
447 lease: ConnectionDriver.EnvironmentConnectionLease,
448 ) {
449 for (;;) {
450 const next = yield* Queue.take(signals);
451 switch (next._tag) {
452 case "DisconnectRequested":
453 case "RetryRequested":
454 return false;
455 case "NetworkChanged":
456 if (next.network === "offline") {
457 return false;
458 }
459 break;
460 case "Wakeup":
461 if (next.reason === "credentials-changed" && target._tag === "RelayConnectionTarget") {
462 yield* logManagedRelayAccountChange;
463 return false;
464 }
465 if (next.reason === "application-active-reconnect") {
466 // Mobile operating systems commonly suspend sockets without
467 // delivering a close event. A long background resume deliberately
468 // replaces that lease and starts a fresh attempt without backoff.
469 return true;
470 }
471 if (next.reason === "application-active" || next.reason === "application-active-probe") {
472 const probe = yield* lease.session.probe.pipe(
473 Effect.timeoutOrElse({
474 duration:
475 next.reason === "application-active-probe"
476 ? MOBILE_CONNECTION_PROBE_TIMEOUT
477 : CONNECTION_PROBE_TIMEOUT,
478 orElse: () =>
479 Effect.fail(
480 new ConnectionTransientError({
481 reason: "timeout",
482 detail: `${target.label} did not respond to a connection health check.`,
483 }),
484 ),
485 }),
486 Effect.forkChild,
487 );
488 for (;;) {
489 const probeEvent = yield* Effect.raceFirst(
490 Fiber.await(probe).pipe(
491 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
492 ),
493 Queue.take(signals).pipe(
494 Effect.map((signal) => ({ _tag: "Signal" as const, signal })),
495 ),
496 );
497 if (probeEvent._tag === "ProbeCompleted") {
498 if (Exit.isFailure(probeEvent.exit)) {
499 yield* Ref.set(wakeProbeFailed, true);
500 }
501 yield* probeEvent.exit;
502 break;
503 }
504 switch (probeEvent.signal._tag) {
505 case "DisconnectRequested":
506 case "RetryRequested":
507 yield* Fiber.interrupt(probe);
508 return false;
509 case "NetworkChanged":
510 if (probeEvent.signal.network === "offline") {
511 yield* Fiber.interrupt(probe);
512 return false;
513 }
514 break;
515 case "Wakeup":
516 if (probeEvent.signal.reason === "application-active-reconnect") {
517 yield* Fiber.interrupt(probe);
518 return true;
519 }
520 if (
521 probeEvent.signal.reason === "credentials-changed" &&
522 target._tag === "RelayConnectionTarget"
523 ) {
524 yield* Fiber.interrupt(probe);
525 return false;
526 }
527 break;
528 case "ConnectRequested":
529 break;
530 }
531 }
532 }
533 break;
534 case "ConnectRequested":
535 break;
536 }
537 }
538 });
539
540 const waitForAuthorizationDeadline = Effect.fnUntraced(function* (
541 preparedConnection: PreparedConnection,
542 skewMs: number,
543 ) {
544 const authorization = preparedConnection.httpAuthorization;
545 if (authorization?._tag !== "Dpop") {
546 return yield* Effect.never;
547 }
548 const now = yield* Clock.currentTimeMillis;
549 yield* Effect.sleep(Math.max(0, authorization.expiresAtEpochMs - now - skewMs));
550 });
551
552 const waitForActiveCompletion = Effect.fnUntraced(function* (active: ScopedConnection) {
553 const exit = yield* exitUnlessInterrupted(
554 Effect.raceAllFirst([
555 active.lease.session.closed.pipe(
556 Effect.mapError((error): TracedAttemptFailure => ({
557 error,
558 attemptSpan: active.attemptSpan,
559 })),
560 ),
561 monitorConnectedLease(active.lease).pipe(
562 Effect.mapError((error): TracedAttemptFailure => ({
563 error,
564 attemptSpan: active.attemptSpan,
565 })),
566 ),
567 ]),
568 );
569 return { _tag: "ActiveCompleted", exit } satisfies ConnectedLeaseEvent;
570 });
571
572 const prepareReplacement = Effect.fnUntraced(function* (
573 active: ScopedConnection,
574 generation: number,
575 ) {
576 yield* waitForAuthorizationDeadline(active.lease.prepared, DPOP_ACCESS_TOKEN_REFRESH_SKEW_MS);
577 yield* Effect.logDebug(
578 "Preparing a replacement environment connection before its DPoP token expires.",
579 );
580
581 let failureCount = 0;
582 for (;;) {
583 const candidate = yield* forkScopedTracedConnection(
584 failureCount + 1,
585 generation,
586 null,
587 Option.none(),
588 false,
589 );
590 const replacement = yield* Effect.raceAllFirst([
591 Fiber.await(candidate.fiber).pipe(
592 Effect.map((exit): ReplacementPreparationEvent => ({ _tag: "Completed", exit })),
593 ),
594 waitForAuthorizationDeadline(active.lease.prepared, 0).pipe(
595 Effect.as<ReplacementPreparationEvent>({ _tag: "AuthorizationExpired" }),
596 ),
597 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
598 Effect.as<ReplacementPreparationEvent>({ _tag: "TimedOut" }),
599 ),
600 ]);
601
602 if (replacement._tag !== "Completed") {
603 yield* Fiber.interrupt(candidate.fiber);
604 yield* Fiber.await(candidate.fiber);
605 yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
606 } else if (Exit.isFailure(replacement.exit)) {
607 yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
608 }
609 if (replacement._tag === "AuthorizationExpired") {
610 return Option.none<ScopedConnection>();
611 }
612 if (replacement._tag === "Completed" && Exit.isSuccess(replacement.exit)) {
613 return Option.some(replacement.exit.value);
614 }
615
616 let replacementError: ConnectionTransientError;
617 if (replacement._tag === "Completed") {
618 if (Exit.isSuccess(replacement.exit)) {
619 return yield* Effect.die("A successful replacement was not installed.");
620 }
621 const failure = Cause.findErrorOption(replacement.exit.cause);
622 if (Option.isNone(failure) || failure.value.error._tag === "ConnectionBlockedError") {
623 return yield* Effect.failCause(replacement.exit.cause);
624 }
625 replacementError = failure.value.error;
626 } else {
627 replacementError = new ConnectionTransientError({
628 reason: "timeout",
629 detail: `${target.label} did not respond during connection setup.`,
630 });
631 }
632
633 const retryDelay = retryDelayMs(failureCount);
634 failureCount += 1;
635 yield* Effect.logWarning(
636 "Could not prepare a replacement environment connection; keeping the active connection.",
637 ).pipe(
638 Effect.annotateLogs({
639 "authorization.refresh.retry_delay_ms": retryDelay,
640 ...safeErrorLogAttributes(replacementError),
641 }),
642 );
643 const retryBeforeExpiry = yield* Effect.raceFirst(
644 Effect.sleep(retryDelay).pipe(Effect.as(true)),
645 waitForAuthorizationDeadline(active.lease.prepared, 0).pipe(Effect.as(false)),
646 );
647 if (!retryBeforeExpiry) {
648 return Option.none<ScopedConnection>();
649 }
650 }
651 });
652
653 const runAttempt = Effect.fnUntraced(function* (
654 attempt: number,
655 previousGeneration: number,
656 lastFailure: ConnectionAttemptError | null,
657 pendingRetry: Option.Option<PendingRetryTrace>,
658 ) {
659 const initialGeneration = previousGeneration + 1;
660 yield* SubscriptionRef.set(prepared, Option.none());
661 const initial = yield* forkScopedTracedConnection(
662 attempt,
663 initialGeneration,
664 lastFailure,
665 pendingRetry,
666 true,
667 );
668 const establishment = yield* Effect.raceAllFirst([
669 Fiber.await(initial.fiber).pipe(
670 Effect.map((exit): EstablishmentEvent => ({
671 _tag: "Completed",
672 exit,
673 })),
674 ),
675 waitForEstablishmentInterrupt().pipe(
676 Effect.map((resetRetry): EstablishmentEvent => ({
677 _tag: "Interrupted",
678 resetRetry,
679 })),
680 ),
681 Effect.sleep(CONNECTION_ESTABLISHMENT_TIMEOUT).pipe(
682 Effect.as<EstablishmentEvent>({ _tag: "TimedOut" }),
683 ),
684 ]);
685
686 if (establishment._tag !== "Completed") {
687 yield* Fiber.interrupt(initial.fiber);
688 yield* Fiber.await(initial.fiber);
689 yield* Scope.close(initial.scope, Exit.void).pipe(Effect.ignore);
690 } else if (Exit.isFailure(establishment.exit)) {
691 yield* Scope.close(initial.scope, Exit.void).pipe(Effect.ignore);
692 }
693 if (establishment._tag === "Interrupted") {
694 return {
695 _tag: "Interrupted",
696 established: false,
697 generation: previousGeneration,
698 stable: false,
699 resetRetry: establishment.resetRetry,
700 } satisfies AttemptOutcome;
701 }
702 if (establishment._tag === "TimedOut") {
703 return {
704 _tag: "Failure",
705 established: false,
706 generation: previousGeneration,
707 stable: false,
708 failure: {
709 error: new ConnectionTransientError({
710 reason: "timeout",
711 detail: `${target.label} did not respond during connection setup.`,
712 }),
713 attemptSpan: Option.none(),
714 },
715 } satisfies AttemptOutcome;
716 }
717 if (Exit.isFailure(establishment.exit)) {
718 const isUnexpectedDefect =
719 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
720 !establishment.exit.cause.reasons.some(Cause.isFailReason);
721 const outcome = failureFromExit(target, establishment.exit, false, previousGeneration, false);
722 if (isUnexpectedDefect) {
723 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
724 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
725 Effect.annotateLogs({
726 "environment.id": target.environmentId,
727 "environment.label": target.label,
728 "cause.reason_count": establishment.exit.cause.reasons.length,
729 ...safeErrorLogAttributes(defect),
730 }),
731 );
732 }
733 return outcome;
734 }
735
736 const currentIntent = yield* Ref.get(intent);
737 if (!currentIntent.desired || currentIntent.network === "offline") {
738 return {
739 _tag: "Interrupted",
740 established: false,
741 generation: previousGeneration,
742 stable: false,
743 resetRetry: false,
744 } satisfies AttemptOutcome;
745 }
746
747 const connectedAt = yield* Clock.currentTimeMillis;
748 let active = establishment.exit.value;
749 let activeGeneration = initialGeneration;
750 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
751 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
752 yield* setState({
753 desired: true,
754 network: currentIntent.network,
755 phase: "connected",
756 stage: null,
757 attempt,
758 generation: activeGeneration,
759 lastFailure: null,
760 retryAt: null,
761 });
762
763 for (;;) {
764 const connectedEvent = yield* Effect.raceAllFirst([
765 waitForActiveCompletion(active),
766 exitUnlessInterrupted(prepareReplacement(active, activeGeneration + 1)).pipe(
767 Effect.map((exit): ConnectedLeaseEvent => ({ _tag: "ReplacementCompleted", exit })),
768 ),
769 ]);
770 const stable = (yield* Clock.currentTimeMillis) - connectedAt >= BACKOFF_RESET_AFTER_MS;
771 if (connectedEvent._tag === "ActiveCompleted") {
772 if (Exit.isSuccess(connectedEvent.exit)) {
773 return {
774 _tag: "Interrupted",
775 established: true,
776 generation: activeGeneration,
777 stable,
778 resetRetry: connectedEvent.exit.value,
779 } satisfies AttemptOutcome;
780 }
781 return failureFromExit(target, connectedEvent.exit, true, activeGeneration, stable);
782 }
783 if (Exit.isFailure(connectedEvent.exit)) {
784 return failureFromExit(target, connectedEvent.exit, true, activeGeneration, stable);
785 }
786 if (Option.isNone(connectedEvent.exit.value)) {
787 return {
788 _tag: "Interrupted",
789 established: true,
790 generation: activeGeneration,
791 stable,
792 resetRetry: true,
793 } satisfies AttemptOutcome;
794 }
795
796 const candidate = connectedEvent.exit.value.value;
797 const replacementIntent = yield* Ref.get(intent);
798 if (!replacementIntent.desired || replacementIntent.network === "offline") {
799 yield* Scope.close(candidate.scope, Exit.void).pipe(Effect.ignore);
800 return {
801 _tag: "Interrupted",
802 established: true,
803 generation: activeGeneration,
804 stable,
805 resetRetry: false,
806 } satisfies AttemptOutcome;
807 }
808
809 const previous = active;
810 yield* Effect.uninterruptible(
811 Effect.gen(function* () {
812 active = candidate;
813 activeGeneration += 1;
814 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
815 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
816 yield* setState({
817 desired: true,
818 network: replacementIntent.network,
819 phase: "connected",
820 stage: null,
821 attempt: 1,
822 generation: activeGeneration,
823 lastFailure: null,
824 retryAt: null,
825 });
826 yield* Scope.close(previous.scope, Exit.void).pipe(Effect.ignore);
827 }),
828 );
829 }
830 }, Effect.ensuring(clearLease));
831
832 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
833 return yield* Effect.raceFirst(
834 Effect.sleep(delayMs).pipe(Effect.as(false)),
835 Effect.gen(function* () {
836 for (;;) {
837 const next = yield* Queue.take(signals);
838 switch (next._tag) {
839 case "Wakeup":
840 return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
841 case "ConnectRequested":
842 case "DisconnectRequested":
843 case "RetryRequested":
844 case "NetworkChanged":
845 return false;
846 }
847 }
848 }),
849 );
850 });
851
852 const waitForSignal = Queue.take(signals).pipe(
853 Effect.map(
854 (next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
855 ),
856 );
857
858 const run = Effect.fnUntraced(function* () {
859 let failureCount = 0;
860 let generation = 0;
861 let latestFailure: ConnectionAttemptError | null = null;
862 let pendingRetry = Option.none<PendingRetryTrace>();
863 const resetRetryLadder = () => {
864 failureCount = 0;
865 pendingRetry = Option.none();
866 };
867
868 for (;;) {
869 if (yield* Ref.getAndSet(resetRetryState, false)) {
870 failureCount = 0;
871 latestFailure = null;
872 pendingRetry = Option.none();
873 }
874 const currentIntent = yield* Ref.get(intent);
875 if (!currentIntent.desired) {
876 resetRetryLadder();
877 latestFailure = null;
878 yield* clearLease;
879 yield* setState(availableState(currentIntent, generation));
880 yield* waitForSignal;
881 continue;
882 }
883 if (currentIntent.network === "offline") {
884 yield* clearLease;
885 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
886 const applicationActivated = yield* waitForSignal;
887 if (applicationActivated) {
888 resetRetryLadder();
889 }
890 continue;
891 }
892
893 const attempt = failureCount + 1;
894 const outcome: AttemptOutcome = yield* Effect.scoped(
895 runAttempt(attempt, generation, latestFailure, pendingRetry),
896 );
897 // Consumed on every iteration so a stale marker can never leak into a
898 // later, unrelated failure.
899 const failedWakeProbe = yield* Ref.getAndSet(wakeProbeFailed, false);
900 generation = outcome.generation;
901 if (outcome.established) {
902 if (outcome.stable) {
903 resetRetryLadder();
904 latestFailure = null;
905 }
906 }
907 if (outcome._tag === "Interrupted") {
908 if (outcome.resetRetry) {
909 resetRetryLadder();
910 }
911 continue;
912 }
913
914 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
915 const error: ConnectionAttemptError = outcome.failure.error;
916 latestFailure = error;
917 if (error._tag === "ConnectionBlockedError") {
918 const blockedIntent = yield* Ref.get(intent);
919 yield* setState({
920 desired: blockedIntent.desired,
921 network: blockedIntent.network,
922 phase: "blocked",
923 stage: null,
924 attempt,
925 generation,
926 lastFailure: error,
927 retryAt: null,
928 });
929 const applicationActivated = yield* waitForSignal;
930 if (applicationActivated) {
931 resetRetryLadder();
932 }
933 continue;
934 }
935
936 if (failedWakeProbe) {
937 // The wake probe found a dead transport while the user is returning to
938 // the app, so reconnect immediately instead of sleeping the first
939 // backoff rung. Only this first attempt skips the ladder; if it fails
940 // too, normal backoff resumes.
941 resetRetryLadder();
942 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, error));
943 continue;
944 }
945
946 failureCount += 1;
947 const delayMs = retryDelayMs(failureCount - 1);
948 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
949 previousAttempt,
950 failureCount,
951 delayMs,
952 reason: error.reason,
953 }));
954 const failedIntent = yield* Ref.get(intent);
955 yield* setState({
956 desired: failedIntent.desired,
957 network: failedIntent.network,
958 phase: "backoff",
959 stage: null,
960 attempt,
961 generation,
962 lastFailure: error,
963 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
964 });
965 const applicationActivated = yield* waitForRetrySignal(delayMs);
966 if (applicationActivated) {
967 resetRetryLadder();
968 }
969 }
970 });
971
972 yield* connectivity.changes.pipe(
973 Stream.runForEach((network) =>
974 Ref.modify(intent, (current) =>
975 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
976 ).pipe(
977 Effect.flatMap((changed) =>
978 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
979 ),
980 ),
981 ),
982 Effect.forkScoped,
983 );
984 yield* wakeups.changes.pipe(
985 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
986 Effect.forkScoped,
987 );
988 yield* run().pipe(Effect.forkScoped);
989
990 const connect = Ref.update(intent, (current) => ({
991 ...current,
992 desired: true,
993 })).pipe(
994 Effect.andThen(signal({ _tag: "ConnectRequested" })),
995 Effect.withSpan("EnvironmentSupervisor.connect"),
996 );
997
998 const disconnect = Ref.update(intent, (current) => ({
999 ...current,
1000 desired: false,
1001 })).pipe(
1002 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
1003 Effect.withSpan("EnvironmentSupervisor.disconnect"),
1004 );
1005
1006 const retryNow = Ref.set(resetRetryState, true).pipe(
1007 Effect.andThen(signal({ _tag: "RetryRequested" })),
1008 Effect.withSpan("EnvironmentSupervisor.retryNow"),
1009 );
1010
1011 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1012
1013 return EnvironmentSupervisor.of({
1014 target,
1015 state,
1016 session,
1017 prepared,
1018 connect,
1019 disconnect,
1020 retryNow,
1021 });
1022});
1023
1024export const layer = (
1025 entry: ConnectionCatalogEntry,
1026 options?: EnvironmentSupervisorOptions,
1027): Layer.Layer<
1028 EnvironmentSupervisor,
1029 never,
1030 | Connectivity.Connectivity
1031 | ConnectionDriver.ConnectionDriver
1032 | ConnectionWakeups.ConnectionWakeups
1033> => Layer.effect(EnvironmentSupervisor, make(entry, options));