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

supervisor.ts

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