fix(mobile): probe on network path changes, report leases on reconnect
Rebuilt on main after #5561 and #5404 landed overlapping reconnect work. What main already covers is dropped from this branch: the backoff ladder rework replaces our jitter, wakeProbeFailed replaces our probe-failure fast path, and the authoritative-session guard replaces our shell warm-cache short-circuit. What remains is the mobile-specific delta: - New advisory `network-path-changed` wakeup: WiFi<->cellular keeps isConnected true while invalidating the socket's path, so the mobile adapter emits a wakeup on interface-type changes while active and the supervisor probes the session (3s bound) instead of waiting for the ping timeout. A failed probe rides main's wakeProbeFailed fast path; flapping interfaces cannot cut backoff delays short. - Client activity is re-reported on every newly connected session generation; the AppState-triggered report races the reconnect and is dropped, leaving provider/VCS work paused server-side for up to 25s after a resume. Generation dedup is per-supervisor since replacements restart the counter. - The RPC onPingTimeout hook is wired to logging so zombie-socket disconnects are distinguishable from ordinary closes. - Server websocket idleTimeout drops to 30s from Bun's 120s default (clients ping every 5s, so live connections never idle), releasing a suspended phone's half-dead socket and buffers four times sooner. Co-Authored-By: Claude Fable 5 <[email protected]> Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
d440442db6
commit
b603bacfd0
7 files changed
+193
-12
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentRpcSubscriptionObserver, request } from "@t3tools/client-runtime/rpc";
|
||||
import {
|
||||
type BackgroundScope,
|
||||
@@ -103,6 +103,40 @@ export const mobileBackgroundActivityReporterLayer = Layer.effectDiscard(
|
||||
Stream.runForEach(() => Effect.sync(requestReport)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
// Re-report on every newly connected session generation. The AppState
|
||||
// report races the reconnect (the RPC fails while the socket is down and
|
||||
// is ignored), so without this the server's lease can lag a resume by up
|
||||
// to REPORT_INTERVAL_MS, keeping provider/VCS work paused. The generation
|
||||
// dedup lives inside the per-supervisor stream because a replacement
|
||||
// supervisor restarts generations; switchMap (default concurrency)
|
||||
// interrupts the previous subscription set on environment changes.
|
||||
const connectedGenerations = (environmentId: EnvironmentId) =>
|
||||
registry.followStream(
|
||||
environmentId,
|
||||
Stream.unwrap(
|
||||
Effect.map(EnvironmentSupervisor, (supervisor) =>
|
||||
SubscriptionRef.changes(supervisor.state).pipe(
|
||||
Stream.filter((state) => state.phase === "connected"),
|
||||
Stream.map((state) => state.generation),
|
||||
Stream.changes,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* Stream.concat(
|
||||
Stream.fromEffect(SubscriptionRef.get(registry.entries)),
|
||||
SubscriptionRef.changes(registry.entries),
|
||||
).pipe(
|
||||
Stream.map((entries) => [...entries.keys()].sort()),
|
||||
Stream.changesWith((a, b) => a.length === b.length && a.every((id, i) => id === b[i])),
|
||||
Stream.switchMap((environmentIds) =>
|
||||
Stream.mergeAll(environmentIds.map(connectedGenerations), {
|
||||
concurrency: "unbounded",
|
||||
}),
|
||||
),
|
||||
Stream.runForEach(() => Effect.sync(requestReport)),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
yield* Stream.fromQueue(reportRequests).pipe(
|
||||
Stream.debounce("250 millis"),
|
||||
Stream.runForEach(() => report),
|
||||
|
||||
@@ -87,11 +87,13 @@ const connectivityLayer = Connectivity.layer({
|
||||
|
||||
const wakeupsLayer = Wakeups.layer({
|
||||
changes: Stream.merge(
|
||||
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
|
||||
Stream.callback<
|
||||
"application-active-probe" | "application-active-reconnect" | "network-path-changed"
|
||||
>((queue) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
|
||||
return AppState.addEventListener("change", (state) => {
|
||||
const appStateSubscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "background") {
|
||||
backgroundedAtMs = Date.now();
|
||||
return;
|
||||
@@ -101,6 +103,39 @@ const wakeupsLayer = Wakeups.layer({
|
||||
backgroundedAtMs = null;
|
||||
}
|
||||
});
|
||||
// WiFi <-> cellular keeps isConnected true while invalidating the
|
||||
// socket's path, so the coarse online/offline signal never fires.
|
||||
// Emit an advisory wakeup on interface-type changes while active;
|
||||
// the supervisor probes the session rather than blindly replacing
|
||||
// it, which keeps flapping paths cheap. Seed the current type so
|
||||
// the first flip after startup is detected; the listener only
|
||||
// reports changes.
|
||||
let networkType: string | null = null;
|
||||
void Network.getNetworkStateAsync()
|
||||
.then((current) => {
|
||||
networkType ??= current.type ?? null;
|
||||
})
|
||||
.catch(() => undefined);
|
||||
const networkSubscription = Network.addNetworkStateListener((state) => {
|
||||
const nextType = state.type ?? null;
|
||||
const previousType = networkType;
|
||||
networkType = nextType;
|
||||
if (
|
||||
previousType !== null &&
|
||||
nextType !== null &&
|
||||
nextType !== previousType &&
|
||||
state.isConnected === true &&
|
||||
AppState.currentState === "active"
|
||||
) {
|
||||
Queue.offerUnsafe(queue, "network-path-changed");
|
||||
}
|
||||
});
|
||||
return {
|
||||
remove: () => {
|
||||
appStateSubscription.remove();
|
||||
networkSubscription.remove();
|
||||
},
|
||||
};
|
||||
}),
|
||||
(subscription) => Effect.sync(() => subscription.remove()),
|
||||
).pipe(Effect.asVoid),
|
||||
|
||||
@@ -198,6 +198,12 @@ const HttpServerLive = Layer.unwrap(
|
||||
compress: "dedicated",
|
||||
decompress: "shared",
|
||||
},
|
||||
// Reap connections that stop sending within 30s instead of Bun's
|
||||
// 120s default. RPC clients ping every 5s, so a live client never
|
||||
// idles; a suspended mobile app stops pinging and its half-dead
|
||||
// socket (plus the server-side buffers feeding it) is released
|
||||
// four times sooner.
|
||||
idleTimeout: 30,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -873,6 +873,84 @@ describe("EnvironmentSupervisor", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("probes the active session when the network path changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const probeCount = yield* Ref.make(0);
|
||||
const probeCalled = yield* Deferred.make<void>();
|
||||
const harness = yield* makeHarness({
|
||||
probe: () =>
|
||||
Ref.update(probeCount, (count) => count + 1).pipe(
|
||||
Effect.andThen(Deferred.succeed(probeCalled, undefined)),
|
||||
),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
yield* harness.wake("network-path-changed");
|
||||
yield* Deferred.await(probeCalled);
|
||||
|
||||
expect(yield* Ref.get(probeCount)).toBe(1);
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(0);
|
||||
expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("connected");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reconnects without backoff when a probe after a path change fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
probe: (attempt) =>
|
||||
attempt === 1
|
||||
? Effect.fail(transient("The path changed under the socket."))
|
||||
: Effect.void,
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
|
||||
yield* harness.wake("network-path-changed");
|
||||
// The failed wake probe skips the first backoff rung (wakeProbeFailed),
|
||||
// so the replacement connects without a TestClock advance.
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "connected" && state.generation === 2,
|
||||
);
|
||||
|
||||
expect(yield* Ref.get(harness.sessionCount)).toBe(2);
|
||||
expect(yield* Ref.get(harness.releaseCount)).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not cut backoff short when the network path flaps", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
prepare: () => Effect.fail(transient()),
|
||||
});
|
||||
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
|
||||
initiallyDesired: true,
|
||||
}).pipe(Effect.provide(harness.dependencies));
|
||||
|
||||
yield* awaitState(
|
||||
supervisor.state,
|
||||
(state) => state.phase === "backoff" && state.attempt === 1,
|
||||
);
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
|
||||
|
||||
// Advisory path-change wakeups have no session to probe during backoff
|
||||
// and must not trigger an early retry.
|
||||
yield* harness.wake("network-path-changed");
|
||||
yield* harness.wake("network-path-changed");
|
||||
for (let attempt = 0; attempt < 20; attempt += 1) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
|
||||
expect((yield* SubscriptionRef.get(supervisor.state)).phase).toBe("backoff");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("immediately replaces a mobile session after a long background resume", () =>
|
||||
Effect.gen(function* () {
|
||||
const probeCount = yield* Ref.make(0);
|
||||
|
||||
@@ -418,13 +418,17 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
// replaces that lease and starts a fresh attempt without backoff.
|
||||
return true;
|
||||
}
|
||||
if (next.reason === "application-active" || next.reason === "application-active-probe") {
|
||||
if (
|
||||
next.reason === "application-active" ||
|
||||
next.reason === "application-active-probe" ||
|
||||
next.reason === "network-path-changed"
|
||||
) {
|
||||
const probe = yield* lease.session.probe.pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration:
|
||||
next.reason === "application-active-probe"
|
||||
? MOBILE_CONNECTION_PROBE_TIMEOUT
|
||||
: CONNECTION_PROBE_TIMEOUT,
|
||||
next.reason === "application-active"
|
||||
? CONNECTION_PROBE_TIMEOUT
|
||||
: MOBILE_CONNECTION_PROBE_TIMEOUT,
|
||||
orElse: () =>
|
||||
Effect.fail(
|
||||
new ConnectionTransientError({
|
||||
@@ -622,6 +626,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
const next = yield* Queue.take(signals);
|
||||
switch (next._tag) {
|
||||
case "Wakeup":
|
||||
// Path-change wakeups are advisory (probe a connected session)
|
||||
// and must not cut backoff delays short on a flapping interface.
|
||||
if (next.reason === "network-path-changed") {
|
||||
break;
|
||||
}
|
||||
return ConnectionWakeups.isApplicationActiveWakeup(next.reason);
|
||||
case "ConnectRequested":
|
||||
case "DisconnectRequested":
|
||||
@@ -634,11 +643,16 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
|
||||
);
|
||||
});
|
||||
|
||||
const waitForSignal = Queue.take(signals).pipe(
|
||||
Effect.map(
|
||||
(next) => next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason),
|
||||
),
|
||||
);
|
||||
const waitForSignal = Effect.gen(function* () {
|
||||
for (;;) {
|
||||
const next = yield* Queue.take(signals);
|
||||
if (next._tag === "Wakeup" && next.reason === "network-path-changed") {
|
||||
// Advisory only; see waitForRetrySignal.
|
||||
continue;
|
||||
}
|
||||
return next._tag === "Wakeup" && ConnectionWakeups.isApplicationActiveWakeup(next.reason);
|
||||
}
|
||||
});
|
||||
|
||||
const run = Effect.fnUntraced(function* () {
|
||||
let failureCount = 0;
|
||||
|
||||
@@ -6,6 +6,12 @@ export type ConnectionWakeup =
|
||||
| "application-active"
|
||||
| "application-active-probe"
|
||||
| "application-active-reconnect"
|
||||
// Advisory: the network path changed shape (e.g. WiFi to cellular) while
|
||||
// still nominally online. The old socket often survives in appearance only,
|
||||
// so the supervisor probes it instead of waiting for a ping timeout. It is
|
||||
// ignored outside the connected state: a flapping interface must not cut
|
||||
// backoff delays short.
|
||||
| "network-path-changed"
|
||||
| "credentials-changed";
|
||||
|
||||
export function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
|
||||
|
||||
@@ -91,6 +91,14 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.asVoid,
|
||||
),
|
||||
// Distinguishes zombie-socket disconnects (missed pong after suspension
|
||||
// or a silent path change) from ordinary closes in logs and telemetry.
|
||||
onPingTimeout: Effect.logInfo("Connection ping timed out; treating the socket as dead.").pipe(
|
||||
Effect.annotateLogs({
|
||||
environmentId: connection.environmentId,
|
||||
connectionLabel: connection.label,
|
||||
}),
|
||||
),
|
||||
});
|
||||
const socketLayer = Socket.layerWebSocket(connection.socketUrl, {
|
||||
openTimeout: SOCKET_OPEN_TIMEOUT,
|
||||
|
||||
Reference in new issue
Block a user