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

supervisor.ts

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