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

supervisor.ts

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