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