TypeScript
fix(client): dead connection routes are probed 30x less often (#27101)
Julius Marminge65b0ab8c91c1
diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.tsindex 0fd08c63364..2cdf012187e 100644--- a/packages/client-runtime/src/connection/driver.ts+++ b/packages/client-runtime/src/connection/driver.ts@@ -40,6 +40,8 @@ export interface EnvironmentConnectionLease {}export type RouteCheck = "answered" | "silent" | "unchecked";+/** "unprepared" means the route answered its check but could not be prepared. */+export type RoutePreflight = "ready" | "unprepared" | "silent" | "unchecked";const ROUTE_CHECK_TIMEOUT_MS = 2_500;// Preferred direct routes share one head start, so a relay connection does not@@ -57,7 +59,7 @@ export class ConnectionDriver extends Context.Service<readonly preflight: (entry: ConnectionCatalogEntry,route: ConnectionRoute,- ) => Effect.Effect<boolean>;+ ) => Effect.Effect<RoutePreflight>;/** Asks the host behind a live session to answer a fresh request on the session's own origin. */readonly checkHost: (prepared: PreparedConnection) => Effect.Effect<RouteCheck>;}@@ -204,13 +206,13 @@ export const make = Effect.gen(function* () {? Effect.succeed("silent" as const): checkRoute(entry, route)).pipe(- Effect.flatMap((check) =>- check === "answered"- ? resolver.prepare(routeEntry(entry, route)).pipe(- Effect.as(true),- Effect.orElseSucceed(() => false),- )- : Effect.succeed(false),+ Effect.filterOrElse(+ (check): check is Exclude<RouteCheck, "answered"> => check !== "answered",+ () =>+ resolver.prepare(routeEntry(entry, route)).pipe(+ Effect.as<RoutePreflight>("ready"),+ Effect.orElseSucceed((): RoutePreflight => "unprepared"),+ ),),Effect.withSpan("ConnectionDriver.preflight"),);diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.tsindex c99e950200b..ec8863949ce 100644--- a/packages/client-runtime/src/connection/registry.test.ts+++ b/packages/client-runtime/src/connection/registry.test.ts@@ -431,7 +431,11 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (),),preflight: (_entry, route) =>- checkRoute(route).pipe(Effect.map((check) => check === "answered")),+ checkRoute(route).pipe(+ Effect.map((check): ConnectionDriver.RoutePreflight =>+ check === "answered" ? "ready" : check,+ ),+ ),checkHost: () => Effect.succeed<ConnectionDriver.RouteCheck>("unchecked"),});diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.tsindex 347bde9cc44..66d151043b1 100644--- a/packages/client-runtime/src/connection/supervisor.test.ts+++ b/packages/client-runtime/src/connection/supervisor.test.ts@@ -148,6 +148,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:readonly initialConfig?: (attempt: number) => Effect.Effect<ServerConfig, ConnectionAttemptError>;readonly checkRoute?: (route: ConnectionRoute) => Effect.Effect<ConnectionDriver.RouteCheck>;readonly checkHost?: (prepared: PreparedConnection) => Effect.Effect<ConnectionDriver.RouteCheck>;+ readonly preflight?: (route: ConnectionRoute) => Effect.Effect<ConnectionDriver.RoutePreflight>;readonly inboundFrames?: Effect.Effect<number>;}) {const networkStatus = yield* SubscriptionRef.make<NetworkStatus>(@@ -244,7 +245,12 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:ConnectionDriver.ConnectionDriver.of({connect,preflight: (_entry, route) =>- checkRoute(route).pipe(Effect.map((check) => check === "answered")),+ options?.preflight?.(route) ??+ checkRoute(route).pipe(+ Effect.map((check): ConnectionDriver.RoutePreflight =>+ check === "answered" ? "ready" : check,+ ),+ ),checkHost: (prepared) =>options?.checkHost?.(prepared) ??Effect.succeed<ConnectionDriver.RouteCheck>("unchecked"),@@ -1614,6 +1620,133 @@ describe("EnvironmentSupervisor routes", () => {}),);+ it.effect("checks a dead LAN route less often until the network changes", () =>+ Effect.gen(function* () {+ const lanReachable = yield* Ref.make(false);+ const lanChecks = yield* Ref.make(0);+ const harness = yield* makeHarness({+ checkRoute: (route) =>+ route.target._tag === "BearerConnectionTarget"+ ? Ref.update(lanChecks, (count) => count + 1).pipe(+ Effect.andThen(Ref.get(lanReachable)),+ Effect.map((reachable) => (reachable ? "answered" : "silent")),+ )+ : Effect.succeed("unchecked"),+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),+ });+ const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {+ initiallyDesired: true,+ }).pipe(Effect.provide(harness.dependencies));++ yield* awaitState(+ supervisor.state,+ (state) => state.phase === "connected" && state.generation === 1,+ );+ yield* Ref.set(lanChecks, 0);++ // Checked at 1, 3 and 7 minutes instead of every minute.+ for (let minute = 0; minute < 10; minute += 1) {+ yield* TestClock.adjust("60 seconds");+ }+ expect(yield* Ref.get(lanChecks)).toBe(3);++ yield* Ref.set(lanReachable, true);+ yield* harness.wake("network-changed");+ yield* awaitState(+ supervisor.state,+ (state) => state.phase === "connected" && state.generation === 2,+ );+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(+ "BearerConnectionTarget",+ );+ }),+ );++ it.effect("keeps checking a LAN route every minute when it answers but cannot be prepared", () =>+ Effect.gen(function* () {+ const lanPreflights = yield* Ref.make(0);+ const harness = yield* makeHarness({+ checkRoute: (route) =>+ Effect.succeed(route.target._tag === "BearerConnectionTarget" ? "silent" : "unchecked"),+ preflight: (route) =>+ route.target._tag === "BearerConnectionTarget"+ ? Ref.update(lanPreflights, (count) => count + 1).pipe(Effect.as("unprepared" as const))+ : Effect.succeed("unchecked"),+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),+ });+ const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {+ initiallyDesired: true,+ }).pipe(Effect.provide(harness.dependencies));++ yield* awaitState(+ supervisor.state,+ (state) => state.phase === "connected" && state.generation === 1,+ );+ for (let minute = 0; minute < 10; minute += 1) {+ yield* TestClock.adjust("60 seconds");+ }+ expect(yield* Ref.get(lanPreflights)).toBe(10);+ }),+ );++ it.effect("ignores a dead LAN check that was running when the network changed", () =>+ Effect.gen(function* () {+ const lanChecks = yield* Ref.make(0);+ const checkStarted = yield* Deferred.make<void>();+ const finishCheck = yield* Deferred.make<void>();+ const woke = yield* Ref.make(false);+ const wakeupHandled = yield* Deferred.make<void>();+ const harness = yield* makeHarness({+ checkRoute: (route) =>+ route.target._tag === "BearerConnectionTarget"+ ? Ref.updateAndGet(lanChecks, (count) => count + 1).pipe(+ Effect.flatMap((check) =>+ check === 1+ ? Effect.succeed("silent" as const)+ : check === 2+ ? Deferred.succeed(checkStarted, undefined).pipe(+ Effect.andThen(Deferred.await(finishCheck)),+ Effect.as("silent" as const),+ )+ : Effect.succeed("answered" as const),+ ),+ )+ : Effect.succeed("unchecked"),+ prepare: (_attempt, target) => Effect.succeed(preparedFor(target)),+ // The wakeup probes the session only after it forgets the silent routes.+ probe: () =>+ Ref.get(woke).pipe(+ Effect.flatMap((afterWake) =>+ afterWake ? Deferred.succeed(wakeupHandled, undefined) : Effect.void,+ ),+ Effect.asVoid,+ ),+ });+ const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, {+ initiallyDesired: true,+ }).pipe(Effect.provide(harness.dependencies));++ yield* awaitState(+ supervisor.state,+ (state) => state.phase === "connected" && state.generation === 1,+ );+ yield* TestClock.adjust("60 seconds");+ yield* Deferred.await(checkStarted);+ yield* Ref.set(woke, true);+ yield* harness.wake("network-changed");+ yield* Deferred.await(wakeupHandled);+ yield* Deferred.succeed(finishCheck, undefined);++ yield* awaitState(+ supervisor.state,+ (state) => state.phase === "connected" && state.generation === 2,+ );+ expect(Option.getOrThrow(yield* SubscriptionRef.get(supervisor.prepared)).target._tag).toBe(+ "BearerConnectionTarget",+ );+ }),+ );+it.effect("moves off a dead LAN socket when the phone switches to cellular", () =>Effect.gen(function* () {const lanReachable = yield* Ref.make(true);diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.tsindex ce7632df0f5..21238192196 100644--- a/packages/client-runtime/src/connection/supervisor.ts+++ b/packages/client-runtime/src/connection/supervisor.ts@@ -58,7 +58,11 @@ const SILENT_SOCKET_RECHECK_EVERY = "1 second";// instead of timing out.const REMOTE_SILENT_SOCKET_AFTER = "2500 millis";const BACKOFF_RESET_AFTER_MS = 30_000;-const BETTER_ROUTE_CHECK_INTERVAL = "60 seconds";+const BETTER_ROUTE_CHECK_INTERVAL_MS = 60_000;+// Each check of a dead route can wait out the full probe timeout, so a route+// that keeps failing is checked half as often each time, until the network+// changes and it may answer again.+const SILENT_ROUTE_BACKOFF_MAX_MS = 1_800_000;// A better route that answered the check but then failed to connect is not// tried again for this long, so a flaky LAN cannot bounce the connection.const BETTER_ROUTE_COOLDOWN_MS = 300_000;@@ -139,6 +143,20 @@ function retryDelayMs(failureCount: number, random: number): number {return Math.round(ceiling / 2 + (ceiling / 2) * random);}+interface SilentRoute {+ readonly failures: number;+ readonly until: bigint;+}++function backOffSilentRoute(previous: SilentRoute | undefined, now: bigint): SilentRoute {+ const failures = (previous?.failures ?? 0) + 1;+ const delayMs = Math.min(+ SILENT_ROUTE_BACKOFF_MAX_MS,+ BETTER_ROUTE_CHECK_INTERVAL_MS * 2 ** failures,+ );+ return { failures, until: now + BigInt(delayMs) * 1_000_000n };+}+function annotateTarget(target: ConnectionTarget) {return Effect.annotateCurrentSpan({"environment.id": target.environmentId,@@ -288,6 +306,16 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (const currentRoutes = Ref.get(currentEntry).pipe(Effect.map(connectionRoutes));const preferredRouteId = yield* Ref.make(Option.none<string>());const routeCooldowns = yield* Ref.make<ReadonlyMap<string, bigint>>(new Map());+ // The generation keeps a check that started before a reset from recording+ // its stale failures after it.+ const silentRoutes = yield* Ref.make({+ generation: 0,+ routes: new Map<string, SilentRoute>() as ReadonlyMap<string, SilentRoute>,+ });+ const forgetSilentRoutes = Ref.update(silentRoutes, ({ generation }) => ({+ generation: generation + 1,+ routes: new Map(),+ }));const attemptEntry = Effect.gen(function* () {const latest = yield* Ref.get(currentEntry);@@ -338,15 +366,29 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (if (current <= 0) return;const now = yield* Clock.monotonicTimeNanos;const cooldowns = yield* Ref.get(routeCooldowns);+ const silent = yield* Ref.get(silentRoutes);const better = connectionRoutes(latest).slice(0, current)- .filter((route) => (cooldowns.get(connectionRouteId(route.target)) ?? 0n) <= now);- const passed = yield* Effect.forEach(+ .filter((route) => {+ const id = connectionRouteId(route.target);+ return (cooldowns.get(id) ?? 0n) <= now && (silent.routes.get(id)?.until ?? 0n) <= now;+ });+ const results = yield* Effect.forEach(better,(route: ConnectionRoute) => driver.preflight(latest, route),{ concurrency: "unbounded" },);- const index = passed.indexOf(true);+ yield* Ref.update(silentRoutes, (previous) => {+ if (previous.generation !== silent.generation) return previous;+ const routes = new Map(previous.routes);+ for (const [position, route] of better.entries()) {+ const id = connectionRouteId(route.target);+ if (results[position] !== "silent") routes.delete(id);+ else routes.set(id, backOffSilentRoute(previous.routes.get(id), now));+ }+ return { generation: previous.generation, routes };+ });+ const index = results.indexOf("ready");if (index === -1) return;const live = yield* SubscriptionRef.get(session);if (Option.isNone(live) || live.value !== lease.session) return;@@ -668,7 +710,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ();// Ticks always run: the check skips the preferred route itself, and the// route list can grow while connected (learned routes).- yield* Stream.tick(BETTER_ROUTE_CHECK_INTERVAL).pipe(+ yield* Stream.tick(Duration.millis(BETTER_ROUTE_CHECK_INTERVAL_MS)).pipe(Stream.drop(1),Stream.runForEach(() => requestBetterRouteCheck(lease)),Effect.forkScoped,@@ -1114,14 +1156,24 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (current.network === network ? [false, current] : ([true, { ...current, network }] as const),).pipe(Effect.flatMap((changed) =>- changed ? signal({ _tag: "NetworkChanged", network }) : Effect.void,+ changed+ ? (network === "offline" ? Effect.void : forgetSilentRoutes).pipe(+ Effect.andThen(signal({ _tag: "NetworkChanged", network })),+ )+ : Effect.void,),),),Effect.forkScoped,);yield* wakeups.changes.pipe(- Stream.runForEach((reason) => signal({ _tag: "Wakeup", reason })),+ Stream.runForEach((reason) =>+ // A long suspension can hide a network change the platform never reported.+ (reason === "network-changed" || reason === "application-active-long"+ ? forgetSilentRoutes+ : Effect.void+ ).pipe(Effect.andThen(signal({ _tag: "Wakeup", reason }))),+ ),Effect.forkScoped,);yield* Queue.take(betterRouteChecks).pipe(