Skip to content

Commit 8fa1088

Browse files
t3dotggclaude
andcommitted
perf(mobile): speed up multi-environment reconnect on foreground
Three serialization points made reconnecting to several environments feel sequential even though the supervisor fan-out is parallel: - The foreground liveness probe waited 15s on half-open sockets before starting a reconnect. It now times out after 5s. - Remote DPoP tokens lived inside the single connection-catalog SecureStore document, so every environment's token read/write serialized on one semaphore and rewrote the whole catalog to the Keychain. Tokens now live under per-environment keys with an in-memory cache and lazy migration. - The relay access-token cache held its lock across the network token exchange, so cache hits queued behind a stale account's round trip. Cache hits now take a lock-free fast path. Also reset the retry backoff ladder on application-active, since network conditions usually changed while backgrounded. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent a8e05cb commit 8fa1088

9 files changed

Lines changed: 542 additions & 50 deletions

File tree

‎apps/mobile/src/connection/catalog-store.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ const encodeCatalog = Effect.fn("mobile.connectionStorage.encodeCatalog")(functi
4141
);
4242
});
4343

44-
interface CatalogStore {
44+
export interface CatalogStore {
4545
readonly read: Effect.Effect<ConnectionCatalogDocumentType, ConnectionTransientError>;
4646
readonly update: (
4747
transform: (catalog: ConnectionCatalogDocumentType) => ConnectionCatalogDocumentType,

‎apps/mobile/src/connection/storage.ts‎

Lines changed: 16 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
} from "@t3tools/client-runtime/platform";
1010
import { TokenStore } from "@t3tools/client-runtime/authorization";
1111
import {
12-
ConnectionTransientError,
12+
type ConnectionAttemptError,
1313
CredentialStore,
1414
ProfileStore,
1515
} from "@t3tools/client-runtime/connection";
@@ -18,10 +18,11 @@ import * as Effect from "effect/Effect";
1818
import * as Layer from "effect/Layer";
1919
import * as Option from "effect/Option";
2020
import * as CatalogStore from "./catalog-store";
21+
import * as RemoteDpopTokenStore from "./token-store";
2122

2223
function targetPersistenceError(
2324
operation: "list-targets" | "register-connection" | "remove-connection",
24-
error: ConnectionTransientError,
25+
error: ConnectionAttemptError,
2526
) {
2627
return new ConnectionPersistenceError({
2728
operation,
@@ -32,6 +33,9 @@ function targetPersistenceError(
3233
export const connectionStorageLayer = Layer.effectContext(
3334
Effect.gen(function* () {
3435
const catalog = yield* CatalogStore.make();
36+
// Tokens live outside the catalog document so reconnecting environments
37+
// do not serialize on the catalog lock. See token-store.ts.
38+
const remoteTokenStore = yield* RemoteDpopTokenStore.make(catalog);
3539

3640
const targetStore = ConnectionTargetStore.of({
3741
list: catalog.read.pipe(
@@ -44,10 +48,17 @@ export const connectionStorageLayer = Layer.effectContext(
4448
catalog
4549
.update((document) => registerConnectionInCatalog(document, registration))
4650
.pipe(Effect.mapError((error) => targetPersistenceError("register-connection", error))),
51+
// The token key is deleted before the catalog entry: if the keychain
52+
// delete fails the registration survives and the removal can be retried,
53+
// instead of leaving an orphaned token that a re-added environment
54+
// would pick back up.
4755
remove: (target) =>
48-
catalog
49-
.update((document) => removeConnectionFromCatalog(document, target))
50-
.pipe(Effect.mapError((error) => targetPersistenceError("remove-connection", error))),
56+
remoteTokenStore.remove(target.environmentId).pipe(
57+
Effect.andThen(
58+
catalog.update((document) => removeConnectionFromCatalog(document, target)),
59+
),
60+
Effect.mapError((error) => targetPersistenceError("remove-connection", error)),
61+
),
5162
});
5263
const profileStore = ProfileStore.make({
5364
get: (connectionId) =>
@@ -100,34 +111,6 @@ export const connectionStorageLayer = Layer.effectContext(
100111
),
101112
})),
102113
});
103-
const remoteTokenStore = TokenStore.make({
104-
get: (environmentId) =>
105-
catalog.read.pipe(
106-
Effect.map((document) =>
107-
Option.fromUndefinedOr(
108-
document.remoteDpopTokens.find((token) => token.environmentId === environmentId),
109-
),
110-
),
111-
),
112-
put: (token) =>
113-
catalog.update((document) => ({
114-
...document,
115-
remoteDpopTokens: replaceCatalogValue(
116-
document.remoteDpopTokens,
117-
(value) => value.environmentId,
118-
token,
119-
),
120-
})),
121-
remove: (environmentId) =>
122-
catalog.update((document) => ({
123-
...document,
124-
remoteDpopTokens: removeCatalogValue(
125-
document.remoteDpopTokens,
126-
(value) => value.environmentId,
127-
environmentId,
128-
),
129-
})),
130-
});
131114
return Context.make(ConnectionTargetStore, targetStore).pipe(
132115
Context.add(ConnectionRegistrationStore, registrationStore),
133116
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import { TokenStore } from "@t3tools/client-runtime/authorization";
2+
import { EnvironmentId } from "@t3tools/contracts";
3+
import { describe, expect, it } from "@effect/vitest";
4+
import * as Deferred from "effect/Deferred";
5+
import * as Effect from "effect/Effect";
6+
import * as Encoding from "effect/Encoding";
7+
import * as Fiber from "effect/Fiber";
8+
import * as Option from "effect/Option";
9+
import * as Schema from "effect/Schema";
10+
import { vi } from "vite-plus/test";
11+
12+
vi.mock("react-native", () => ({
13+
Platform: { OS: "ios" },
14+
}));
15+
16+
vi.mock("expo-secure-store", () => ({
17+
deleteItemAsync: vi.fn(),
18+
getItemAsync: vi.fn(),
19+
setItemAsync: vi.fn(),
20+
}));
21+
22+
import * as CatalogStore from "./catalog-store";
23+
import { REMOTE_DPOP_TOKEN_KEY_PREFIX, make } from "./token-store";
24+
import { MobileSecureStorage } from "../persistence/mobile-secure-storage";
25+
26+
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
27+
28+
const TOKEN = new TokenStore.RemoteDpopAccessToken({
29+
environmentId: ENVIRONMENT_ID,
30+
label: "Remote",
31+
endpoint: {
32+
httpBaseUrl: "https://remote.example.test",
33+
wsBaseUrl: "wss://remote.example.test",
34+
providerKind: "cloudflare_tunnel",
35+
},
36+
accessToken: "dpop-token",
37+
expiresAtEpochMs: 1_000_000,
38+
dpopThumbprint: "thumbprint",
39+
});
40+
41+
const TOKEN_KEY = `${REMOTE_DPOP_TOKEN_KEY_PREFIX}${Encoding.encodeBase64Url(ENVIRONMENT_ID)}`;
42+
43+
const encodeToken = Schema.encodeSync(TokenStore.RemoteDpopAccessToken);
44+
45+
function makeStorage(initial: Readonly<Record<string, string>> = {}) {
46+
const values = new Map(Object.entries(initial));
47+
const writes: Array<string> = [];
48+
const storage = MobileSecureStorage.of({
49+
getItem: (key) => Effect.sync(() => values.get(key) ?? null),
50+
setItem: (key, value) =>
51+
Effect.sync(() => {
52+
writes.push(key);
53+
values.set(key, value);
54+
}),
55+
removeItem: (key) =>
56+
Effect.sync(() => {
57+
values.delete(key);
58+
}),
59+
});
60+
return { storage, values, writes };
61+
}
62+
63+
const makeStores = Effect.fn("makeStores")(function* (storage: MobileSecureStorage["Service"]) {
64+
const catalog = yield* CatalogStore.make().pipe(
65+
Effect.provideService(MobileSecureStorage, storage),
66+
);
67+
const tokens = yield* make(catalog).pipe(Effect.provideService(MobileSecureStorage, storage));
68+
return { catalog, tokens };
69+
});
70+
71+
describe("mobile remote DPoP token store", () => {
72+
it.effect("stores each token under its own key without touching the catalog", () =>
73+
Effect.gen(function* () {
74+
const memory = makeStorage();
75+
const { catalog, tokens } = yield* makeStores(memory.storage);
76+
77+
yield* tokens.put(TOKEN);
78+
expect(memory.values.has(TOKEN_KEY)).toBe(true);
79+
expect((yield* catalog.read).remoteDpopTokens).toEqual([]);
80+
81+
const loaded = yield* tokens.get(ENVIRONMENT_ID);
82+
expect(Option.getOrThrow(loaded)).toMatchObject({ accessToken: "dpop-token" });
83+
84+
yield* tokens.remove(ENVIRONMENT_ID);
85+
expect(memory.values.has(TOKEN_KEY)).toBe(false);
86+
expect(Option.isNone(yield* tokens.get(ENVIRONMENT_ID))).toBe(true);
87+
}),
88+
);
89+
90+
it.effect("serves repeat reads from memory without re-reading the keychain", () =>
91+
Effect.gen(function* () {
92+
const memory = makeStorage();
93+
const { tokens } = yield* makeStores(memory.storage);
94+
95+
yield* tokens.put(TOKEN);
96+
// Corrupt the persisted copy: a cached read must not notice.
97+
memory.values.set(TOKEN_KEY, "{not-json");
98+
const loaded = yield* tokens.get(ENVIRONMENT_ID);
99+
expect(Option.getOrThrow(loaded).accessToken).toBe("dpop-token");
100+
}),
101+
);
102+
103+
it.effect("migrates a token persisted inside the catalog document to its own key", () =>
104+
Effect.gen(function* () {
105+
const memory = makeStorage();
106+
const { catalog, tokens } = yield* makeStores(memory.storage);
107+
yield* catalog.update((document) => ({
108+
...document,
109+
remoteDpopTokens: [TOKEN],
110+
}));
111+
112+
const loaded = yield* tokens.get(ENVIRONMENT_ID);
113+
expect(Option.getOrThrow(loaded)).toMatchObject({ accessToken: "dpop-token" });
114+
expect(memory.values.has(TOKEN_KEY)).toBe(true);
115+
expect((yield* catalog.read).remoteDpopTokens).toEqual([]);
116+
}),
117+
);
118+
119+
it.effect("does not resurrect a token removed while a cold read is in flight", () =>
120+
Effect.gen(function* () {
121+
const readGate = yield* Deferred.make<void>();
122+
const readStarted = yield* Deferred.make<void>();
123+
const memory = makeStorage();
124+
// getItem captures the stored value immediately (like a real Keychain
125+
// read that already completed) but only delivers it after the gate, so
126+
// the remove can run while the read is in flight.
127+
const gatedStorage = MobileSecureStorage.of({
128+
getItem: (key) =>
129+
key === TOKEN_KEY
130+
? Effect.sync(() => memory.values.get(key) ?? null).pipe(
131+
Effect.tap(() => Deferred.succeed(readStarted, undefined)),
132+
Effect.tap(() => Deferred.await(readGate)),
133+
)
134+
: Effect.sync(() => memory.values.get(key) ?? null),
135+
setItem: (key, value) =>
136+
Effect.sync(() => {
137+
memory.values.set(key, value);
138+
}),
139+
removeItem: (key) =>
140+
Effect.sync(() => {
141+
memory.values.delete(key);
142+
}),
143+
});
144+
const { tokens } = yield* makeStores(gatedStorage);
145+
yield* Effect.sync(() => memory.values.set(TOKEN_KEY, JSON.stringify(encodeToken(TOKEN))));
146+
147+
const pendingGet = yield* tokens.get(ENVIRONMENT_ID).pipe(Effect.forkScoped);
148+
yield* Deferred.await(readStarted);
149+
const pendingRemove = yield* tokens.remove(ENVIRONMENT_ID).pipe(Effect.forkScoped);
150+
// Give remove every chance to run while the read is parked on the gate.
151+
// With per-environment serialization it stays queued behind the get; a
152+
// regression lets it delete the keychain entry here, and the resumed
153+
// get would then resurrect the removed token into the cache.
154+
for (let i = 0; i < 20 && memory.values.has(TOKEN_KEY); i += 1) {
155+
yield* Effect.yieldNow;
156+
}
157+
yield* Deferred.succeed(readGate, undefined);
158+
yield* Fiber.join(pendingGet);
159+
yield* Fiber.join(pendingRemove);
160+
161+
// remove ran after get completed (same-env operations serialize), so
162+
// the token is gone from both the keychain and the in-memory cache.
163+
expect(memory.values.has(TOKEN_KEY)).toBe(false);
164+
expect(Option.isNone(yield* tokens.get(ENVIRONMENT_ID))).toBe(true);
165+
}),
166+
);
167+
168+
it.effect("discards a corrupt persisted token instead of failing the connection", () =>
169+
Effect.gen(function* () {
170+
const memory = makeStorage({ [TOKEN_KEY]: "{not-json" });
171+
const { tokens } = yield* makeStores(memory.storage);
172+
173+
expect(Option.isNone(yield* tokens.get(ENVIRONMENT_ID))).toBe(true);
174+
expect(memory.values.has(TOKEN_KEY)).toBe(false);
175+
}),
176+
);
177+
});

0 commit comments

Comments
 (0)