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

supervisor.ts

1,343 lines49.4 KB

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