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

supervisor.ts

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