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

supervisor.ts

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