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* annotateTarget(target);
532 yield* Effect.annotateCurrentSpan({
533 "connection.attempt": attempt,
534 "connection.generation": generation,
535 "connection.retry.failure_count": Option.match(pendingRetry, {
536 onNone: () => 0,
537 onSome: (retry) => retry.failureCount,
538 }),
539 });
540 return yield* effect.pipe(Effect.onExit(annotateAttemptOutcome));
541 }).pipe(Effect.withSpan("relay.connection.attempt", { root: true }));
542
543 return Option.match(pendingRetry, {
544 onNone: () => traced,
545 onSome: (retry) =>
546 traced.pipe(
547 Effect.linkSpans(retry.previousAttempt, {
548 "connection.retry.delay_ms": retry.delayMs,
549 "connection.retry.reason": retry.reason,
550 }),
551 ),
552 }).pipe(
553 Effect.map((lease) => ({ attemptSpan, lease })),
554 Effect.mapError((error): TracedAttemptFailure => ({ error, attemptSpan })),
555 withRelayClientTracing,
556 );
557 };
558
559 const establishTracedConnection = Effect.fnUntraced(function* (
560 attempt: number,
561 generation: number,
562 lastFailure: ConnectionAttemptError | null,
563 pendingRetry: Option.Option<PendingRetryTrace>,
564 synchronizedRoutes: Ref.Ref<number>,
565 ) {
566 if (usesRelay) {
567 return yield* traceRelayEstablishment(
568 establishConnection(attempt, generation, lastFailure, synchronizedRoutes),
569 attempt,
570 generation,
571 pendingRetry,
572 );
573 }
574 return yield* establishConnection(attempt, generation, lastFailure, synchronizedRoutes).pipe(
575 Effect.map((lease) => ({
576 attemptSpan: Option.none<Tracer.Span>(),
577 lease,
578 })),
579 Effect.mapError((error): TracedAttemptFailure => ({
580 error,
581 attemptSpan: Option.none(),
582 })),
583 );
584 });
585
586 const waitForEstablishmentInterrupt = Effect.fnUntraced(function* () {
587 // A primary attempt keeps running through an offline report, so the
588 // network returning restarts it in case it stalled meanwhile.
589 let deviceOffline = (yield* connectivity.status) === "offline";
590 for (;;) {
591 const next = yield* Queue.take(signals);
592 switch (next._tag) {
593 case "DisconnectRequested":
594 case "RetryRequested":
595 return false;
596 case "NetworkChanged":
597 if (target._tag !== "PrimaryConnectionTarget") {
598 if (next.network === "offline") {
599 return false;
600 }
601 } else if (next.network === "offline") {
602 deviceOffline = true;
603 } else if (deviceOffline) {
604 return true;
605 }
606 break;
607 case "ConnectRequested":
608 case "BetterRouteAvailable":
609 break;
610 case "Wakeup":
611 // An attempt that ran into a long suspension is likely stuck.
612 if (next.reason === "application-active-long") {
613 return true;
614 }
615 if (next.reason === "credentials-changed" && usesRelay) {
616 yield* logManagedRelayAccountChange;
617 return false;
618 }
619 break;
620 }
621 }
622 });
623
624 const isRelayLease = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
625 lease.prepared.target._tag === "RelayConnectionTarget";
626
627 const connectedLeaseEnd = Effect.fnUntraced(function* (
628 next: SupervisorSignal,
629 lease: ConnectionDriver.EnvironmentConnectionLease,
630 ) {
631 if (next._tag === "DisconnectRequested") {
632 return "end" as const;
633 }
634 if (next._tag === "BetterRouteAvailable") {
635 yield* Ref.set(preferredRouteId, Option.some(next.routeId));
636 return "reset" as const;
637 }
638 // Only a session over T3 Connect holds the old account's credential.
639 if (next._tag === "Wakeup" && next.reason === "credentials-changed" && isRelayLease(lease)) {
640 yield* logManagedRelayAccountChange;
641 return "end" as const;
642 }
643 return undefined;
644 });
645
646 const leaseRouteKind = (lease: ConnectionDriver.EnvironmentConnectionLease) =>
647 currentRoutes.pipe(
648 Effect.map((routes) => {
649 const route = routes.find(
650 (candidate) =>
651 connectionRouteId(candidate.target) === connectionRouteId(lease.prepared.target),
652 );
653 return route === undefined ? undefined : connectionRouteKind(route);
654 }),
655 );
656
657 const isLongResume = (signal: SupervisorSignal) =>
658 signal._tag === "Wakeup" && signal.reason === "application-active-long";
659
660 const answersQuickly = (routeKind: ConnectionRouteKind | undefined) =>
661 routeKind === "loopback" || routeKind === "lan";
662
663 const probeTimeoutFor = (
664 next: SupervisorSignal,
665 routeKind: ConnectionRouteKind | undefined,
666 ): Duration.Input | undefined => {
667 switch (next._tag) {
668 case "RetryRequested":
669 return QUICK_CONNECTION_PROBE_TIMEOUT;
670 case "NetworkChanged":
671 return next.network === "offline" ? QUICK_CONNECTION_PROBE_TIMEOUT : undefined;
672 case "Wakeup":
673 if (next.reason === "application-active") {
674 return CONNECTION_PROBE_TIMEOUT;
675 }
676 // After a long suspension the data on screen is stale, so a slow
677 // answer reconnects as quickly as a missing one, even on a remote
678 // route where a reconnect takes longer than the wait it replaces.
679 if (next.reason === "application-active-long") {
680 return LONG_RESUME_PROBE_TIMEOUT;
681 }
682 if (next.reason !== "application-active-probe" && next.reason !== "network-changed") {
683 return undefined;
684 }
685 // Only loopback and LAN answer within 3 seconds reliably. A tailnet
686 // over DERP, a VPN, or the relay can spike past it on a live socket;
687 // a dead one is still caught early by the silent socket check.
688 return answersQuickly(routeKind)
689 ? QUICK_CONNECTION_PROBE_TIMEOUT
690 : CONNECTION_PROBE_TIMEOUT;
691 case "ConnectRequested":
692 case "DisconnectRequested":
693 case "BetterRouteAvailable":
694 return undefined;
695 }
696 };
697
698 const isForegroundProbe = (next: SupervisorSignal) =>
699 next._tag === "Wakeup" && next.reason === "application-active";
700
701 // Ends "silent" when the host answers a fresh request while the socket
702 // delivers nothing, as when iOS kills a suspended socket without a close
703 // event, and "alive" once the socket delivers a frame. A slow or
704 // unreachable host never ends it.
705 const awaitSilentSocket = Effect.fn("EnvironmentSupervisor.awaitSilentSocket")(function* (
706 lease: ConnectedLease,
707 routeKind: ConnectionRouteKind | undefined,
708 longResume: boolean,
709 ) {
710 const startedAt = yield* Clock.monotonicTimeNanos;
711 yield* Effect.sleep(SILENT_SOCKET_CHECK_AFTER);
712 const configLoaded = yield* lease.session.initialConfig.pipe(
713 Effect.as(true),
714 Effect.catchCause(() => Effect.succeed(false)),
715 );
716 if (!configLoaded) return yield* Effect.never;
717 // Frames that queued while the app was suspended have drained by now, so
718 // a later frame shows the path still works.
719 const framesBefore = yield* lease.session.inboundFrames;
720 const socketSilent = lease.session.inboundFrames.pipe(
721 Effect.map((frames) => frames === framesBefore),
722 );
723 // The session only counts frames, so a host check slower than the probe
724 // deadline would otherwise hide a frame until after the socket is replaced.
725 const frameArrives = Effect.sleep(FRAME_CHECK_EVERY).pipe(
726 Effect.andThen(socketSilent),
727 Effect.repeat({ while: (silent) => silent }),
728 Effect.as("alive" as const),
729 );
730 const hostAnswersWhileSilent = Effect.gen(function* () {
731 // A radio still waking up or a stale pooled connection can fail one check.
732 while ((yield* driver.checkHost(lease.prepared)) !== "answered") {
733 yield* Effect.sleep(SILENT_SOCKET_RECHECK_EVERY);
734 }
735 if (!answersQuickly(routeKind) && !longResume) {
736 const silentFor = (yield* Clock.monotonicTimeNanos) - startedAt;
737 const remaining = Duration.toNanosUnsafe(REMOTE_SILENT_SOCKET_AFTER) - silentFor;
738 if (remaining > 0n) yield* Effect.sleep(Duration.nanos(remaining));
739 }
740 return (yield* socketSilent) ? ("silent" as const) : ("alive" as const);
741 });
742 return yield* Effect.race(hostAnswersWhileSilent, frameArrives);
743 });
744
745 // Returning to the app, an explicit retry, and the network reporting offline
746 // all probe the live session instead of replacing it, so a healthy socket is
747 // not torn down (the offline report is often wrong, for example for a
748 // loopback server).
749 const monitorConnectedLease = Effect.fnUntraced(function* (lease: ConnectedLease) {
750 // A probe answers an explicit retry here, so the retry must not also reset
751 // the backoff of a later, unrelated failure.
752 const takeSignal = Queue.take(signals).pipe(
753 Effect.tap((next) =>
754 next._tag === "RetryRequested" ? Ref.set(resetRetryState, false) : Effect.void,
755 ),
756 );
757 // Ticks always run: the check skips the preferred route itself, and the
758 // route list can grow while connected (learned routes).
759 yield* Stream.tick(Duration.millis(BETTER_ROUTE_CHECK_INTERVAL_MS)).pipe(
760 Stream.drop(1),
761 Stream.runForEach(() => requestBetterRouteCheck(lease)),
762 Effect.forkScoped,
763 );
764 const routeKind = yield* leaseRouteKind(lease);
765 for (;;) {
766 const next = yield* takeSignal;
767 const end = yield* connectedLeaseEnd(next, lease);
768 if (end !== undefined) {
769 return end === "reset";
770 }
771 if (
772 (next._tag === "NetworkChanged" && next.network !== "offline") ||
773 (next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason))
774 ) {
775 yield* requestBetterRouteCheck(lease);
776 }
777 const probeTimeout = probeTimeoutFor(next, routeKind);
778 if (probeTimeout === undefined) {
779 continue;
780 }
781 yield* Ref.set(probeUnanswered, true);
782 let probe = yield* Effect.forkChild(lease.session.probe);
783 // A busy server can miss one foreground probe while the socket is still
784 // healthy, so the first miss asks again and only the follow-up's miss
785 // replaces the session.
786 let toleratesMiss = isForegroundProbe(next);
787 let silentSocket: Fiber.Fiber<"silent" | "alive"> | undefined;
788 // A signal during a running check, such as a network change that kills
789 // the socket, needs a fresh check only if the running one sees a frame.
790 let recheck = false;
791 let longResume = isLongResume(next);
792 const startSilentSocketCheck = Effect.gen(function* () {
793 silentSocket = yield* Effect.forkChild(awaitSilentSocket(lease, routeKind, longResume));
794 recheck = false;
795 });
796 // The web and desktop foreground probe allows a busy host 15 seconds,
797 // and a busy host can answer a fresh request before a queued probe.
798 const armSilentSocketCheck = Effect.fnUntraced(function* (signal: SupervisorSignal) {
799 if (isForegroundProbe(signal)) return;
800 if (silentSocket !== undefined) {
801 recheck = true;
802 return;
803 }
804 yield* startSilentSocketCheck;
805 });
806 yield* armSilentSocketCheck(next);
807 const stopProbe = Effect.suspend(() =>
808 Effect.all(
809 [Fiber.interrupt(probe), silentSocket ? Fiber.interrupt(silentSocket) : Effect.void],
810 { discard: true },
811 ),
812 );
813 let longResumeStartedAt = yield* Clock.monotonicTimeNanos;
814 let deadline = longResumeStartedAt + Duration.toNanosUnsafe(probeTimeout);
815 for (;;) {
816 const remaining = deadline - (yield* Clock.monotonicTimeNanos);
817 const probeEvent = yield* Effect.raceAllFirst([
818 Fiber.await(probe).pipe(
819 Effect.map((exit) => ({ _tag: "ProbeCompleted" as const, exit })),
820 ),
821 takeSignal.pipe(Effect.map((signal) => ({ _tag: "Signal" as const, signal }))),
822 Effect.sleep(Duration.nanos(remaining > 0n ? remaining : 0n)).pipe(
823 Effect.as({ _tag: "TimedOut" as const }),
824 ),
825 (silentSocket ? Fiber.join(silentSocket) : Effect.never).pipe(
826 Effect.map((check) =>
827 check === "silent"
828 ? { _tag: "SocketSilent" as const }
829 : { _tag: "SocketAlive" as const },
830 ),
831 ),
832 ]);
833 if (probeEvent._tag === "SocketAlive") {
834 silentSocket = undefined;
835 // A frame shows the socket still works, so its probe gets the usual resume time.
836 if (longResume) {
837 const aliveDeadline =
838 longResumeStartedAt + Duration.toNanosUnsafe(QUICK_CONNECTION_PROBE_TIMEOUT);
839 if (aliveDeadline > deadline) deadline = aliveDeadline;
840 }
841 if (recheck) yield* startSilentSocketCheck;
842 continue;
843 }
844 if (probeEvent._tag === "SocketSilent") {
845 // The host is reachable, so replace the socket at once, even while
846 // the network reports offline.
847 yield* stopProbe;
848 return true;
849 }
850 if (probeEvent._tag === "TimedOut") {
851 if (toleratesMiss) {
852 toleratesMiss = false;
853 yield* Fiber.interrupt(probe);
854 probe = yield* Effect.forkChild(lease.session.probe);
855 deadline = (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(probeTimeout);
856 continue;
857 }
858 yield* stopProbe;
859 // A long suspension leaves the socket suspect even when the network
860 // reports offline, so it is replaced like a silent one.
861 if (longResume) return true;
862 return yield* new ConnectionTransientError({
863 reason: "timeout",
864 detail: `${target.label} did not respond to a connection health check.`,
865 });
866 }
867 if (probeEvent._tag === "ProbeCompleted") {
868 if (silentSocket) yield* Fiber.interrupt(silentSocket);
869 if (Exit.isSuccess(probeEvent.exit)) {
870 yield* Ref.set(probeUnanswered, false);
871 }
872 yield* probeEvent.exit;
873 break;
874 }
875 const endDuringProbe = yield* connectedLeaseEnd(probeEvent.signal, lease);
876 if (endDuringProbe !== undefined) {
877 yield* stopProbe;
878 return endDuringProbe === "reset";
879 }
880 const signalTimeout = probeTimeoutFor(probeEvent.signal, routeKind);
881 if (signalTimeout !== undefined) {
882 // A retry or network signal wants a definite answer, even when its
883 // own deadline lands after the foreground one.
884 if (!isForegroundProbe(probeEvent.signal)) toleratesMiss = false;
885 if (isLongResume(probeEvent.signal) && !longResume) {
886 longResume = true;
887 longResumeStartedAt = yield* Clock.monotonicTimeNanos;
888 }
889 yield* armSilentSocketCheck(probeEvent.signal);
890 const signalDeadline =
891 (yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
892 if (signalDeadline < deadline) deadline = signalDeadline;
893 }
894 }
895 }
896 });
897
898 const runAttempt = Effect.fnUntraced(function* (
899 attempt: number,
900 generation: number,
901 lastFailure: ConnectionAttemptError | null,
902 pendingRetry: Option.Option<PendingRetryTrace>,
903 ignoreOffline: boolean,
904 ) {
905 const switchingTo = yield* Ref.get(preferredRouteId);
906 yield* SubscriptionRef.set(prepared, Option.none());
907 const synchronizedRoutes = yield* Ref.make(0);
908 const establishment = yield* Effect.raceAllFirst([
909 exitUnlessInterrupted(
910 establishTracedConnection(
911 attempt,
912 generation,
913 lastFailure,
914 pendingRetry,
915 synchronizedRoutes,
916 ),
917 ).pipe(
918 Effect.map((exit): EstablishmentEvent => ({
919 _tag: "Completed",
920 exit,
921 })),
922 ),
923 waitForEstablishmentInterrupt().pipe(
924 Effect.map((resetRetry): EstablishmentEvent => ({
925 _tag: "Interrupted",
926 resetRetry,
927 })),
928 ),
929 // Each route may use the full setup time before the next is tried, and
930 // each route that reaches synchronizing adds its own snapshot budget, so
931 // a route that fails late does not eat the next route's time.
932 Effect.gen(function* () {
933 const routes = connectionRoutes(yield* Ref.get(currentEntry));
934 const setup = Duration.toNanosUnsafe(Duration.times(establishmentTimeout, routes.length));
935 // The desktop bounds SSH preparation, which may download a server
936 // release, so for SSH-only entries the clock stops while preparing.
937 const pausesWhilePreparing = routes.every((route) => connectionRouteKind(route) === "ssh");
938 const preparing = (expected: boolean) =>
939 SubscriptionRef.changes(state).pipe(
940 Stream.filter((current) => (current.stage === "preparing") === expected),
941 Stream.runHead,
942 );
943 let spent = 0n;
944 while (true) {
945 if (pausesWhilePreparing) yield* preparing(false);
946 const synchronized = BigInt(yield* Ref.get(synchronizedRoutes));
947 const remaining =
948 setup + synchronized * Duration.toNanosUnsafe(synchronizationTimeout) - spent;
949 if (remaining <= 0n) {
950 return { _tag: "TimedOut" } as const satisfies EstablishmentEvent;
951 }
952 const resumedAt = yield* Clock.monotonicTimeNanos;
953 const sleep = Effect.sleep(Duration.nanos(remaining));
954 yield* pausesWhilePreparing ? Effect.raceFirst(sleep, preparing(true)) : sleep;
955 spent += (yield* Clock.monotonicTimeNanos) - resumedAt;
956 }
957 }),
958 ]);
959
960 if (establishment._tag === "Interrupted") {
961 return {
962 _tag: "Interrupted",
963 established: false,
964 stable: false,
965 resetRetry: establishment.resetRetry,
966 } satisfies AttemptOutcome;
967 }
968 if (establishment._tag === "TimedOut") {
969 return {
970 _tag: "Failure",
971 established: false,
972 stable: false,
973 failure: {
974 error: new ConnectionTransientError({
975 reason: "timeout",
976 detail: setupTimeoutDetail,
977 }),
978 attemptSpan: Option.none(),
979 },
980 } satisfies AttemptOutcome;
981 }
982 if (Exit.isFailure(establishment.exit)) {
983 const isUnexpectedDefect =
984 !Cause.hasInterruptsOnly(establishment.exit.cause) &&
985 !establishment.exit.cause.reasons.some(Cause.isFailReason);
986 const outcome = failureFromExit(target, establishment.exit, false, false);
987 if (isUnexpectedDefect) {
988 const defect = establishment.exit.cause.reasons.find(Cause.isDieReason)?.defect;
989 yield* Effect.logError("Connection attempt failed with an unexpected defect.").pipe(
990 Effect.annotateLogs({
991 "environment.id": target.environmentId,
992 "environment.label": target.label,
993 "cause.reason_count": establishment.exit.cause.reasons.length,
994 ...safeErrorLogAttributes(defect),
995 }),
996 );
997 }
998 return outcome;
999 }
1000
1001 const active = establishment.exit.value;
1002 if (Option.isSome(switchingTo)) {
1003 const landed = connectionRouteId(active.lease.prepared.target);
1004 if (landed !== switchingTo.value) {
1005 const until =
1006 (yield* Clock.monotonicTimeNanos) + BigInt(BETTER_ROUTE_COOLDOWN_MS) * 1_000_000n;
1007 yield* Ref.update(routeCooldowns, (current) =>
1008 new Map(current).set(switchingTo.value, until),
1009 );
1010 }
1011 }
1012 const currentIntent = yield* Ref.get(intent);
1013 if (!currentIntent.desired || (currentIntent.network === "offline" && !ignoreOffline)) {
1014 return {
1015 _tag: "Interrupted",
1016 established: false,
1017 stable: false,
1018 resetRetry: false,
1019 } satisfies AttemptOutcome;
1020 }
1021
1022 const connectedLease: ConnectedLease = {
1023 ...active.lease,
1024 activeRoute: (yield* currentRoutes).find(
1025 (route) =>
1026 connectionRouteId(route.target) === connectionRouteId(active.lease.prepared.target),
1027 ),
1028 };
1029 const connectedAt = yield* Clock.currentTimeMillis;
1030 yield* SubscriptionRef.set(prepared, Option.some(connectedLease.prepared));
1031 yield* SubscriptionRef.set(session, Option.some(connectedLease.session));
1032 if (options?.learnRoutes !== undefined) {
1033 yield* learnRoutesFrom(options.learnRoutes, connectedLease).pipe(Effect.forkScoped);
1034 }
1035 yield* setState({
1036 desired: true,
1037 network: currentIntent.network,
1038 phase: "connected",
1039 stage: null,
1040 attempt,
1041 generation,
1042 lastFailure: null,
1043 retryAt: null,
1044 });
1045
1046 const connectedExit = yield* Effect.raceFirst(
1047 connectedLease.session.closed.pipe(
1048 Effect.mapError((error): TracedAttemptFailure => ({
1049 error,
1050 attemptSpan: active.attemptSpan,
1051 })),
1052 ),
1053 monitorConnectedLease(connectedLease).pipe(
1054 Effect.mapError((error): TracedAttemptFailure => ({
1055 error,
1056 attemptSpan: active.attemptSpan,
1057 })),
1058 ),
1059 ).pipe(exitUnlessInterrupted);
1060 const connectedForMs = (yield* Clock.currentTimeMillis) - connectedAt;
1061 if (Exit.isSuccess(connectedExit)) {
1062 return {
1063 _tag: "Interrupted",
1064 established: true,
1065 stable: connectedForMs >= BACKOFF_RESET_AFTER_MS,
1066 resetRetry: connectedExit.value,
1067 } satisfies AttemptOutcome;
1068 }
1069 const outcome = failureFromExit(
1070 target,
1071 connectedExit,
1072 true,
1073 connectedForMs >= BACKOFF_RESET_AFTER_MS,
1074 );
1075 if (outcome._tag === "Failure") {
1076 yield* Effect.void.pipe(
1077 Effect.withSpan("EnvironmentSupervisor.connectionLost", {
1078 root: true,
1079 attributes: {
1080 "environment.id": target.environmentId,
1081 "environment.label": target.label,
1082 "environment.target.kind": target._tag,
1083 "connection.connected_ms": connectedForMs,
1084 "connection.failure.reason": outcome.failure.error.reason,
1085 "connection.failure.detail": outcome.failure.error.detail,
1086 },
1087 }),
1088 );
1089 }
1090 return outcome;
1091 }, Effect.ensuring(clearLease));
1092
1093 const waitForRetrySignal = Effect.fnUntraced(function* (delayMs: number) {
1094 // @effect-diagnostics-next-line raceFirstWithSleepToTimeout:off - the sleep is the retry delay (false), not a timeout around the signal loop
1095 return yield* Effect.raceFirst(
1096 Effect.sleep(delayMs).pipe(Effect.as(false)),
1097 Effect.gen(function* () {
1098 for (;;) {
1099 const next = yield* Queue.take(signals);
1100 switch (next._tag) {
1101 case "Wakeup":
1102 return ConnectionWakeups.resetsRetryBackoff(next.reason);
1103 case "ConnectRequested":
1104 case "DisconnectRequested":
1105 case "RetryRequested":
1106 case "NetworkChanged":
1107 return false;
1108 case "BetterRouteAvailable":
1109 break;
1110 }
1111 }
1112 }),
1113 );
1114 });
1115
1116 const waitForSignal = Queue.take(signals).pipe(
1117 Effect.repeat({ while: (next) => next._tag === "BetterRouteAvailable" }),
1118 Effect.map(
1119 (next) => next._tag === "Wakeup" && ConnectionWakeups.resetsRetryBackoff(next.reason),
1120 ),
1121 );
1122
1123 const run = Effect.fnUntraced(function* () {
1124 let failureCount = 0;
1125 // Approval waits count as attempts but not toward backoff, so a later outage starts low.
1126 let backoffFailures = 0;
1127 let approvalWaits = 0;
1128 let generation = 0;
1129 let latestFailure: ConnectionAttemptError | null = null;
1130 let pendingRetry = Option.none<PendingRetryTrace>();
1131 const resetRetryLadder = () => {
1132 failureCount = 0;
1133 backoffFailures = 0;
1134 approvalWaits = 0;
1135 pendingRetry = Option.none();
1136 };
1137 let replacing = false;
1138
1139 for (;;) {
1140 if (yield* Ref.getAndSet(resetRetryState, false)) {
1141 failureCount = 0;
1142 backoffFailures = 0;
1143 approvalWaits = 0;
1144 latestFailure = null;
1145 pendingRetry = Option.none();
1146 }
1147 const currentIntent = yield* Ref.get(intent);
1148 if (!currentIntent.desired) {
1149 resetRetryLadder();
1150 latestFailure = null;
1151 yield* clearLease;
1152 yield* setState(availableState(currentIntent, generation));
1153 yield* waitForSignal;
1154 continue;
1155 }
1156 if (currentIntent.network === "offline" && !replacing) {
1157 yield* clearLease;
1158 yield* setState(offlineState(currentIntent, generation, failureCount + 1, latestFailure));
1159 const applicationActivated = yield* waitForSignal;
1160 if (applicationActivated) {
1161 resetRetryLadder();
1162 }
1163 continue;
1164 }
1165
1166 const attempt = failureCount + 1;
1167 const nextGeneration = generation + 1;
1168 const outcome: AttemptOutcome = yield* Effect.scoped(
1169 runAttempt(attempt, nextGeneration, latestFailure, pendingRetry, replacing),
1170 );
1171 replacing = false;
1172 const failedProbe = yield* Ref.getAndSet(probeUnanswered, false);
1173 if (outcome.established) {
1174 generation = nextGeneration;
1175 // A session came up, so no earlier failure describes the connection.
1176 // Losing a live session is not a failed connection either, for example
1177 // a socket the OS killed while the app was suspended: its replacement
1178 // reports no failure until it fails itself.
1179 latestFailure = null;
1180 if (outcome.stable) {
1181 resetRetryLadder();
1182 }
1183 }
1184 if (outcome._tag === "Interrupted") {
1185 if (outcome.resetRetry) {
1186 resetRetryLadder();
1187 replacing = true;
1188 }
1189 continue;
1190 }
1191
1192 const attemptSpan: Option.Option<Tracer.Span> = outcome.failure.attemptSpan;
1193 const error: ConnectionAttemptError = outcome.failure.error;
1194 if (!outcome.established) {
1195 latestFailure = error;
1196 }
1197 if (error._tag === "ConnectionBlockedError") {
1198 const blockedIntent = yield* Ref.get(intent);
1199 yield* setState({
1200 desired: blockedIntent.desired,
1201 network: blockedIntent.network,
1202 phase: "blocked",
1203 stage: null,
1204 attempt,
1205 generation,
1206 lastFailure: error,
1207 retryAt: null,
1208 });
1209 const applicationActivated = yield* waitForSignal;
1210 if (applicationActivated) {
1211 resetRetryLadder();
1212 }
1213 continue;
1214 }
1215
1216 if (failedProbe) {
1217 resetRetryLadder();
1218 yield* setState(connectingState(yield* Ref.get(intent), generation, 1, latestFailure));
1219 continue;
1220 }
1221
1222 // The first loss of a live session retries almost at once; the ladder
1223 // still counts it, so a host that keeps dropping sessions backs off.
1224 const firstLoss = outcome.established && failureCount === 0;
1225 failureCount += 1;
1226 if (error.reason === "approval-pending") approvalWaits += 1;
1227 const awaitingApproval =
1228 error.reason === "approval-pending" && approvalWaits <= APPROVAL_PENDING_FAST_RETRIES;
1229 if (!awaitingApproval) backoffFailures += 1;
1230 const delayMs = awaitingApproval
1231 ? APPROVAL_PENDING_RETRY_DELAY_MS
1232 : firstLoss
1233 ? Math.round(SESSION_LOSS_RETRY_DELAY_MS * (0.5 + (yield* Random.next) / 2))
1234 : error.reason === "approval-pending"
1235 ? Math.max(
1236 APPROVAL_PENDING_RETRY_DELAY_MS,
1237 retryDelayMs(backoffFailures - 1, yield* Random.next),
1238 )
1239 : retryDelayMs(backoffFailures - 1, yield* Random.next);
1240 pendingRetry = Option.map(attemptSpan, (previousAttempt) => ({
1241 previousAttempt,
1242 failureCount,
1243 delayMs,
1244 reason: error.reason,
1245 }));
1246 const failedIntent = yield* Ref.get(intent);
1247 yield* setState({
1248 desired: failedIntent.desired,
1249 network: failedIntent.network,
1250 phase: "backoff",
1251 stage: null,
1252 attempt,
1253 generation,
1254 lastFailure: latestFailure,
1255 retryAt: (yield* Clock.currentTimeMillis) + delayMs,
1256 });
1257 const applicationActivated = yield* waitForRetrySignal(delayMs);
1258 if (applicationActivated) {
1259 resetRetryLadder();
1260 }
1261 }
1262 });
1263
1264 yield* connectivity.changes.pipe(
1265 Stream.runForEach((network) =>
1266 Ref.modify(intent, (current) => {
1267 const next = targetNetwork(network);
1268 return current.network === next
1269 ? [false, current]
1270 : ([true, { ...current, network: next }] as const);
1271 }).pipe(
1272 Effect.flatMap((changed) =>
1273 changed
1274 ? (network === "offline" ? Effect.void : forgetSilentRoutes).pipe(
1275 Effect.andThen(signal({ _tag: "NetworkChanged", network })),
1276 )
1277 : Effect.void,
1278 ),
1279 ),
1280 ),
1281 Effect.forkScoped,
1282 );
1283 yield* wakeups.changes.pipe(
1284 Stream.runForEach((reason) =>
1285 // A long suspension can hide a network change the platform never reported.
1286 (reason === "network-changed" || reason === "application-active-long"
1287 ? forgetSilentRoutes
1288 : Effect.void
1289 ).pipe(Effect.andThen(signal({ _tag: "Wakeup", reason }))),
1290 ),
1291 Effect.forkScoped,
1292 );
1293 yield* Queue.take(betterRouteChecks).pipe(
1294 Effect.flatMap(checkBetterRoutes),
1295 Effect.forever,
1296 Effect.forkScoped,
1297 );
1298 yield* run().pipe(Effect.forkScoped);
1299
1300 const connect = Ref.update(intent, (current) => ({
1301 ...current,
1302 desired: true,
1303 })).pipe(
1304 Effect.andThen(signal({ _tag: "ConnectRequested" })),
1305 Effect.withSpan("EnvironmentSupervisor.connect"),
1306 );
1307
1308 const disconnect = Ref.update(intent, (current) => ({
1309 ...current,
1310 desired: false,
1311 })).pipe(
1312 Effect.andThen(signal({ _tag: "DisconnectRequested" })),
1313 Effect.withSpan("EnvironmentSupervisor.disconnect"),
1314 );
1315
1316 const retryNow = Ref.set(resetRetryState, true).pipe(
1317 Effect.andThen(signal({ _tag: "RetryRequested" })),
1318 Effect.withSpan("EnvironmentSupervisor.retryNow"),
1319 );
1320
1321 yield* Effect.addFinalizer(() => Queue.shutdown(signals).pipe(Effect.andThen(clearLease)));
1322
1323 return EnvironmentSupervisor.of({
1324 target,
1325 state,
1326 session,
1327 prepared,
1328 connect,
1329 disconnect,
1330 retryNow,
1331 });
1332});