Open History to see the last commit
1import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
2import * as Cause from "effect/Cause";
3import * as Clock from "effect/Clock";
4import * as Context from "effect/Context";
5import * as 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;
69}
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"];
84}
85
86interface TracedAttemptFailure {
87 readonly error: ConnectionAttemptError;
88 readonly attemptSpan: Option.Option<Tracer.Span>;
89}
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 });
127}
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>>;
135}
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);
140}
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 });
148}
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 };
161}
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 };
179}
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 };
198}
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 };
230}
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 const configLoaded = yield* lease.session.initialConfig.pipe(
632 Effect.as(true),
633 Effect.catchCause(() => Effect.succeed(false)),
634 );
635 if (!configLoaded) return yield* Effect.never;
636 // Frames that queued while the app was suspended have drained by now, so
637 // a later frame shows the path still works.
638 const framesBefore = yield* lease.session.inboundFrames;
639 const socketSilent = lease.session.inboundFrames.pipe(
640 Effect.map((frames) => frames === framesBefore),
641 );
642 // A radio still waking up or a stale pooled connection can fail one check.
643 while ((yield* driver.checkHost(lease.prepared)) !== "answered") {
644 if (!(yield* socketSilent)) return "alive" as const;
645 yield* Effect.sleep(SILENT_SOCKET_RECHECK_EVERY);
646 }
647 if (!answersQuickly(routeKind)) {
648 const silentFor = (yield* Clock.monotonicTimeNanos) - startedAt;
649 const remaining = Duration.toNanosUnsafe(REMOTE_SILENT_SOCKET_AFTER) - silentFor;
650 if (remaining > 0n) yield* Effect.sleep(Duration.nanos(remaining));
651 }
652 return (yield* socketSilent) ? ("silent" as const) : ("alive" as const);
653 });
654
655 // Returning to the app, an explicit retry, and the network reporting offline
656 // all probe the live session instead of replacing it, so a healthy socket is
657 // not torn down (the offline report is often wrong, for example for a
658 // loopback server).
659 const monitorConnectedLease = Effect.fnUntraced(function* (
660 lease: ConnectionDriver.EnvironmentConnectionLease,
661 ) {
662 // A probe answers an explicit retry here, so the retry must not also reset
663 // the backoff of a later, unrelated failure.
664 const takeSignal = Queue.take(signals).pipe(
665 Effect.tap((next) =>
666 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
667 ),
668 );
669 // Ticks always run: the check skips the preferred route itself, and the
670 // route list can grow while connected (learned routes).
671 yield* Stream.tick(BETTER_ROUTE_CHECK_INTERVAL).pipe(
672 Stream.drop(1),
673 Stream.runForEach(() => requestBetterRouteCheck(lease)),
674 Effect.forkScoped,
675 );
676 const routeKind = yield* leaseRouteKind(lease);
677 for (;;) {
678 const next = yield* takeSignal;
679 const end = yield* connectedLeaseEnd(next, lease);
680 if (end !== undefined) {
681 return end === "reset";
682 }
683 if (
684 (next._tag === "NetworkChanged" && next.network !== "offline") ||
685 (next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
686 ) {
687 yield* requestBetterRouteCheck(lease);
688 }
689 const probeTimeout = probeTimeoutFor(next, routeKind);
690 if (probeTimeout === undefined) {
691 continue;
692 }
693 yield* Ref.set(probeUnanswered, true);
694 const probe = yield* Effect.forkChild(lease.session.probe);
695 let silentSocket: Fiber.Fiber<"silent" | "alive"> | undefined;
696 // A signal during a running check, such as a network change that kills
697 // the socket, needs a fresh check only if the running one sees a frame.
698 let recheck = false;
699 let longResume = isLongResume(next);
700 const startSilentSocketCheck = Effect.gen(function* () {
701 silentSocket = yield* Effect.forkChild(awaitSilentSocket(lease, routeKind));
702 recheck = false;
703 });
704 // The web and desktop foreground probe allows a busy host 15 seconds,
705 // and a busy host can answer a fresh request before a queued probe.
706 const armSilentSocketCheck = Effect.fnUntraced(function* (signal: SupervisorSignal) {
707 if (signal._tag === "Wakeup" && signal.reason === "application-active") return;
708 if (silentSocket !== undefined) {
709 recheck = true;
710 return;
711 }
712 yield* startSilentSocketCheck;
713 });
714 yield* armSilentSocketCheck(next);
715 const stopProbe = Effect.suspend(() =>
716 Effect.all(
717 [Fiber.interrupt(probe), silentSocket ? Fiber.interrupt(silentSocket) : Effect.void],
718 { discard: true },
719 ),
720 );
721 let deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
722 for (;;) {
723 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
724 const probeEvent = yield* Effect.raceAllFirst([
725 Fiber.await(probe).pipe(
726 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
727 ),
728 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
729 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
730 Effect.as({ _tag: "TimedOut" as const }),
731 ),
732 (silentSocket ? Fiber.join(silentSocket) : Effect.never).pipe(
733 Effect.map((check) =>
734 check === "silent"
735 ? { _tag: "SocketSilent" as const }
736 : { _tag: "SocketAlive" as const },
737 ),
738 ),
739 ]);
740 if (probeEvent._tag === "SocketAlive") {
741 silentSocket = undefined;
742 if (recheck) yield* startSilentSocketCheck;
743 continue;
744 }
745 if (probeEvent._tag === "SocketSilent") {
746 // The host is reachable, so replace the socket at once, even while
747 // the network reports offline.
748 yield* stopProbe;
749 return true;
750 }
751 if (probeEvent._tag === "TimedOut") {
752 yield* stopProbe;
753 // A long suspension leaves the socket suspect even when the network
754 // reports offline, so it is replaced like a silent one.
755 if (longResume) return true;
756 return yield* new ConnectionTransientError({
757 reason: "timeout",
758 detail: `${target.label} did not respond to a connection health check.`,
759 });
760 }
761 if (probeEvent._tag === "ProbeCompleted") {
762 if (silentSocket) yield* Fiber.interrupt(silentSocket);
763 if (Exit.isSuccess(probeEvent.exit)) {
764 yield* Ref.set(probeUnanswered, false);
765 }
766 yield* probeEvent.exit;
767 break;
768 }
769 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
770 if (endDuringProbe !== undefined) {
771 yield* stopProbe;
772 return endDuringProbe === "reset";
773 }
774 const signalTimeout = probeTimeoutFor(probeEvent.signal, routeKind);
775 if (signalTimeout !== undefined) {
776 yield* armSilentSocketCheck(probeEvent.signal);
777 longResume ||= isLongResume(probeEvent.signal);
778 const signalDeadline =
779 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
780 if (signalDeadline < deadline) deadline = signalDeadline;
781 }
782 }
783 }
784 });
785
786 const runAttempt = Effect.fnUntraced(function* (
787 attempt: number,
788 generation: number,
789 lastFailure: ConnectionAttemptError | null,
790 pendingRetry: Option.Option<PendingRetryTrace>,
791 ignoreOffline: boolean,
792 ) {
793 const switchingTo = yield* Ref.get(preferredRouteId);
794 yield* SubscriptionRef.set(prepared, Option.none());
795 const synchronizedRoutes = yield* Ref.make(0);
796 const establishment = yield* Effect.raceAllFirst([
797 exitUnlessInterrupted(
798 establishTracedConnection(
799 attempt,
800 generation,
801 lastFailure,
802 pendingRetry,
803 synchronizedRoutes,
804 ),
805 ).pipe(
806 Effect.map((exit): EstablishmentEvent => ({
807 _tag: "Completed",
808 exit,
809 })),
810 ),
811 waitForEstablishmentInterrupt().pipe(
812 Effect.map((resetRetry): EstablishmentEvent => ({
813 _tag: "Interrupted",
814 resetRetry,
815 })),
816 ),
817 // Each route may use the full setup time before the next is tried, and
818 // each route that reaches synchronizing adds its own snapshot budget, so
819 // a route that fails late does not eat the next route's time.
820 Effect.gen(function* () {
821 const routeCount = connectionRoutes(yield* Ref.get(currentEntry)).length;
822 const startedAt = yield* Clock.monotonicTimeNanos;
823 const setup = Duration.toNanosUnsafe(Duration.times(establishmentTimeout, routeCount));
824 while (true) {
825 const synchronized = BigInt(yield* Ref.get(synchronizedRoutes));
826 const deadline =
827 startedAt + setup + synchronized * Duration.toNanosUnsafe(synchronizationTimeout);
828 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
829 if (remaining <= 0n) {
830 return { _tag: "TimedOut" } as const satisfies EstablishmentEvent;
831 }
832 yield* Effect.sleep(Duration.nanos(remaining));
833 }
834 }),
835 ]);
836
837 if (establishment._tag === "Interrupted") {
838 return {
839 _tag: "Interrupted",
840 established: false,
841 stable: false,
842 resetRetry: establishment.resetRetry,
843 } satisfies AttemptOutcome;
844 }
845 if (establishment._tag === "TimedOut") {
846 return {
847 _tag: "Failure",
848 established: false,
849 stable: false,
850 failure: {
851 error: new ConnectionTransientError({
852 reason: "timeout",
853 detail: setupTimeoutDetail,
854 }),
855 attemptSpan: Option.none(),
856 },
857 } satisfies AttemptOutcome;
858 }
859 if (Exit.isFailure(establishment.exit)) {
860 const isUnexpectedDefect =
861 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
862 !establishment.exit.cause.reasons.some(Cause.isFailReason);
863 const outcome = failureFromExit(target, establishment.exit, false, false);
864 if (isUnexpectedDefect) {
865 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
866 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
867 Effect.annotateLogs({
868 "environment.id": target.environmentId,
869 "environment.label": target.label,
870 "cause.reason_count": establishment.exit.cause.reasons.length,
871 ...safeErrorLogAttributes(defect),
872 }),
873 );
874 }
875 return outcome;
876 }
877
878 const active = establishment.exit.value;
879 if (Option.isSome(switchingTo)) {
880 const landed = connectionRouteId(active.lease.prepared.target);
881 if (landed !== switchingTo.value) {
882 const until =
883 (yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
884 yield* Ref.update(routeCooldowns, (current) =>
885 new Map(current).set(switchingTo.value, until),
886 );
887 }
888 }
889 const currentIntent = yield* Ref.get(intent);
890 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
891 return {
892 _tag: "Interrupted",
893 established: false,
894 stable: false,
895 resetRetry: false,
896 } satisfies AttemptOutcome;
897 }
898
899 const connectedAt = yield* Clock.currentTimeMillis;
900 yield* SubscriptionRef.set(prepared, Option.some(active.lease.prepared));
901 yield* SubscriptionRef.set(session, Option.some(active.lease.session));
902 if (options?.learnRoutes !== undefined) {
903 yield* learnRoutesFrom(options.learnRoutes, active.lease).pipe(Effect.forkScoped);
904 }
905 yield* setState({
906 desired: true,
907 network: currentIntent.network,
908 phase: "connected",
909 stage: null,
910 attempt,
911 generation,
912 lastFailure: null,
913 retryAt: null,
914 });
915
916 const connectedExit = yield* Effect.raceFirst(
917 active.lease.session.closed.pipe(
918 Effect.mapError((error): TracedAttemptFailure => ({
919 error,
920 attemptSpan: active.attemptSpan,
921 })),
922 ),
923 monitorConnectedLease(active.lease).pipe(
924 Effect.mapError((error): TracedAttemptFailure => ({
925 error,
926 attemptSpan: active.attemptSpan,
927 })),
928 ),
929 ).pipe(exitUnlessInterrupted);
930 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
931 if (Exit.isSuccess(connectedExit)) {
932 return {
933 _tag: "Interrupted",
934 established: true,
935 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
936 resetRetry: connectedExit.value,
937 } satisfies AttemptOutcome;
938 }
939 const outcome = failureFromExit(
940 target,
941 connectedExit,
942 true,
943 connectedForMs >= BACKOFF_RESET_AFTER_MS,
944 );
945 if (outcome._tag === "Failure") {
946 yield* Effect.void.pipe(
947 Effect.withSpan("EnvironmentSupervisor.connectionLost", {
948 root: true,
949 attributes: {
950 "environment.id": target.environmentId,
951 "environment.label": target.label,
952 "environment.target.kind": target._tag,
953 "connection.connected_ms": connectedForMs,
954 "connection.failure.reason": outcome.failure.error.reason,
955 "connection.failure.detail": outcome.failure.error.detail,
956 },
957 }),
958 );
959 }
960 return outcome;
961 }, Effect.ensuring(clearLease));
962
963 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
964 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
965 return yield* Effect.raceFirst(
966 Effect.sleep(delayMs).pipe(Effect.as(false)),
967 Effect.gen(function* () {
968 for (;;) {
969 const next = yield* Queue.take(signals);
970 switch (next._tag) {
971 case "Wakeup":
972 return ConnectionWakeups.resetsRetryBackoff(next.reason);
973 case "ConnectRequested":
974 case "DisconnectRequested":
975 case "RetryRequested":
976 case "NetworkChanged":
977 return false;
978 case "BetterRouteAvailable":
979 break;
980 }
981 }
982 }),
983 );
984 });
985
986 const waitForSignal = Queue.take(signals).pipe(
987 Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
988 Effect.map(
989 (next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
990 ),
991 );
992
993 const run = Effect.fnUntraced(function* () {
994 let failureCount = 0;
995 let generation = 0;
996 let latestFailure: ConnectionAttemptError | null = null;
997 let pendingRetry = Option.none<PendingRetryTrace>();
998 const resetRetryLadder = () => {
999 failureCount = 0;
1000 pendingRetry = Option.none();
1001 };
1002 let replacing = false;
1003
1004 for (;;) {
1005 if (yield* Ref.getAndSet(resetRetryState, false)) {
1006 failureCount = 0;
1007 latestFailure = null;
1008 pendingRetry = Option.none();
1009 }
1010 const currentIntent = yield* Ref.get(intent);
1011 if (!currentIntent.desired) {
1012 resetRetryLadder();
1013 latestFailure = null;
1014 yield* clearLease;
1015 yield* setState(availableState(currentIntent, generation));
1016 yield* waitForSignal;
1017 continue;
1018 }
1019 if (currentIntent.network === "offline" && !replacing) {
1020 yield* clearLease;
1021 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
1022 const applicationActivated = yield* waitForSignal;
1023 if (applicationActivated) {
1024 resetRetryLadder();
1025 }
1026 continue;
1027 }
1028
1029 const attempt = failureCount + 1;
1030 const nextGeneration = generation + 1;
1031 const outcome: AttemptOutcome = yield* Effect.scoped(
1032 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
1033 );
1034 replacing = false;
1035 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
1036 if (outcome.established) {
1037 generation = nextGeneration;
1038 // A session came up, so no earlier failure describes the connection.
1039 // Losing a live session is not a failed connection either, for example
1040 // a socket the OS killed while the app was suspended: its replacement
1041 // reports no failure until it fails itself.
1042 latestFailure = null;
1043 if (outcome.stable) {
1044 resetRetryLadder();
1045 }
1046 }
1047 if (outcome._tag === "Interrupted") {
1048 if (outcome.resetRetry) {
1049 resetRetryLadder();
1050 replacing = true;
1051 }
1052 continue;
1053 }
1054
1055 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
1056 const error: ConnectionAttemptError = outcome.failure.error;
1057 if (!outcome.established) {
1058 latestFailure = error;
1059 }
1060 if (error._tag === "ConnectionBlockedError") {
1061 const blockedIntent = yield* Ref.get(intent);
1062 yield* setState({
1063 desired: blockedIntent.desired,
1064 network: blockedIntent.network,
1065 phase: "blocked",
1066 stage: null,
1067 attempt,
1068 generation,
1069 lastFailure: error,
1070 retryAt: null,
1071 });
1072 const applicationActivated = yield* waitForSignal;
1073 if (applicationActivated) {
1074 resetRetryLadder();
1075 }
1076 continue;
1077 }
1078
1079 if (failedProbe) {
1080 resetRetryLadder();
1081 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, latestFailure));
1082 continue;
1083 }
1084
1085 failureCount += 1;
1086 const delayMs = retryDelayMs(failureCount - 1, yield* Random.next);
1087 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
1088 previousAttempt,
1089 failureCount,
1090 delayMs,
1091 reason: error.reason,
1092 }));
1093 const failedIntent = yield* Ref.get(intent);
1094 yield* setState({
1095 desired: failedIntent.desired,
1096 network: failedIntent.network,
1097 phase: "backoff",
1098 stage: null,
1099 attempt,
1100 generation,
1101 lastFailure: latestFailure,
1102 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
1103 });
1104 const applicationActivated = yield* waitForRetrySignal(delayMs);
1105 if (applicationActivated) {
1106 resetRetryLadder();
1107 }
1108 }
1109 });
1110
1111 yield* connectivity.changes.pipe(
1112 Stream.runForEach((network) =>
1113 Ref.modify(intent, (current) =>
1114 current.network === network ? [false, current] : ([true, { ...current, network }] as const),
1115 ).pipe(
1116 Effect.flatMap((changed) =>
1117 changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,
1118 ),
1119 ),
1120 ),
1121 Effect.forkScoped,
1122 );
1123 yield* wakeups.changes.pipe(
1124 Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),
1125 Effect.forkScoped,
1126 );
1127 yield* Queue.take(betterRouteChecks).pipe(
1128 Effect.flatMap(checkBetterRoutes),
1129 Effect.forever,
1130 Effect.forkScoped,
1131 );
1132 yield* run().pipe(Effect.forkScoped);
1133
1134 const connect = Ref.update(intent, (current) => ({
1135 ...current,
1136 desired: true,
1137 })).pipe(
1138 Effect.andThen(signal({ _tag: "ConnectRequested" })),
1139 Effect.withSpan("EnvironmentSupervisor.connect"),
1140 );
1141
1142 const disconnect = Ref.update(intent, (current) => ({
1143 ...current,
1144 desired: false,
1145 })).pipe(
1146 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
1147 Effect.withSpan("EnvironmentSupervisor.disconnect"),
1148 );
1149
1150 const retryNow = Ref.set(resetRetryState, true).pipe(
1151 Effect.andThen(signal({ _tag: "RetryRequested" })),
1152 Effect.withSpan("EnvironmentSupervisor.retryNow"),
1153 );
1154
1155 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1156
1157 return EnvironmentSupervisor.of({
1158 target,
1159 state,
1160 session,
1161 prepared,
1162 connect,
1163 disconnect,
1164 retryNow,
1165 });
1166});