Open History to see the last commit
1import { msg } from "gt-i18n";
2import { translatableDetail } from "../errors/translatable.ts";
3import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
4import * as Cause from "effect/Cause";
5import * as Clock from "effect/Clock";
6import * as Context from "effect/Context";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Fiber from "effect/Fiber";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Random from "effect/Random";
14import * as Ref from "effect/Ref";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import * as Tracer from "effect/Tracer";
19
20import type { ConnectionCatalogEntry, ConnectionRoute } from "./catalog.ts";
21import * as Connectivity from "./connectivity.ts";
22import * as ConnectionDriver from "./driver.ts";
23import {
24 type ConnectionAttemptError,
25 type ConnectionTarget,
26 ConnectionTransientError,
27 type NetworkStatus,
28 NO_REFUSED_ROUTES,
29 type PreparedConnection,
30 type SupervisorConnectionState,
31} from "./model.ts";
32import * as RpcSession from "../rpc/session.ts";
33import { safeErrorLogAttributes } from "../errors/safeLog.ts";
34import { NETWORK_BLOCKING_HINT } from "../errors/network.ts";
35import * as ConnectionWakeups from "./wakeups.ts";
36import {
37 connectionRouteId,
38 connectionRouteKind,
39 connectionRoutes,
40 type ConnectionRouteKind,
41 entryWithRoutes,
42 insertRoute,
43 type ReportedEndpoint,
44} from "./routes.ts";
45
46const RETRY_BASE_DELAY_MS = 1_000;
47const RETRY_MAX_DELAY_MS = 300_000;
48const SESSION_LOSS_RETRY_DELAY_MS = 250;
49// Someone is approving this device on the host; check back soon rather than climbing the ladder.
50const APPROVAL_PENDING_RETRY_DELAY_MS = 4_000;
51// A request lives 10 minutes; past that nobody is approving, so a forgotten device backs off.
52const APPROVAL_PENDING_FAST_RETRIES = 150;
53// A cold server with a large database can take longer than 15 seconds to
54// answer, and that is not a reason to drop a working connection.
55const CONNECTION_ESTABLISHMENT_TIMEOUT = "15 seconds";
56const establishmentTimeout = Duration.fromInputUnsafe(CONNECTION_ESTABLISHMENT_TIMEOUT);
57const synchronizationTimeout = Duration.fromInputUnsafe("75 seconds");
58const CONNECTION_PROBE_TIMEOUT = "15 seconds";
59const QUICK_CONNECTION_PROBE_TIMEOUT = "3 seconds";
60// After a long suspension pooled connections are often dead too, so the host
61// check can hang with the socket. A replacement is cheaper than the wait.
62const LONG_RESUME_PROBE_TIMEOUT = "1500 millis";
63// A probe still unanswered this long checks the host with a fresh request. If
64// the host answers while the socket stays silent, the socket is dead.
65const SILENT_SOCKET_CHECK_AFTER = "500 millis";
66const SILENT_SOCKET_RECHECK_EVERY = "1 second";
67const FRAME_CHECK_EVERY = "100 millis";
68// Off the LAN one lost packet can stall a live socket for a second, so a remote
69// socket must stay silent this long, except after a long resume. It must end
70// before QUICK_CONNECTION_PROBE_TIMEOUT so a resume replaces a silent socket
71// instead of timing out.
72const REMOTE_SILENT_SOCKET_AFTER = "2500 millis";
73const BACKOFF_RESET_AFTER_MS = 30_000;
74const BETTER_ROUTE_CHECK_INTERVAL_MS = 60_000;
75// Each check of a dead route can wait out the full probe timeout, so a route
76// that keeps failing is checked half as often each time, until the network
77// changes and it may answer again.
78const SILENT_ROUTE_BACKOFF_MAX_MS = 1_800_000;
79// A better route that answered the check but then failed to connect is not
80// tried again for this long, so a flaky LAN cannot bounce the connection.
81const BETTER_ROUTE_COOLDOWN_MS = 300_000;
82
83interface SupervisorIntent {
84 readonly desired: boolean;
85 readonly network: NetworkStatus;
86}
87
88type SupervisorSignal =
89 | { readonly _tag: "ConnectRequested" }
90 | { readonly _tag: "DisconnectRequested" }
91 | { readonly _tag: "RetryRequested" }
92 | { readonly _tag: "NetworkChanged"; readonly network: NetworkStatus }
93 | { readonly _tag: "Wakeup"; readonly reason: ConnectionWakeups.ConnectionWakeup }
94 | { readonly _tag: "BetterRouteAvailable"; readonly routeId: string };
95
96interface PendingRetryTrace {
97 readonly previousAttempt: Tracer.Span;
98 readonly failureCount: number;
99 readonly delayMs: number;
100 readonly reason: ConnectionAttemptError["reason"];
101}
102
103type ConnectedLease = ConnectionDriver.EnvironmentConnectionLease & {
104 readonly activeRoute: ConnectionRoute | undefined;
105 readonly generation: number;
106};
107
108function mergeRefusedRoutes(
109 known: ReadonlyArray<string>,
110 refused: ReadonlyArray<string>,
111 keep: (routeId: string) => boolean,
112): ReadonlyArray<string> {
113 const next = [...new Set([...known, ...refused])].filter(keep);
114 return next.length === known.length && next.every((id, index) => id === known[index])
115 ? known
116 : next;
117}
118
119interface TracedAttemptFailure {
120 readonly error: ConnectionAttemptError;
121 readonly attemptSpan: Option.Option<Tracer.Span>;
122}
123
124type AttemptOutcome =
125 | {
126 readonly _tag: "Interrupted";
127 readonly established: boolean;
128 readonly stable: boolean;
129 readonly resetRetry: boolean;
130 }
131 | {
132 readonly _tag: "Failure";
133 readonly established: boolean;
134 readonly stable: boolean;
135 readonly failure: TracedAttemptFailure;
136 };
137
138type EstablishmentEvent =
139 | {
140 readonly _tag: "Completed";
141 readonly exit: Exit.Exit<
142 {
143 readonly attemptSpan: Option.Option<Tracer.Span>;
144 readonly lease: ConnectionDriver.EnvironmentConnectionLease;
145 },
146 TracedAttemptFailure
147 >;
148 }
149 | { readonly _tag: "Interrupted"; readonly resetRetry: boolean }
150 | { readonly _tag: "TimedOut" };
151
152function exitUnlessInterrupted<A, E, R>(
153 effect: Effect.Effect<A, E, R>,
154): Effect.Effect<Exit.Exit<A, E>, never, R> {
155 return Effect.matchCauseEffect(effect, {
156 onFailure: (cause) =>
157 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Exit.failCause(cause)),
158 onSuccess: (value) => Effect.succeed(Exit.succeed(value)),
159 });
160}
161
162export interface EnvironmentSupervisorOptions {
163 readonly initiallyDesired?: boolean;
164 readonly learnRoutes?: (input: {
165 readonly activeRoute: ConnectionRoute;
166 readonly reported: ReadonlyArray<ReportedEndpoint>;
167 }) => Effect.Effect<Option.Option<ConnectionCatalogEntry>>;
168}
169
170function retryDelayMs(failureCount: number, random: number): number {
171 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failureCount + 1));
172 return Math.round(ceiling / 2 + (ceiling / 2) * random);
173}
174
175interface SilentRoute {
176 readonly failures: number;
177 readonly until: bigint;
178}
179
180function backOffSilentRoute(previous: SilentRoute | undefined, now: bigint): SilentRoute {
181 const failures = (previous?.failures ?? 0) + 1;
182 const delayMs = Math.min(
183 SILENT_ROUTE_BACKOFF_MAX_MS,
184 BETTER_ROUTE_CHECK_INTERVAL_MS * 2 ** failures,
185 );
186 return { failures, until: now + BigInt(delayMs) * 1_000_000n };
187}
188
189function annotateTarget(target: ConnectionTarget) {
190 return Effect.annotateCurrentSpan({
191 "environment.id": target.environmentId,
192 "environment.label": target.label,
193 "environment.target.kind": target._tag,
194 });
195}
196
197function availableState(intent: SupervisorIntent, generation: number): SupervisorConnectionState {
198 return {
199 desired: false,
200 network: intent.network,
201 phase: "available",
202 stage: null,
203 attempt: 0,
204 generation,
205 lastFailure: null,
206 retryAt: null,
207 refusedRouteIds: NO_REFUSED_ROUTES,
208 };
209}
210
211function offlineState(
212 intent: SupervisorIntent,
213 generation: number,
214 attempt: number,
215 lastFailure: ConnectionAttemptError | null,
216): SupervisorConnectionState {
217 return {
218 desired: true,
219 network: intent.network,
220 phase: "offline",
221 stage: null,
222 attempt,
223 generation,
224 lastFailure,
225 retryAt: null,
226 refusedRouteIds: NO_REFUSED_ROUTES,
227 };
228}
229
230function connectingState(
231 intent: SupervisorIntent,
232 generation: number,
233 attempt: number,
234 lastFailure: ConnectionAttemptError | null,
235 stage: SupervisorConnectionState["stage"] = "preparing",
236): SupervisorConnectionState {
237 return {
238 desired: true,
239 network: intent.network,
240 phase: "connecting",
241 stage,
242 attempt,
243 generation,
244 lastFailure,
245 retryAt: null,
246 refusedRouteIds: NO_REFUSED_ROUTES,
247 };
248}
249
250function failureFromExit<A>(
251 target: ConnectionTarget,
252 exit: Exit.Exit<A, TracedAttemptFailure>,
253 established: boolean,
254 stable: boolean,
255): AttemptOutcome {
256 if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) {
257 return { _tag: "Interrupted", established, stable, resetRetry: false };
258 }
259 const typedFailure = exit.cause.reasons.find(Cause.isFailReason);
260 if (typedFailure) {
261 return {
262 _tag: "Failure",
263 established,
264 stable,
265 failure: typedFailure.error,
266 };
267 }
268 return {
269 _tag: "Failure",
270 established,
271 stable,
272 failure: {
273 error: new ConnectionTransientError({
274 reason: "transport",
275 ...translatableDetail(
276 msg("{host} connection failed unexpectedly.", { host: target.label }),
277 ),
278 }),
279 attemptSpan: Option.none(),
280 },
281 };
282}
283
284export class EnvironmentSupervisor extends Context.Service<
285 EnvironmentSupervisor,
286 {
287 readonly target: ConnectionTarget;
288 readonly state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>;
289 readonly session: SubscriptionRef.SubscriptionRef<Option.Option<RpcSession.RpcSession>>;
290 readonly prepared: SubscriptionRef.SubscriptionRef<Option.Option<PreparedConnection>>;
291 readonly connect: Effect.Effect<void>;
292 readonly disconnect: Effect.Effect<void>;
293 readonly retryNow: Effect.Effect<void>;
294 }
295>()("@t3tools/client-runtime/connection/supervisor/EnvironmentSupervisor") {}
296
297export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
298 entry: ConnectionCatalogEntry,
299 options?: EnvironmentSupervisorOptions,
300): Effect.fn.Return<
301 EnvironmentSupervisor["Service"],
302 never,
303 | Connectivity.Connectivity
304 | ConnectionDriver.ConnectionDriver
305 | Scope.Scope
306 | ConnectionWakeups.ConnectionWakeups
307> {
308 const target = entry.target;
309 const usesRelay = connectionRoutes(entry).some(
310 (route) => route.target._tag === "RelayConnectionTarget",
311 );
312 const setupTimeout = msg("{host} did not respond during connection setup.", {
313 host: target.label,
314 });
315 const setupTimeoutDetail = usesRelay
316 ? translatableDetail(setupTimeout, NETWORK_BLOCKING_HINT)
317 : translatableDetail(setupTimeout);
318 yield* annotateTarget(target);
319
320 const connectivity = yield* Connectivity.Connectivity;
321 const driver = yield* ConnectionDriver.ConnectionDriver;
322 const wakeups = yield* ConnectionWakeups.ConnectionWakeups;
323 // The primary environment served this client or runs beside it on loopback,
324 // so the device reporting offline (often wrongly) never parks it. The report
325 // still probes its live session, like any other network change.
326 const targetNetwork = (network: NetworkStatus): NetworkStatus =>
327 network === "offline" && target._tag === "PrimaryConnectionTarget" ? "unknown" : network;
328 const initialIntent: SupervisorIntent = {
329 desired: options?.initiallyDesired ?? false,
330 network: targetNetwork(yield* connectivity.status),
331 };
332 const intent = yield* Ref.make(initialIntent);
333 const signals = yield* Queue.unbounded<SupervisorSignal>();
334 const resetRetryState = yield* Ref.make(false);
335 const probeUnanswered = yield* Ref.make(false);
336 const state = yield* SubscriptionRef.make<SupervisorConnectionState>(
337 !initialIntent.desired
338 ? availableState(initialIntent, 0)
339 : initialIntent.network === "offline"
340 ? offlineState(initialIntent, 0, 0, null)
341 : connectingState(initialIntent, 0, 1, null),
342 );
343 const session = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(Option.none());
344 const prepared = yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none());
345 // Learned routes arrive while a session is live, so the route list is read
346 // fresh by each attempt and check instead of being fixed at creation.
347 const currentEntry = yield* Ref.make(entry);
348 const currentRoutes = Ref.get(currentEntry).pipe(Effect.map(connectionRoutes));
349 const preferredRouteId = yield* Ref.make(Option.none<string>());
350 const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());
351 // Outlives sessions so a reconnect shows a refusal seen earlier; a route leaves once it connects.
352 const refusedRoutes = yield* Ref.make(NO_REFUSED_ROUTES);
353 // The generation keeps a check that started before a reset from recording
354 // its stale failures after it.
355 const silentRoutes = yield* Ref.make({
356 generation: 0,
357 routes: new Map<string, SilentRoute>() as ReadonlyMap<string, SilentRoute>,
358 });
359 const forgetSilentRoutes = Ref.update(silentRoutes, ({ generation }) => ({
360 generation: generation + 1,
361 routes: new Map(),
362 }));
363
364 const attemptEntry = Effect.gen(function* () {
365 const latest = yield* Ref.get(currentEntry);
366 const routes = connectionRoutes(latest);
367 const preferred = yield* Ref.getAndSet(preferredRouteId, Option.none());
368 if (Option.isNone(preferred)) return latest;
369 const route = routes.find(
370 (candidate) => connectionRouteId(candidate.target) === preferred.value,
371 );
372 return route === undefined
373 ? latest
374 : entryWithRoutes(latest, [route, ...routes.filter((candidate) => candidate !== route)]);
375 });
376
377 const learnRoutesFrom = Effect.fnUntraced(function* (
378 learn: NonNullable<EnvironmentSupervisorOptions["learnRoutes"]>,
379 lease: ConnectedLease,
380 ) {
381 const activeRoute = lease.activeRoute;
382 if (activeRoute === undefined) return;
383 yield* lease.session.subscribeServerConfig().pipe(
384 Stream.filter((event) => event.type === "snapshot"),
385 Stream.map((event) => event.config.directEndpoints),
386 Stream.filter((reported) => reported !== undefined),
387 Stream.changesWith((previous, next) => JSON.stringify(previous) === JSON.stringify(next)),
388 Stream.runForEach((reported) =>
389 Effect.gen(function* () {
390 const updated = yield* learn({ activeRoute, reported });
391 if (Option.isSome(updated)) {
392 yield* Ref.set(currentEntry, updated.value);
393 yield* requestBetterRouteCheck(lease);
394 }
395 }),
396 ),
397 Effect.ignoreCause({ log: true }),
398 );
399 });
400
401 const routeIndex = (lease: ConnectedLease) =>
402 currentRoutes.pipe(
403 Effect.map((routes) => {
404 const activeId = connectionRouteId(lease.prepared.target);
405 const index = routes.findIndex((route) => connectionRouteId(route.target) === activeId);
406 return index === -1 && lease.activeRoute !== undefined
407 ? insertRoute(routes, lease.activeRoute).findIndex(
408 (route) => connectionRouteId(route.target) === activeId,
409 )
410 : index;
411 }),
412 );
413
414 const checkBetterRoutes = Effect.fnUntraced(function* (lease: ConnectedLease) {
415 const latest = yield* Ref.get(currentEntry);
416 const current = yield* routeIndex(lease);
417 if (current <= 0) return;
418 const now = yield* Clock.monotonicTimeNanos;
419 const cooldowns = yield* Ref.get(routeCooldowns);
420 const silent = yield* Ref.get(silentRoutes);
421 const better = connectionRoutes(latest)
422 .slice(0, current)
423 .filter((route) => {
424 const id = connectionRouteId(route.target);
425 return (cooldowns.get(id) ?? 0n) <= now && (silent.routes.get(id)?.until ?? 0n) <= now;
426 });
427 const results = yield* Effect.forEach(
428 better,
429 (route: ConnectionRoute) => driver.preflight(latest, route),
430 { concurrency: "unbounded" },
431 );
432 yield* Ref.update(silentRoutes, (previous) => {
433 if (previous.generation !== silent.generation) return previous;
434 const routes = new Map(previous.routes);
435 for (const [position, route] of better.entries()) {
436 const id = connectionRouteId(route.target);
437 if (results[position] !== "silent") routes.delete(id);
438 else routes.set(id, backOffSilentRoute(previous.routes.get(id), now));
439 }
440 return { generation: previous.generation, routes };
441 });
442 const live = yield* SubscriptionRef.get(session);
443 if (Option.isNone(live) || live.value !== lease.session) return;
444 const refused = better
445 .filter((_route, position) => results[position] === "refused")
446 .map((route) => connectionRouteId(route.target));
447 if (refused.length > 0) {
448 const known = yield* Ref.updateAndGet(refusedRoutes, (current) =>
449 mergeRefusedRoutes(current, refused, () => true),
450 );
451 yield* SubscriptionRef.updateSome(state, (current) =>
452 current.phase === "connected" &&
453 current.generation === lease.generation &&
454 current.refusedRouteIds !== known
455 ? Option.some({ ...current, refusedRouteIds: known })
456 : Option.none(),
457 );
458 }
459 const index = results.indexOf("ready");
460 if (index === -1) return;
461 yield* signal({
462 _tag: "BetterRouteAvailable",
463 routeId: connectionRouteId(better[index]!.target),
464 });
465 });
466
467 const betterRouteChecks = yield* Queue.dropping<ConnectedLease>(1);
468 const requestBetterRouteCheck = (lease: ConnectedLease) =>
469 routeIndex(lease).pipe(
470 Effect.flatMap((index) =>
471 index > 0 ? Queue.offer(betterRouteChecks, lease).pipe(Effect.asVoid) : Effect.void,
472 ),
473 );
474
475 const clearLease = Effect.all(
476 [SubscriptionRef.set(session, Option.none()), SubscriptionRef.set(prepared, Option.none())],
477 { discard: true },
478 );
479
480 const setState = Effect.fn("EnvironmentSupervisor.setState")(function* (
481 next: SupervisorConnectionState,
482 ) {
483 yield* SubscriptionRef.set(state, next);
484 });
485
486 const signal = Effect.fn("EnvironmentSupervisor.signal")(function* (next: SupervisorSignal) {
487 yield* Queue.offer(signals, next);
488 });
489
490 const logManagedRelayAccountChange = Effect.logInfo(
491 "Managed relay account changed; restarting the environment connection.",
492 ).pipe(
493 Effect.annotateLogs({
494 "environment.id": target.environmentId,
495 "environment.label": target.label,
496 }),
497 );
498
499 const reportProgress = Effect.fn("EnvironmentSupervisor.reportProgress")(function* (
500 attempt: number,
501 generation: number,
502 lastFailure: ConnectionAttemptError | null,
503 progress: ConnectionDriver.ConnectionDriverProgress,
504 ) {
505 if ("prepared" in progress) {
506 yield* SubscriptionRef.set(prepared, Option.some(progress.prepared));
507 }
508 yield* setState(
509 connectingState(yield* Ref.get(intent), generation, attempt, lastFailure, progress.stage),
510 );
511 });
512
513 const establishConnection = Effect.fnUntraced(function* (
514 attempt: number,
515 generation: number,
516 lastFailure: ConnectionAttemptError | null,
517 synchronizedRoutes: Ref.Ref<number>,
518 ) {
519 return yield* driver.connect(yield* attemptEntry, (progress) =>
520 (progress.stage === "synchronizing"
521 ? Ref.update(synchronizedRoutes, (count) => count + 1)
522 : Effect.void
523 ).pipe(Effect.andThen(reportProgress(attempt, generation, lastFailure, progress))),
524 );
525 });
526
527 // Low-cardinality dimensions for time-to-connected dashboards; the error
528 // detail stays in the span status, never in an attribute.
529 const annotateAttemptOutcome = Effect.fnUntraced(function* (
530 exit: Exit.Exit<ConnectionDriver.EnvironmentConnectionLease, ConnectionAttemptError>,
531 ) {
532 if (Exit.isSuccess(exit)) {
533 const leaseTarget = exit.value.prepared.target;
534 const route = (yield* currentRoutes).find(
535 (candidate) => connectionRouteId(candidate.target) === connectionRouteId(leaseTarget),
536 );
537 return yield* Effect.annotateCurrentSpan({
538 "connection.outcome": "connected",
539 "connection.route": connectionRouteKind(
540 route ?? { target: leaseTarget, profile: Option.none() },
541 ),
542 });
543 }
544 if (Cause.hasInterruptsOnly(exit.cause)) {
545 return yield* Effect.annotateCurrentSpan("connection.outcome", "interrupted");
546 }
547 const failure = exit.cause.reasons.find(Cause.isFailReason)?.error;
548 yield* Effect.annotateCurrentSpan({
549 "connection.outcome": "failed",
550 "connection.failure.tag": failure?._tag ?? "defect",
551 "connection.failure.reason": failure?.reason ?? "defect",
552 });
553 });
554
555 const traceRelayEstablishment = (
556 effect: Effect.Effect<
557 ConnectionDriver.EnvironmentConnectionLease,
558 ConnectionAttemptError,
559 Scope.Scope
560 >,
561 attempt: number,
562 generation: number,
563 pendingRetry: Option.Option<PendingRetryTrace>,
564 ) => {
565 // The span must end with the ConnectionAttemptError itself: the exporter
566 // can only describe an Error-like failure, and a TracedAttemptFailure
567 // wrapper reached it as "[object Object]". The wrapper is added outside.
568 let attemptSpan = Option.none<Tracer.Span>();
569 const traced = Effect.gen(function* () {
570 attemptSpan = Option.some(yield* Effect.currentSpan.pipe(Effect.orDie));
571 yield* Effect.annotateCurrentSpan({
572 "environment.id": target.environmentId,
573 "environment.target.kind": target._tag,
574 "connection.attempt": attempt,
575 "connection.generation": generation,
576 "connection.retry.failure_count": Option.match(pendingRetry, {
577 onNone: () => 0,
578 onSome: (retry) => retry.failureCount,
579 }),
580 });
581 return yield* effect.pipe(Effect.onExit(annotateAttemptOutcome));
582 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
583
584 return Option.match(pendingRetry, {
585 onNone: () => traced,
586 onSome: (retry) =>
587 traced.pipe(
588 Effect.linkSpans(retry.previousAttempt, {
589 "connection.retry.delay_ms": retry.delayMs,
590 "connection.retry.reason": retry.reason,
591 }),
592 ),
593 }).pipe(
594 Effect.map((lease) => ({ attemptSpan, lease })),
595 Effect.mapError((error): TracedAttemptFailure => ({ error, attemptSpan })),
596 withRelayClientTracing,
597 );
598 };
599
600 const establishTracedConnection = Effect.fnUntraced(function* (
601 attempt: number,
602 generation: number,
603 lastFailure: ConnectionAttemptError | null,
604 pendingRetry: Option.Option<PendingRetryTrace>,
605 synchronizedRoutes: Ref.Ref<number>,
606 ) {
607 if (usesRelay) {
608 return yield* traceRelayEstablishment(
609 establishConnection(attempt, generation, lastFailure, synchronizedRoutes),
610 attempt,
611 generation,
612 pendingRetry,
613 );
614 }
615 return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe(
616 Effect.map((lease) => ({
617 attemptSpan: Option.none<Tracer.Span>(),
618 lease,
619 })),
620 Effect.mapError((error): TracedAttemptFailure => ({
621 error,
622 attemptSpan: Option.none(),
623 })),
624 );
625 });
626
627 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* (ignoreOffline: boolean) {
628 // A primary attempt keeps running through an offline report, so the
629 // network returning restarts it in case it stalled meanwhile.
630 let deviceOffline = (yield* connectivity.status) === "offline";
631 for (;;) {
632 const next = yield* Queue.take(signals);
633 switch (next._tag) {
634 case "DisconnectRequested":
635 return false;
636 case "RetryRequested":
637 // Once the loop has taken this retry's flag, the running attempt is
638 // the one the retry asked for.
639 if (yield* Ref.get(resetRetryState)) {
640 return false;
641 }
642 break;
643 case "NetworkChanged":
644 if (target._tag !== "PrimaryConnectionTarget") {
645 if (next.network === "offline" && !ignoreOffline) {
646 return false;
647 }
648 } else if (next.network === "offline") {
649 deviceOffline = true;
650 } else if (deviceOffline) {
651 return true;
652 }
653 break;
654 case "ConnectRequested":
655 case "BetterRouteAvailable":
656 break;
657 case "Wakeup":
658 // An attempt that ran into a long suspension is likely stuck.
659 if (next.reason === "application-active-long") {
660 return true;
661 }
662 if (next.reason === "credentials-changed" && usesRelay) {
663 yield* logManagedRelayAccountChange;
664 return false;
665 }
666 break;
667 }
668 }
669 });
670
671 const isRelayLease = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
672 lease.prepared.target._tag === "RelayConnectionTarget";
673
674 const connectedLeaseEnd = Effect.fnUntraced(function* (
675 next: SupervisorSignal,
676 lease: ConnectionDriver.EnvironmentConnectionLease,
677 ) {
678 if (next._tag === "DisconnectRequested") {
679 return "end" as const;
680 }
681 if (next._tag === "BetterRouteAvailable") {
682 yield* Ref.set(preferredRouteId, Option.some(next.routeId));
683 return "reset" as const;
684 }
685 // Only a session over T3 Connect holds the old account's credential.
686 if (next._tag === "Wakeup" && next.reason === "credentials-changed" && isRelayLease(lease)) {
687 yield* logManagedRelayAccountChange;
688 return "end" as const;
689 }
690 return undefined;
691 });
692
693 const leaseRouteKind = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
694 currentRoutes.pipe(
695 Effect.map((routes) => {
696 const route = routes.find(
697 (candidate) =>
698 connectionRouteId(candidate.target) === connectionRouteId(lease.prepared.target),
699 );
700 return route === undefined ? undefined : connectionRouteKind(route);
701 }),
702 );
703
704 const isLongResume = (signal: SupervisorSignal) =>
705 signal._tag === "Wakeup" && signal.reason === "application-active-long";
706
707 const answersQuickly = (routeKind: ConnectionRouteKind | undefined) =>
708 routeKind === "loopback" || routeKind === "lan";
709
710 const probeTimeoutFor = (
711 next: SupervisorSignal,
712 routeKind: ConnectionRouteKind | undefined,
713 ): Duration.Input | undefined => {
714 switch (next._tag) {
715 case "RetryRequested":
716 return QUICK_CONNECTION_PROBE_TIMEOUT;
717 case "NetworkChanged":
718 return next.network === "offline" ? QUICK_CONNECTION_PROBE_TIMEOUT : undefined;
719 case "Wakeup":
720 if (next.reason === "application-active") {
721 return CONNECTION_PROBE_TIMEOUT;
722 }
723 // After a long suspension the data on screen is stale, so a slow
724 // answer reconnects as quickly as a missing one, even on a remote
725 // route where a reconnect takes longer than the wait it replaces.
726 if (next.reason === "application-active-long") {
727 return LONG_RESUME_PROBE_TIMEOUT;
728 }
729 if (next.reason !== "application-active-probe" && next.reason !== "network-changed") {
730 return undefined;
731 }
732 // Only loopback and LAN answer within 3 seconds reliably. A tailnet
733 // over DERP, a VPN, or the relay can spike past it on a live socket;
734 // a dead one is still caught early by the silent socket check.
735 return answersQuickly(routeKind)
736 ? QUICK_CONNECTION_PROBE_TIMEOUT
737 : CONNECTION_PROBE_TIMEOUT;
738 case "ConnectRequested":
739 case "DisconnectRequested":
740 case "BetterRouteAvailable":
741 return undefined;
742 }
743 };
744
745 const isForegroundProbe = (next: SupervisorSignal) =>
746 next._tag === "Wakeup" && next.reason === "application-active";
747
748 // Ends "silent" when the host answers a fresh request while the socket
749 // delivers nothing, as when iOS kills a suspended socket without a close
750 // event, and "alive" once the socket delivers a frame. A slow or
751 // unreachable host never ends it.
752 const awaitSilentSocket = Effect.fn("EnvironmentSupervisor.awaitSilentSocket")(function* (
753 lease: ConnectedLease,
754 routeKind: ConnectionRouteKind | undefined,
755 longResume: boolean,
756 ) {
757 const startedAt = yield* Clock.monotonicTimeNanos;
758 yield* Effect.sleep(SILENT_SOCKET_CHECK_AFTER);
759 const configLoaded = yield* lease.session.initialConfig.pipe(
760 Effect.as(true),
761 Effect.catchCause(() => Effect.succeed(false)),
762 );
763 if (!configLoaded) return yield* Effect.never;
764 // Frames that queued while the app was suspended have drained by now, so
765 // a later frame shows the path still works.
766 const framesBefore = yield* lease.session.inboundFrames;
767 const socketSilent = lease.session.inboundFrames.pipe(
768 Effect.map((frames) => frames === framesBefore),
769 );
770 // The session only counts frames, so a host check slower than the probe
771 // deadline would otherwise hide a frame until after the socket is replaced.
772 const frameArrives = Effect.sleep(FRAME_CHECK_EVERY).pipe(
773 Effect.andThen(socketSilent),
774 Effect.repeat({ while: (silent) => silent }),
775 Effect.as("alive" as const),
776 );
777 const hostAnswersWhileSilent = Effect.gen(function* () {
778 // A radio still waking up or a stale pooled connection can fail one check.
779 while ((yield* driver.checkHost(lease.prepared)) !== "answered") {
780 yield* Effect.sleep(SILENT_SOCKET_RECHECK_EVERY);
781 }
782 if (!answersQuickly(routeKind) && !longResume) {
783 const silentFor = (yield* Clock.monotonicTimeNanos) - startedAt;
784 const remaining = Duration.toNanosUnsafe(REMOTE_SILENT_SOCKET_AFTER) - silentFor;
785 if (remaining > 0n) yield* Effect.sleep(Duration.nanos(remaining));
786 }
787 return (yield* socketSilent) ? ("silent" as const) : ("alive" as const);
788 });
789 return yield* Effect.race(hostAnswersWhileSilent, frameArrives);
790 });
791
792 // Returning to the app, an explicit retry, and the network reporting offline
793 // all probe the live session instead of replacing it, so a healthy socket is
794 // not torn down (the offline report is often wrong, for example for a
795 // loopback server).
796 const monitorConnectedLease = Effect.fnUntraced(function* (lease: ConnectedLease) {
797 // A probe answers an explicit retry here, so the retry must not also reset
798 // the backoff of a later, unrelated failure.
799 const takeSignal = Queue.take(signals).pipe(
800 Effect.tap((next) =>
801 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
802 ),
803 );
804 // Ticks always run: the check skips the preferred route itself, and the
805 // route list can grow while connected (learned routes).
806 yield* Stream.tick(Duration.millis(BETTER_ROUTE_CHECK_INTERVAL_MS)).pipe(
807 Stream.drop(1),
808 Stream.runForEach(() => requestBetterRouteCheck(lease)),
809 Effect.forkScoped,
810 );
811 const routeKind = yield* leaseRouteKind(lease);
812 for (;;) {
813 const next = yield* takeSignal;
814 const end = yield* connectedLeaseEnd(next, lease);
815 if (end !== undefined) {
816 return end === "reset";
817 }
818 if (
819 (next._tag === "NetworkChanged" && next.network !== "offline") ||
820 (next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
821 ) {
822 yield* requestBetterRouteCheck(lease);
823 }
824 const probeTimeout = probeTimeoutFor(next, routeKind);
825 if (probeTimeout === undefined) {
826 continue;
827 }
828 yield* Ref.set(probeUnanswered, true);
829 let probe = yield* Effect.forkChild(lease.session.probe);
830 // A busy server can miss one foreground probe while the socket is still
831 // healthy, so the first miss asks again and only the follow-up's miss
832 // replaces the session.
833 let toleratesMiss = isForegroundProbe(next);
834 let silentSocket: Fiber.Fiber<"silent" | "alive"> | undefined;
835 // A signal during a running check, such as a network change that kills
836 // the socket, needs a fresh check only if the running one sees a frame.
837 let recheck = false;
838 let longResume = isLongResume(next);
839 const startSilentSocketCheck = Effect.gen(function* () {
840 silentSocket = yield* Effect.forkChild(awaitSilentSocket(lease, routeKind, longResume));
841 recheck = false;
842 });
843 // The web and desktop foreground probe allows a busy host 15 seconds,
844 // and a busy host can answer a fresh request before a queued probe.
845 const armSilentSocketCheck = Effect.fnUntraced(function* (signal: SupervisorSignal) {
846 if (isForegroundProbe(signal)) return;
847 if (silentSocket !== undefined) {
848 recheck = true;
849 return;
850 }
851 yield* startSilentSocketCheck;
852 });
853 yield* armSilentSocketCheck(next);
854 const stopProbe = Effect.suspend(() =>
855 Effect.all(
856 [Fiber.interrupt(probe), silentSocket ? Fiber.interrupt(silentSocket) : Effect.void],
857 { discard: true },
858 ),
859 );
860 let longResumeStartedAt = yield* Clock.monotonicTimeNanos;
861 let deadline = longResumeStartedAt + Duration.toNanosUnsafe(probeTimeout);
862 for (;;) {
863 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
864 const probeEvent = yield* Effect.raceAllFirst([
865 Fiber.await(probe).pipe(
866 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
867 ),
868 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
869 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
870 Effect.as({ _tag: "TimedOut" as const }),
871 ),
872 (silentSocket ? Fiber.join(silentSocket) : Effect.never).pipe(
873 Effect.map((check) =>
874 check === "silent"
875 ? { _tag: "SocketSilent" as const }
876 : { _tag: "SocketAlive" as const },
877 ),
878 ),
879 ]);
880 if (probeEvent._tag === "SocketAlive") {
881 silentSocket = undefined;
882 // A frame shows the socket still works, so its probe gets the usual resume time.
883 if (longResume) {
884 const aliveDeadline =
885 longResumeStartedAt + Duration.toNanosUnsafe(QUICK_CONNECTION_PROBE_TIMEOUT);
886 if (aliveDeadline > deadline) deadline = aliveDeadline;
887 }
888 if (recheck) yield* startSilentSocketCheck;
889 continue;
890 }
891 if (probeEvent._tag === "SocketSilent") {
892 // The host is reachable, so replace the socket at once, even while
893 // the network reports offline.
894 yield* stopProbe;
895 return true;
896 }
897 if (probeEvent._tag === "TimedOut") {
898 if (toleratesMiss) {
899 toleratesMiss = false;
900 yield* Fiber.interrupt(probe);
901 probe = yield* Effect.forkChild(lease.session.probe);
902 deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
903 continue;
904 }
905 yield* stopProbe;
906 // A long suspension leaves the socket suspect even when the network
907 // reports offline, so it is replaced like a silent one.
908 if (longResume) return true;
909 return yield* new ConnectionTransientError({
910 reason: "timeout",
911 ...translatableDetail(
912 msg("{host} did not respond to a connection health check.", {
913 host: target.label,
914 }),
915 ),
916 });
917 }
918 if (probeEvent._tag === "ProbeCompleted") {
919 if (silentSocket) yield* Fiber.interrupt(silentSocket);
920 if (Exit.isSuccess(probeEvent.exit)) {
921 yield* Ref.set(probeUnanswered, false);
922 }
923 yield* probeEvent.exit;
924 break;
925 }
926 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
927 if (endDuringProbe !== undefined) {
928 yield* stopProbe;
929 return endDuringProbe === "reset";
930 }
931 const signalTimeout = probeTimeoutFor(probeEvent.signal, routeKind);
932 if (signalTimeout !== undefined) {
933 // A retry or network signal wants a definite answer, even when its
934 // own deadline lands after the foreground one.
935 if (!isForegroundProbe(probeEvent.signal)) toleratesMiss = false;
936 if (isLongResume(probeEvent.signal) && !longResume) {
937 longResume = true;
938 longResumeStartedAt = yield* Clock.monotonicTimeNanos;
939 }
940 yield* armSilentSocketCheck(probeEvent.signal);
941 const signalDeadline =
942 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
943 if (signalDeadline < deadline) deadline = signalDeadline;
944 }
945 }
946 }
947 });
948
949 const runAttempt = Effect.fnUntraced(function* (
950 attempt: number,
951 generation: number,
952 lastFailure: ConnectionAttemptError | null,
953 pendingRetry: Option.Option<PendingRetryTrace>,
954 ignoreOffline: boolean,
955 ) {
956 const switchingTo = yield* Ref.get(preferredRouteId);
957 yield* SubscriptionRef.set(prepared, Option.none());
958 const synchronizedRoutes = yield* Ref.make(0);
959 const establishment = yield* Effect.raceAllFirst([
960 exitUnlessInterrupted(
961 establishTracedConnection(
962 attempt,
963 generation,
964 lastFailure,
965 pendingRetry,
966 synchronizedRoutes,
967 ),
968 ).pipe(
969 Effect.map((exit): EstablishmentEvent => ({
970 _tag: "Completed",
971 exit,
972 })),
973 ),
974 waitForEstablishmentInterrupt(ignoreOffline).pipe(
975 Effect.map((resetRetry): EstablishmentEvent => ({
976 _tag: "Interrupted",
977 resetRetry,
978 })),
979 ),
980 // Each route may use the full setup time before the next is tried, and
981 // each route that reaches synchronizing adds its own snapshot budget, so
982 // a route that fails late does not eat the next route's time.
983 Effect.gen(function* () {
984 const routes = connectionRoutes(yield* Ref.get(currentEntry));
985 const setup = Duration.toNanosUnsafe(Duration.times(establishmentTimeout, routes.length));
986 // The desktop bounds SSH preparation, which may download a server
987 // release, so for SSH-only entries the clock stops while preparing.
988 const pausesWhilePreparing = routes.every((route) => connectionRouteKind(route) === "ssh");
989 const preparing = (expected: boolean) =>
990 SubscriptionRef.changes(state).pipe(
991 Stream.filter((current) => (current.stage === "preparing") === expected),
992 Stream.runHead,
993 );
994 let spent = 0n;
995 while (true) {
996 if (pausesWhilePreparing) yield* preparing(false);
997 const synchronized = BigInt(yield* Ref.get(synchronizedRoutes));
998 const remaining =
999 setup + synchronized * Duration.toNanosUnsafe(synchronizationTimeout) - spent;
1000 if (remaining <= 0n) {
1001 return { _tag: "TimedOut" } as const satisfies EstablishmentEvent;
1002 }
1003 const resumedAt = yield* Clock.monotonicTimeNanos;
1004 const sleep = Effect.sleep(Duration.nanos(remaining));
1005 yield* pausesWhilePreparing ? Effect.raceFirst(sleep, preparing(true)) : sleep;
1006 spent += (yield* Clock.monotonicTimeNanos) - resumedAt;
1007 }
1008 }),
1009 ]);
1010
1011 if (establishment._tag === "Interrupted") {
1012 return {
1013 _tag: "Interrupted",
1014 established: false,
1015 stable: false,
1016 resetRetry: establishment.resetRetry,
1017 } satisfies AttemptOutcome;
1018 }
1019 if (establishment._tag === "TimedOut") {
1020 return {
1021 _tag: "Failure",
1022 established: false,
1023 stable: false,
1024 failure: {
1025 error: new ConnectionTransientError({
1026 reason: "timeout",
1027 ...setupTimeoutDetail,
1028 }),
1029 attemptSpan: Option.none(),
1030 },
1031 } satisfies AttemptOutcome;
1032 }
1033 if (Exit.isFailure(establishment.exit)) {
1034 const isUnexpectedDefect =
1035 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
1036 !establishment.exit.cause.reasons.some(Cause.isFailReason);
1037 const outcome = failureFromExit(target, establishment.exit, false, false);
1038 if (isUnexpectedDefect) {
1039 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
1040 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
1041 Effect.annotateLogs({
1042 "environment.id": target.environmentId,
1043 "environment.label": target.label,
1044 "cause.reason_count": establishment.exit.cause.reasons.length,
1045 ...safeErrorLogAttributes(defect),
1046 }),
1047 );
1048 }
1049 return outcome;
1050 }
1051
1052 const active = establishment.exit.value;
1053 if (Option.isSome(switchingTo)) {
1054 const landed = connectionRouteId(active.lease.prepared.target);
1055 if (landed !== switchingTo.value) {
1056 const until =
1057 (yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
1058 yield* Ref.update(routeCooldowns, (current) =>
1059 new Map(current).set(switchingTo.value, until),
1060 );
1061 }
1062 }
1063 const currentIntent = yield* Ref.get(intent);
1064 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
1065 return {
1066 _tag: "Interrupted",
1067 established: false,
1068 stable: false,
1069 resetRetry: false,
1070 } satisfies AttemptOutcome;
1071 }
1072
1073 const routes = yield* currentRoutes;
1074 const activeRouteId = connectionRouteId(active.lease.prepared.target);
1075 const connectedLease: ConnectedLease = {
1076 ...active.lease,
1077 activeRoute: routes.find((route) => connectionRouteId(route.target) === activeRouteId),
1078 generation,
1079 };
1080 const refusedRouteIds = yield* Ref.updateAndGet(refusedRoutes, (known) =>
1081 mergeRefusedRoutes(
1082 known,
1083 active.lease.refusedRouteIds,
1084 (id) =>
1085 id !== activeRouteId && routes.some((route) => connectionRouteId(route.target) === id),
1086 ),
1087 );
1088 const connectedAt = yield* Clock.currentTimeMillis;
1089 yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared));
1090 yield* SubscriptionRef.set(session, Option.some(connectedLease.session));
1091 if (options?.learnRoutes !== undefined) {
1092 yield* learnRoutesFrom(options.learnRoutes, connectedLease).pipe(Effect.forkScoped);
1093 }
1094 yield* setState({
1095 desired: true,
1096 network: currentIntent.network,
1097 phase: "connected",
1098 stage: null,
1099 attempt,
1100 generation,
1101 lastFailure: null,
1102 retryAt: null,
1103 refusedRouteIds,
1104 });
1105
1106 const connectedExit = yield* Effect.raceFirst(
1107 connectedLease.session.closed.pipe(
1108 Effect.mapError((error): TracedAttemptFailure => ({
1109 error,
1110 attemptSpan: active.attemptSpan,
1111 })),
1112 ),
1113 monitorConnectedLease(connectedLease).pipe(
1114 Effect.mapError((error): TracedAttemptFailure => ({
1115 error,
1116 attemptSpan: active.attemptSpan,
1117 })),
1118 ),
1119 ).pipe(exitUnlessInterrupted);
1120 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
1121 if (Exit.isSuccess(connectedExit)) {
1122 return {
1123 _tag: "Interrupted",
1124 established: true,
1125 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
1126 resetRetry: connectedExit.value,
1127 } satisfies AttemptOutcome;
1128 }
1129 const outcome = failureFromExit(
1130 target,
1131 connectedExit,
1132 true,
1133 connectedForMs >= BACKOFF_RESET_AFTER_MS,
1134 );
1135 if (outcome._tag === "Failure") {
1136 yield* Effect.void.pipe(
1137 Effect.withSpan("EnvironmentSupervisor.connectionLost", {
1138 root: true,
1139 attributes: {
1140 "environment.id": target.environmentId,
1141 "environment.label": target.label,
1142 "environment.target.kind": target._tag,
1143 "connection.connected_ms": connectedForMs,
1144 "connection.failure.reason": outcome.failure.error.reason,
1145 "connection.failure.detail": outcome.failure.error.detail,
1146 },
1147 }),
1148 );
1149 }
1150 return outcome;
1151 }, Effect.ensuring(clearLease));
1152
1153 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
1154 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
1155 return yield* Effect.raceFirst(
1156 Effect.sleep(delayMs).pipe(Effect.as(false)),
1157 Effect.gen(function* () {
1158 for (;;) {
1159 const next = yield* Queue.take(signals);
1160 switch (next._tag) {
1161 case "Wakeup":
1162 return ConnectionWakeups.resetsRetryBackoff(next.reason);
1163 case "ConnectRequested":
1164 case "DisconnectRequested":
1165 case "RetryRequested":
1166 case "NetworkChanged":
1167 return false;
1168 case "BetterRouteAvailable":
1169 break;
1170 }
1171 }
1172 }),
1173 );
1174 });
1175
1176 const waitForSignal = Queue.take(signals).pipe(
1177 Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
1178 Effect.map(
1179 (next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
1180 ),
1181 );
1182
1183 const run = Effect.fnUntraced(function* () {
1184 let failureCount = 0;
1185 // Approval waits count as attempts but not toward backoff, so a later outage starts low.
1186 let backoffFailures = 0;
1187 let approvalWaits = 0;
1188 let generation = 0;
1189 let latestFailure: ConnectionAttemptError | null = null;
1190 let pendingRetry = Option.none<PendingRetryTrace>();
1191 const resetRetryLadder = () => {
1192 failureCount = 0;
1193 backoffFailures = 0;
1194 approvalWaits = 0;
1195 pendingRetry = Option.none();
1196 };
1197 let replacing = false;
1198
1199 for (;;) {
1200 const retryRequested = yield* Ref.getAndSet(resetRetryState, false);
1201 if (retryRequested) {
1202 failureCount = 0;
1203 backoffFailures = 0;
1204 approvalWaits = 0;
1205 latestFailure = null;
1206 pendingRetry = Option.none();
1207 }
1208 const currentIntent = yield* Ref.get(intent);
1209 if (!currentIntent.desired) {
1210 resetRetryLadder();
1211 latestFailure = null;
1212 yield* clearLease;
1213 yield* setState(availableState(currentIntent, generation));
1214 yield* waitForSignal;
1215 continue;
1216 }
1217 // The platform's offline report can stay wrong after the network is back,
1218 // so an explicit retry still tries instead of waiting for it to change.
1219 const ignoreOffline = replacing || retryRequested;
1220 if (currentIntent.network === "offline" && !ignoreOffline) {
1221 yield* clearLease;
1222 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
1223 const applicationActivated = yield* waitForSignal;
1224 if (applicationActivated) {
1225 resetRetryLadder();
1226 }
1227 continue;
1228 }
1229
1230 const attempt = failureCount + 1;
1231 const nextGeneration = generation + 1;
1232 const outcome: AttemptOutcome = yield* Effect.scoped(
1233 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, ignoreOffline),
1234 );
1235 replacing = false;
1236 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
1237 if (outcome.established) {
1238 generation = nextGeneration;
1239 // A session came up, so no earlier failure describes the connection.
1240 // Losing a live session is not a failed connection either, for example
1241 // a socket the OS killed while the app was suspended: its replacement
1242 // reports no failure until it fails itself.
1243 latestFailure = null;
1244 if (outcome.stable) {
1245 resetRetryLadder();
1246 }
1247 }
1248 if (outcome._tag === "Interrupted") {
1249 if (outcome.resetRetry) {
1250 resetRetryLadder();
1251 replacing = true;
1252 }
1253 continue;
1254 }
1255
1256 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
1257 const error: ConnectionAttemptError = outcome.failure.error;
1258 if (!outcome.established) {
1259 latestFailure = error;
1260 }
1261 if (error._tag === "ConnectionBlockedError") {
1262 const blockedIntent = yield* Ref.get(intent);
1263 yield* setState({
1264 desired: blockedIntent.desired,
1265 network: blockedIntent.network,
1266 phase: "blocked",
1267 stage: null,
1268 attempt,
1269 generation,
1270 lastFailure: error,
1271 retryAt: null,
1272 refusedRouteIds: NO_REFUSED_ROUTES,
1273 });
1274 const applicationActivated = yield* waitForSignal;
1275 if (applicationActivated) {
1276 resetRetryLadder();
1277 }
1278 continue;
1279 }
1280
1281 if (failedProbe) {
1282 resetRetryLadder();
1283 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, latestFailure));
1284 continue;
1285 }
1286
1287 // The first loss of a live session retries almost at once; the ladder
1288 // still counts it, so a host that keeps dropping sessions backs off.
1289 const firstLoss = outcome.established && failureCount === 0;
1290 failureCount += 1;
1291 if (error.reason === "approval-pending") approvalWaits += 1;
1292 const awaitingApproval =
1293 error.reason === "approval-pending" && approvalWaits <= APPROVAL_PENDING_FAST_RETRIES;
1294 if (!awaitingApproval) backoffFailures += 1;
1295 const delayMs = awaitingApproval
1296 ? APPROVAL_PENDING_RETRY_DELAY_MS
1297 : firstLoss
1298 ? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
1299 : error.reason === "approval-pending"
1300 ? Math.max(
1301 APPROVAL_PENDING_RETRY_DELAY_MS,
1302 retryDelayMs(backoffFailures - 1, yield* Random.next),
1303 )
1304 : retryDelayMs(backoffFailures - 1, yield* Random.next);
1305 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
1306 previousAttempt,
1307 failureCount,
1308 delayMs,
1309 reason: error.reason,
1310 }));
1311 const failedIntent = yield* Ref.get(intent);
1312 yield* setState({
1313 desired: failedIntent.desired,
1314 network: failedIntent.network,
1315 phase: "backoff",
1316 stage: null,
1317 attempt,
1318 generation,
1319 lastFailure: latestFailure,
1320 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
1321 refusedRouteIds: NO_REFUSED_ROUTES,
1322 });
1323 const applicationActivated = yield* waitForRetrySignal(delayMs);
1324 if (applicationActivated) {
1325 resetRetryLadder();
1326 }
1327 }
1328 });
1329
1330 yield* connectivity.changes.pipe(
1331 Stream.runForEach((network) =>
1332 Ref.modify(intent, (current) => {
1333 const next = targetNetwork(network);
1334 return current.network === next
1335 ? [false, current]
1336 : ([true, { ...current, network: next }] as const);
1337 }).pipe(
1338 Effect.flatMap((changed) =>
1339 changed
1340 ? (network === "offline" ? Effect.void : forgetSilentRoutes).pipe(
1341 Effect.andThen(signal({ _tag: "NetworkChanged", network })),
1342 )
1343 : Effect.void,
1344 ),
1345 ),
1346 ),
1347 Effect.forkScoped,
1348 );
1349 yield* wakeups.changes.pipe(
1350 Stream.filter(ConnectionWakeups.reachesConnectionSupervisor),
1351 Stream.runForEach((reason) =>
1352 // A long suspension can hide a network change the platform never reported.
1353 (reason === "network-changed" || reason === "application-active-long"
1354 ? forgetSilentRoutes
1355 : Effect.void
1356 ).pipe(Effect.andThen(signal({ _tag: "Wakeup", reason }))),
1357 ),
1358 Effect.forkScoped,
1359 );
1360 yield* Queue.take(betterRouteChecks).pipe(
1361 Effect.flatMap(checkBetterRoutes),
1362 Effect.forever,
1363 Effect.forkScoped,
1364 );
1365 yield* run().pipe(Effect.forkScoped);
1366
1367 const connect = Ref.update(intent, (current) => ({
1368 ...current,
1369 desired: true,
1370 })).pipe(
1371 Effect.andThen(signal({ _tag: "ConnectRequested" })),
1372 Effect.withSpan("EnvironmentSupervisor.connect"),
1373 );
1374
1375 const disconnect = Ref.update(intent, (current) => ({
1376 ...current,
1377 desired: false,
1378 })).pipe(
1379 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
1380 Effect.withSpan("EnvironmentSupervisor.disconnect"),
1381 );
1382
1383 const retryNow = Ref.set(resetRetryState, true).pipe(
1384 Effect.andThen(signal({ _tag: "RetryRequested" })),
1385 Effect.withSpan("EnvironmentSupervisor.retryNow"),
1386 );
1387
1388 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1389
1390 return EnvironmentSupervisor.of({
1391 target,
1392 state,
1393 session,
1394 prepared,
1395 connect,
1396 disconnect,
1397 retryNow,
1398 });
1399});