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

supervisor.ts

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