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

supervisor.ts

1,010 lines33.9 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 Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Fiber from "effect/Fiber";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Random from "effect/Random";
12import * as Ref from "effect/Ref";
13import * as Scope from "effect/Scope";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import * as Tracer from "effect/Tracer";
17​
18import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
19import * as Connectivity from "./connectivity.ts";
20import * as ConnectionDriver from "./driver.ts";
21import {
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 { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
32import * as ConnectionWakeups from "./wakeups.ts";
33import {
34 connectionRouteId,
35 connectionRoutes,
36 entryWithRoutes,
37 type ReportedEndpoint,
38} from "./routes.ts";
39​
40const RETRY_BASE_DELAY_MS = 1_000;
41const RETRY_MAX_DELAY_MS = 300_000;
42// A cold server with a large database can take longer than 15 seconds to
43// answer, and that is not a reason to drop a working connection.
44const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
45const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_TIMEOUT);
46const synchronizationTimeout = Duration.fromInputUnsafe("75 seconds");
47const CONNECTION_PROBE_TIMEOUT = "15 seconds";
48const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
49const BACKOFF_RESET_AFTER_MS = 30_000;
50const BETTER_ROUTE_CHECK_INTERVAL = "60 seconds";
51// A better route that answered the check but then failed to connect is not
52// tried again for this long, so a flaky LAN cannot bounce the connection.
53const BETTER_ROUTE_COOLDOWN_MS = 300_000;
54​
55interface SupervisorIntent {
56 readonly desired: boolean;
57 readonly network: NetworkStatus;
59​
60type SupervisorSignal =
61 | { readonly _tag: "ConnectRequested" }
62 | { readonly _tag: "DisconnectRequested" }
63 | { readonly _tag: "RetryRequested" }
64 | { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
65 | { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup }
66 | { readonly _tag: "BetterRouteAvailable"; readonly routeId: string };
67​
68interface PendingRetryTrace {
69 readonly previousAttempt: Tracer.Span;
70 readonly failureCount: number;
71 readonly delayMs: number;
72 readonly reason: ConnectionAttemptError["reason"];
74​
75interface TracedAttemptFailure {
76 readonly error: ConnectionAttemptError;
77 readonly attemptSpan: Option.Option<Tracer.Span>;
79​
80type AttemptOutcome =
81 | {
82 readonly _tag: "Interrupted";
83 readonly established: boolean;
84 readonly stable: boolean;
85 readonly resetRetry: boolean;
86 }
87 | {
88 readonly _tag: "Failure";
89 readonly established: boolean;
90 readonly stable: boolean;
91 readonly failure: TracedAttemptFailure;
92 };
93​
94type EstablishmentEvent =
95 | {
96 readonly _tag: "Completed";
97 readonly exit: Exit.Exit<
98 {
99 readonly attemptSpan: Option.Option<Tracer.Span>;
100 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
101 },
102 TracedAttemptFailure
103 >;
104 }
105 | { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
106 | { readonly _tag: "TimedOut" };
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 });
117​
118export interface EnvironmentSupervisorOptions {
119 readonly initiallyDesired?: boolean;
120 readonly learnRoutes?: (input: {
121 readonly activeRoute: ConnectionRoute;
122 readonly reported: ReadonlyArray<ReportedEndpoint>;
123 }) => Effect.Effect<Option.Option<ConnectionCatalogEntry>>;
125​
126export function retryDelayMs(failureCount: number, random: number): number {
127 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failureCount + 1));
128 return Math.round(ceiling / 2 + (ceiling / 2) * random);
130​
131function annotateTarget(target: ConnectionTarget) {
132 return Effect.annotateCurrentSpan({
133 "environment.id": target.environmentId,
134 "environment.label": target.label,
135 "environment.target.kind": target._tag,
136 });
138​
139function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
140 return {
141 desired: false,
142 network: intent.network,
143 phase: "available",
144 stage: null,
145 attempt: 0,
146 generation,
147 lastFailure: null,
148 retryAt: null,
149 };
151​
152function offlineState(
153 intent: SupervisorIntent,
154 generation: number,
155 attempt: number,
156 lastFailure: ConnectionAttemptError | null,
157): SupervisorConnectionState {
158 return {
159 desired: true,
160 network: intent.network,
161 phase: "offline",
162 stage: null,
163 attempt,
164 generation,
165 lastFailure,
166 retryAt: null,
167 };
169​
170function connectingState(
171 intent: SupervisorIntent,
172 generation: number,
173 attempt: number,
174 lastFailure: ConnectionAttemptError | null,
175 stage: SupervisorConnectionState["stage"] = "preparing",
176): SupervisorConnectionState {
177 return {
178 desired: true,
179 network: intent.network,
180 phase: "connecting",
181 stage,
182 attempt,
183 generation,
184 lastFailure,
185 retryAt: null,
186 };
188​
189function failureFromExit<A>(
190 target: ConnectionTarget,
191 exit: Exit.Exit<A, TracedAttemptFailure>,
192 established: boolean,
193 stable: boolean,
194): AttemptOutcome {
195 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
196 return { _tag: "Interrupted", established, stable, resetRetry: false };
197 }
198 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
199 if (typedFailure) {
200 return {
201 _tag: "Failure",
202 established,
203 stable,
204 failure: typedFailure.error,
205 };
206 }
207 return {
208 _tag: "Failure",
209 established,
210 stable,
211 failure: {
212 error: new ConnectionTransientError({
213 reason: "transport",
214 detail: `${target.label} connection failed unexpectedly.`,
215 }),
216 attemptSpan: Option.none(),
217 },
218 };
220​
221export class EnvironmentSupervisor extends Context.Service<
222 EnvironmentSupervisor,
223 {
224 readonly target: ConnectionTarget;
225 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
226 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
227 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
228 readonly connect: Effect.Effect<void>;
229 readonly disconnect: Effect.Effect<void>;
230 readonly retryNow: Effect.Effect<void>;
231 }
232>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
233​
234export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
235 entry: ConnectionCatalogEntry,
236 options?: EnvironmentSupervisorOptions,
237): Effect.fn.Return<
238 EnvironmentSupervisor["Service"],
239 never,
240 | Connectivity.Connectivity
241 | ConnectionDriver.ConnectionDriver
242 | Scope.Scope
243 | ConnectionWakeups.ConnectionWakeups
244> {
245 const target = entry.target;
246 const usesRelay = connectionRoutes(entry).some(
247 (route) => route.target._tag === "RelayConnectionTarget",
248 );
249 const setupTimeoutDetail = `${target.label} did not respond during connection setup.${
250 usesRelay ? ` ${NETWORK_BLOCKING_HINT}` : ""
251 }`;
252 yield* annotateTarget(target);
253​
254 const connectivity = yield* Connectivity.Connectivity;
255 const driver = yield* ConnectionDriver.ConnectionDriver;
256 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
257 const initialIntent: SupervisorIntent = {
258 desired: options?.initiallyDesired ?? false,
259 network: yield* connectivity.status,
260 };
261 const intent = yield* Ref.make(initialIntent);
262 const signals = yield* Queue.unbounded<SupervisorSignal>();
263 const resetRetryState = yield* Ref.make(false);
264 const probeUnanswered = yield* Ref.make(false);
265 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
266 !initialIntent.desired
267 ? availableState(initialIntent, 0)
268 : initialIntent.network === "offline"
269 ? offlineState(initialIntent, 0, 0, null)
270 : connectingState(initialIntent, 0, 1, null),
271 );
272 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
273 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
274 // Learned routes arrive while a session is live, so the route list is read
275 // fresh by each attempt and check instead of being fixed at creation.
276 const currentEntry = yield* Ref.make(entry);
277 const currentRoutes = Ref.get(currentEntry).pipe(Effect.map(connectionRoutes));
278 const preferredRouteId = yield* Ref.make(Option.none<string>());
279 const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());
280​
281 const attemptEntry = Effect.gen(function* () {
282 const latest = yield* Ref.get(currentEntry);
283 const routes = connectionRoutes(latest);
284 const preferred = yield* Ref.getAndSet(preferredRouteId, Option.none());
285 if (Option.isNone(preferred)) return latest;
286 const route = routes.find(
287 (candidate) => connectionRouteId(candidate.target) === preferred.value,
288 );
289 return route === undefined
290 ? latest
291 : entryWithRoutes(latest, [route, ...routes.filter((candidate) => candidate !== route)]);
292 });
293​
294 const learnRoutesFrom = Effect.fnUntraced(function* (
295 learn: NonNullable<EnvironmentSupervisorOptions["learnRoutes"]>,
296 lease: ConnectionDriver.EnvironmentConnectionLease,
297 ) {
298 const config = yield* lease.session.initialConfig.pipe(Effect.option);
299 const reported = Option.getOrUndefined(config)?.directEndpoints;
300 if (reported === undefined) return;
301 const activeId = connectionRouteId(lease.prepared.target);
302 const activeRoute = (yield* currentRoutes).find(
303 (route) => connectionRouteId(route.target) === activeId,
304 );
305 if (activeRoute === undefined) return;
306 const updated = yield* learn({ activeRoute, reported });
307 if (Option.isSome(updated)) {
308 yield* Ref.set(currentEntry, updated.value);
309 yield* requestBetterRouteCheck(lease);
310 }
311 });
312​
313 const routeIndex = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
314 currentRoutes.pipe(
315 Effect.map((routes) =>
316 routes.findIndex(
317 (route) => connectionRouteId(route.target) === connectionRouteId(lease.prepared.target),
318 ),
319 ),
320 );
321​
322 const checkBetterRoutes = Effect.fnUntraced(function* (
323 lease: ConnectionDriver.EnvironmentConnectionLease,
324 ) {
325 const latest = yield* Ref.get(currentEntry);
326 const current = yield* routeIndex(lease);
327 if (current <= 0) return;
328 const now = yield* Clock.monotonicTimeNanos;
329 const cooldowns = yield* Ref.get(routeCooldowns);
330 const better = connectionRoutes(latest)
331 .slice(0, current)
332 .filter((route) => (cooldowns.get(connectionRouteId(route.target)) ?? 0n) <= now);
333 const passed = yield* Effect.forEach(
334 better,
335 (route: ConnectionRoute) => driver.preflight(latest, route),
336 { concurrency: "unbounded" },
337 );
338 const index = passed.indexOf(true);
339 if (index === -1) return;
340 const live = yield* SubscriptionRef.get(session);
341 if (Option.isNone(live) || live.value !== lease.session) return;
342 yield* signal({
343 _tag: "BetterRouteAvailable",
344 routeId: connectionRouteId(better[index]!.target),
345 });
346 });
347​
348 const betterRouteChecks = yield* Queue.dropping<ConnectionDriver.EnvironmentConnectionLease>(1);
349 const requestBetterRouteCheck = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
350 routeIndex(lease).pipe(
351 Effect.flatMap((index) =>
352 index > 0 ? Queue.offer(betterRouteChecks, lease).pipe(Effect.asVoid) : Effect.void,
353 ),
354 );
355​
356 const clearLease = Effect.all(
357 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
358 { discard: true },
359 );
360​
361 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
362 next: SupervisorConnectionState,
363 ) {
364 yield* SubscriptionRef.set(state, next);
365 });
366​
367 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
368 yield* Queue.offer(signals, next);
369 });
370​
371 const logManagedRelayAccountChange = Effect.logInfo(
372 "Managed relay account changed; restarting the environment connection.",
373 ).pipe(
374 Effect.annotateLogs({
375 "environment.id": target.environmentId,
376 "environment.label": target.label,
377 }),
378 );
379​
380 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
381 attempt: number,
382 generation: number,
383 lastFailure: ConnectionAttemptError | null,
384 progress: ConnectionDriver.ConnectionDriverProgress,
385 ) {
386 if ("prepared" in progress) {
387 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
388 }
389 yield* setState(
390 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
391 );
392 });
393​
394 const establishConnection = Effect.fnUntraced(function* (
395 attempt: number,
396 generation: number,
397 lastFailure: ConnectionAttemptError | null,
398 synchronizedRoutes: Ref.Ref<number>,
399 ) {
400 return yield* driver.connect(yield* attemptEntry, (progress) =>
401 (progress.stage === "synchronizing"
402 ? Ref.update(synchronizedRoutes, (count) => count + 1)
403 : Effect.void
404 ).pipe(Effect.andThen(reportProgress(attempt, generation, lastFailure, progress))),
405 );
406 });
407​
408 const traceRelayEstablishment = (
409 effect: Effect.Effect<
410 ConnectionDriver.EnvironmentConnectionLease,
411 ConnectionAttemptError,
412 Scope.Scope
413 >,
414 attempt: number,
415 generation: number,
416 pendingRetry: Option.Option<PendingRetryTrace>,
417 ) => {
418 const traced = Effect.gen(function* () {
419 const attemptSpan = yield* Effect.currentSpan.pipe(Effect.orDie);
420 yield* annotateTarget(target);
421 yield* Effect.annotateCurrentSpan({
422 "connection.attempt": attempt,
423 "connection.generation": generation,
424 "connection.retry.failure_count": Option.match(pendingRetry, {
425 onNone: () => 0,
426 onSome: (retry) => retry.failureCount,
427 }),
428 });
429 const lease = yield* effect.pipe(
430 Effect.mapError((error): TracedAttemptFailure => ({
431 error,
432 attemptSpan: Option.some(attemptSpan),
433 })),
434 );
435 return { attemptSpan: Option.some(attemptSpan), lease };
436 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
437​
438 return Option.match(pendingRetry, {
439 onNone: () => traced,
440 onSome: (retry) =>
441 traced.pipe(
442 Effect.linkSpans(retry.previousAttempt, {
443 "connection.retry.delay_ms": retry.delayMs,
444 "connection.retry.reason": retry.reason,
445 }),
446 ),
447 }).pipe(withRelayClientTracing);
448 };
449​
450 const establishTracedConnection = Effect.fnUntraced(function* (
451 attempt: number,
452 generation: number,
453 lastFailure: ConnectionAttemptError | null,
454 pendingRetry: Option.Option<PendingRetryTrace>,
455 synchronizedRoutes: Ref.Ref<number>,
456 ) {
457 if (usesRelay) {
458 return yield* traceRelayEstablishment(
459 establishConnection(attempt, generation, lastFailure, synchronizedRoutes),
460 attempt,
461 generation,
462 pendingRetry,
463 );
464 }
465 return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe(
466 Effect.map((lease) => ({
467 attemptSpan: Option.none<Tracer.Span>(),
468 lease,
469 })),
470 Effect.mapError((error): TracedAttemptFailure => ({
471 error,
472 attemptSpan: Option.none(),
473 })),
474 );
475 });
476​
477 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
478 for (;;) {
479 const next = yield* Queue.take(signals);
480 switch (next._tag) {
481 case "DisconnectRequested":
482 case "RetryRequested":
483 return false;
484 case "NetworkChanged":
485 if (next.network === "offline") {
486 return false;
487 }
488 break;
489 case "ConnectRequested":
490 case "BetterRouteAvailable":
491 break;
492 case "Wakeup":
493 if (next.reason === "application-active-reconnect") {
494 return true;
495 }
496 if (next.reason === "credentials-changed" && usesRelay) {
497 yield* logManagedRelayAccountChange;
498 return false;
499 }
500 break;
501 }
502 }
503 });
504​
505 const isRelayLease = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
506 lease.prepared.target._tag === "RelayConnectionTarget";
507​
508 const connectedLeaseEnd = Effect.fnUntraced(function* (
509 next: SupervisorSignal,
510 lease: ConnectionDriver.EnvironmentConnectionLease,
511 ) {
512 if (next._tag === "DisconnectRequested") {
513 return "end" as const;
514 }
515 if (next._tag === "BetterRouteAvailable") {
516 yield* Ref.set(preferredRouteId, Option.some(next.routeId));
517 return "reset" as const;
518 }
519 if (next._tag !== "Wakeup") {
520 return undefined;
521 }
522 if (next.reason === "application-active-reconnect") {
523 // Mobile operating systems often kill a suspended socket without a close
524 // event. A probe would show a dead socket as "Resuming" until it times
525 // out, so a long background resume replaces the session at once.
526 return "reset" as const;
527 }
528 // Only a session over T3 Connect holds the old account's credential.
529 if (next.reason === "credentials-changed" && isRelayLease(lease)) {
530 yield* logManagedRelayAccountChange;
531 return "end" as const;
532 }
533 return undefined;
534 });
535​
536 const probeTimeoutFor = (next: SupervisorSignal): Duration.Input | undefined => {
537 switch (next._tag) {
538 case "RetryRequested":
539 return QUICK_CONNECTION_PROBE_TIMEOUT;
540 case "NetworkChanged":
541 return next.network === "offline" ? QUICK_CONNECTION_PROBE_TIMEOUT : undefined;
542 case "Wakeup":
543 if (next.reason === "application-active") {
544 return CONNECTION_PROBE_TIMEOUT;
545 }
546 return next.reason === "application-active-probe" || next.reason === "network-changed"
547 ? QUICK_CONNECTION_PROBE_TIMEOUT
548 : undefined;
549 case "ConnectRequested":
550 case "DisconnectRequested":
551 case "BetterRouteAvailable":
552 return undefined;
553 }
554 };
555​
556 // Returning to the app, an explicit retry, and the network reporting offline
557 // all probe the live session instead of replacing it, so a healthy socket is
558 // not torn down (the offline report is often wrong, for example for a
559 // loopback server).
560 const monitorConnectedLease = Effect.fnUntraced(function* (
561 lease: ConnectionDriver.EnvironmentConnectionLease,
562 ) {
563 // A probe answers an explicit retry here, so the retry must not also reset
564 // the backoff of a later, unrelated failure.
565 const takeSignal = Queue.take(signals).pipe(
566 Effect.tap((next) =>
567 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
568 ),
569 );
570 // Ticks always run: the check skips the preferred route itself, and the
571 // route list can grow while connected (learned routes).
572 yield* Stream.tick(BETTER_ROUTE_CHECK_INTERVAL).pipe(
573 Stream.drop(1),
574 Stream.runForEach(() => requestBetterRouteCheck(lease)),
575 Effect.forkScoped,
576 );
577 for (;;) {
578 const next = yield* takeSignal;
579 const end = yield* connectedLeaseEnd(next, lease);
580 if (end !== undefined) {
581 return end === "reset";
582 }
583 if (
584 (next._tag === "NetworkChanged" && next.network !== "offline") ||
585 (next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
586 ) {
587 yield* requestBetterRouteCheck(lease);
588 }
589 const probeTimeout = probeTimeoutFor(next);
590 if (probeTimeout === undefined) {
591 continue;
592 }
593 yield* Ref.set(probeUnanswered, true);
594 const probe = yield* Effect.forkChild(lease.session.probe);
595 let deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
596 for (;;) {
597 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
598 const probeEvent = yield* Effect.raceAllFirst([
599 Fiber.await(probe).pipe(
600 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
601 ),
602 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
603 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
604 Effect.as({ _tag: "TimedOut" as const }),
605 ),
606 ]);
607 if (probeEvent._tag === "TimedOut") {
608 yield* Fiber.interrupt(probe);
609 return yield* new ConnectionTransientError({
610 reason: "timeout",
611 detail: `${target.label} did not respond to a connection health check.`,
612 });
613 }
614 if (probeEvent._tag === "ProbeCompleted") {
615 if (Exit.isSuccess(probeEvent.exit)) {
616 yield* Ref.set(probeUnanswered, false);
617 }
618 yield* probeEvent.exit;
619 break;
620 }
621 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
622 if (endDuringProbe !== undefined) {
623 yield* Fiber.interrupt(probe);
624 return endDuringProbe === "reset";
625 }
626 const signalTimeout = probeTimeoutFor(probeEvent.signal);
627 if (signalTimeout !== undefined) {
628 const signalDeadline =
629 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
630 if (signalDeadline < deadline) deadline = signalDeadline;
631 }
632 }
633 }
634 });
635​
636 const runAttempt = Effect.fnUntraced(function* (
637 attempt: number,
638 generation: number,
639 lastFailure: ConnectionAttemptError | null,
640 pendingRetry: Option.Option<PendingRetryTrace>,
641 ignoreOffline: boolean,
642 ) {
643 const switchingTo = yield* Ref.get(preferredRouteId);
644 yield* SubscriptionRef.set(prepared, Option.none());
645 const synchronizedRoutes = yield* Ref.make(0);
646 const establishment = yield* Effect.raceAllFirst([
647 exitUnlessInterrupted(
648 establishTracedConnection(
649 attempt,
650 generation,
651 lastFailure,
652 pendingRetry,
653 synchronizedRoutes,
654 ),
655 ).pipe(
656 Effect.map((exit): EstablishmentEvent => ({
657 _tag: "Completed",
658 exit,
659 })),
660 ),
661 waitForEstablishmentInterrupt().pipe(
662 Effect.map((resetRetry): EstablishmentEvent => ({
663 _tag: "Interrupted",
664 resetRetry,
665 })),
666 ),
667 // Each route may use the full setup time before the next is tried, and
668 // each route that reaches synchronizing adds its own snapshot budget, so
669 // a route that fails late does not eat the next route's time.
670 Effect.gen(function* () {
671 const routeCount = connectionRoutes(yield* Ref.get(currentEntry)).length;
672 const startedAt = yield* Clock.monotonicTimeNanos;
673 const setup = Duration.toNanosUnsafe(Duration.times(establishmentTimeout, routeCount));
674 while (true) {
675 const synchronized = BigInt(yield* Ref.get(synchronizedRoutes));
676 const deadline =
677 startedAt + setup + synchronized * Duration.toNanosUnsafe(synchronizationTimeout);
678 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
679 if (remaining <= 0n) {
680 return { _tag: "TimedOut" } as const satisfies EstablishmentEvent;
681 }
682 yield* Effect.sleep(Duration.nanos(remaining));
683 }
684 }),
685 ]);
686​
687 if (establishment._tag === "Interrupted") {
688 return {
689 _tag: "Interrupted",
690 established: false,
691 stable: false,
692 resetRetry: establishment.resetRetry,
693 } satisfies AttemptOutcome;
694 }
695 if (establishment._tag === "TimedOut") {
696 return {
697 _tag: "Failure",
698 established: false,
699 stable: false,
700 failure: {
701 error: new ConnectionTransientError({
702 reason: "timeout",
703 detail: setupTimeoutDetail,
704 }),
705 attemptSpan: Option.none(),
706 },
707 } satisfies AttemptOutcome;
708 }
709 if (Exit.isFailure(establishment.exit)) {
710 const isUnexpectedDefect =
711 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
712 !establishment.exit.cause.reasons.some(Cause.isFailReason);
713 const outcome = failureFromExit(target, establishment.exit, false, false);
714 if (isUnexpectedDefect) {
715 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
716 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
717 Effect.annotateLogs({
718 "environment.id": target.environmentId,
719 "environment.label": target.label,
720 "cause.reason_count": establishment.exit.cause.reasons.length,
721 ...safeErrorLogAttributes(defect),
722 }),
723 );
724 }
725 return outcome;
726 }
727​
728 const active = establishment.exit.value;
729 if (Option.isSome(switchingTo)) {
730 const landed = connectionRouteId(active.lease.prepared.target);
731 if (landed !== switchingTo.value) {
732 const until =
733 (yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
734 yield* Ref.update(routeCooldowns, (current) =>
735 new Map(current).set(switchingTo.value, until),
736 );
737 }
738 }
739 const currentIntent = yield* Ref.get(intent);
740 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
741 return {
742 _tag: "Interrupted",
743 established: false,
744 stable: false,
745 resetRetry: false,
746 } satisfies AttemptOutcome;
747 }
748​
749 const connectedAt = yield* Clock.currentTimeMillis;
750 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
751 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
752 if (options?.learnRoutes !== undefined) {
753 yield* learnRoutesFrom(options.learnRoutes, active.lease).pipe(Effect.forkScoped);
754 }
755 yield* setState({
756 desired: true,
757 network: currentIntent.network,
758 phase: "connected",
759 stage: null,
760 attempt,
761 generation,
762 lastFailure: null,
763 retryAt: null,
764 });
765​
766 const connectedExit = yield* Effect.raceFirst(
767 active.lease.session.closed.pipe(
768 Effect.mapError((error): TracedAttemptFailure => ({
769 error,
770 attemptSpan: active.attemptSpan,
771 })),
772 ),
773 monitorConnectedLease(active.lease).pipe(
774 Effect.mapError((error): TracedAttemptFailure => ({
775 error,
776 attemptSpan: active.attemptSpan,
777 })),
778 ),
779 ).pipe(exitUnlessInterrupted);
780 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
781 if (Exit.isSuccess(connectedExit)) {
782 return {
783 _tag: "Interrupted",
784 established: true,
785 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
786 resetRetry: connectedExit.value,
787 } satisfies AttemptOutcome;
788 }
789 const outcome = failureFromExit(
790 target,
791 connectedExit,
792 true,
793 connectedForMs >= BACKOFF_RESET_AFTER_MS,
794 );
795 if (outcome._tag === "Failure") {
796 yield* Effect.void.pipe(
797 Effect.withSpan("EnvironmentSupervisor.connectionLost", {
798 root: true,
799 attributes: {
800 "environment.id": target.environmentId,
801 "environment.label": target.label,
802 "environment.target.kind": target._tag,
803 "connection.connected_ms": connectedForMs,
804 "connection.failure.reason": outcome.failure.error.reason,
805 "connection.failure.detail": outcome.failure.error.detail,
806 },
807 }),
808 );
809 }
810 return outcome;
811 }, Effect.ensuring(clearLease));
812​
813 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
814 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
815 return yield* Effect.raceFirst(
816 Effect.sleep(delayMs).pipe(Effect.as(false)),
817 Effect.gen(function* () {
818 for (;;) {
819 const next = yield* Queue.take(signals);
820 switch (next._tag) {
821 case "Wakeup":
822 return ConnectionWakeups.resetsRetryBackoff(next.reason);
823 case "ConnectRequested":
824 case "DisconnectRequested":
825 case "RetryRequested":
826 case "NetworkChanged":
827 return false;
828 case "BetterRouteAvailable":
829 break;
830 }
831 }
832 }),
833 );
834 });
835​
836 const waitForSignal = Queue.take(signals).pipe(
837 Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
838 Effect.map(
839 (next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
840 ),
841 );
842​
843 const run = Effect.fnUntraced(function* () {
844 let failureCount = 0;
845 let generation = 0;
846 let latestFailure: ConnectionAttemptError | null = null;
847 let pendingRetry = Option.none<PendingRetryTrace>();
848 const resetRetryLadder = () => {
849 failureCount = 0;
850 pendingRetry = Option.none();
851 };
852 let replacing = false;
853​
854 for (;;) {
855 if (yield* Ref.getAndSet(resetRetryState, false)) {
856 failureCount = 0;
857 latestFailure = null;
858 pendingRetry = Option.none();
859 }
860 const currentIntent = yield* Ref.get(intent);
861 if (!currentIntent.desired) {
862 resetRetryLadder();
863 latestFailure = null;
864 yield* clearLease;
865 yield* setState(availableState(currentIntent, generation));
866 yield* waitForSignal;
867 continue;
868 }
869 if (currentIntent.network === "offline" && !replacing) {
870 yield* clearLease;
871 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
872 const applicationActivated = yield* waitForSignal;
873 if (applicationActivated) {
874 resetRetryLadder();
875 }
876 continue;
877 }
878​
879 const attempt = failureCount + 1;
880 const nextGeneration = generation + 1;
881 const outcome: AttemptOutcome = yield* Effect.scoped(
882 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
883 );
884 replacing = false;
885 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
886 if (outcome.established) {
887 generation = nextGeneration;
888 if (outcome.stable) {
889 resetRetryLadder();
890 latestFailure = null;
891 }
892 }
893 if (outcome._tag === "Interrupted") {
894 if (outcome.resetRetry) {
895 resetRetryLadder();
896 replacing = true;
897 }
898 continue;
899 }
900​
901 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
902 const error: ConnectionAttemptError = outcome.failure.error;
903 latestFailure = error;
904 if (error._tag === "ConnectionBlockedError") {
905 const blockedIntent = yield* Ref.get(intent);
906 yield* setState({
907 desired: blockedIntent.desired,
908 network: blockedIntent.network,
909 phase: "blocked",
910 stage: null,
911 attempt,
912 generation,
913 lastFailure: error,
914 retryAt: null,
915 });
916 const applicationActivated = yield* waitForSignal;
917 if (applicationActivated) {
918 resetRetryLadder();
919 }
920 continue;
921 }
922​
923 if (failedProbe) {
924 resetRetryLadder();
925 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, error));
926 continue;
927 }
928​
929 failureCount += 1;
930 const delayMs = retryDelayMs(failureCount - 1, yield* Random.next);
931 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
932 previousAttempt,
933 failureCount,
934 delayMs,
935 reason: error.reason,
936 }));
937 const failedIntent = yield* Ref.get(intent);
938 yield* setState({
939 desired: failedIntent.desired,
940 network: failedIntent.network,
941 phase: "backoff",
942 stage: null,
943 attempt,
944 generation,
945 lastFailure: error,
946 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
947 });
948 const applicationActivated = yield* waitForRetrySignal(delayMs);
949 if (applicationActivated) {
950 resetRetryLadder();
951 }
952 }
953 });
954​
955 yield* connectivity.changes.pipe(
956 Stream.runForEach((network) =>
957 Ref.modify(intent, (current) =>
958 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
959 ).pipe(
960 Effect.flatMap((changed) =>
961 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
962 ),
963 ),
964 ),
965 Effect.forkScoped,
966 );
967 yield* wakeups.changes.pipe(
968 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
969 Effect.forkScoped,
970 );
971 yield* Queue.take(betterRouteChecks).pipe(
972 Effect.flatMap(checkBetterRoutes),
973 Effect.forever,
974 Effect.forkScoped,
975 );
976 yield* run().pipe(Effect.forkScoped);
977​
978 const connect = Ref.update(intent, (current) => ({
979 ...current,
980 desired: true,
981 })).pipe(
982 Effect.andThen(signal({ _tag: "ConnectRequested" })),
983 Effect.withSpan("EnvironmentSupervisor.connect"),
984 );
985​
986 const disconnect = Ref.update(intent, (current) => ({
987 ...current,
988 desired: false,
989 })).pipe(
990 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
991 Effect.withSpan("EnvironmentSupervisor.disconnect"),
992 );
993​
994 const retryNow = Ref.set(resetRetryState, true).pipe(
995 Effect.andThen(signal({ _tag: "RetryRequested" })),
996 Effect.withSpan("EnvironmentSupervisor.retryNow"),
997 );
998​
999 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1000​
1001 return EnvironmentSupervisor.of({
1002 target,
1003 state,
1004 session,
1005 prepared,
1006 connect,
1007 disconnect,
1008 retryNow,
1009 });
1010});