TypeScript
perf(mobile): reduce shell cache encoding work (#15096)
Julius Marminge1c33f3b2b297
diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.tsindex 6ca84b2a512..8e4ce3e6211 100644--- a/apps/mobile/src/connection/environment-cache-store.test.ts+++ b/apps/mobile/src/connection/environment-cache-store.test.ts@@ -388,16 +388,105 @@ describe("cooperative shell cache encoding", () => {}),);- it.effect("still rejects invalid rows after an encoding batch yields", () =>+ it.effect("preserves optional fields and dates across chunk boundaries and archived rows", () =>Effect.gen(function* () {- const invalid = {+ const base = SHELL_SNAPSHOT.threads[0]!;+ const { titleRegeneration: _, unsettledAt: __, ...withoutOptional } = base;+ const row = (index: number) =>+ index % 3 === 0+ ? { ...withoutOptional, id: ThreadId.make(`row-${index}`) }+ : {+ ...base,+ id: ThreadId.make(`row-${index}`),+ snoozedUntil: DateTime.add(NOW, { minutes: index }),+ pinnedAt: index % 2 === 0 ? null : NOW,+ };+ const mixed = {...stored,snapshot: {...stored.snapshot,- threads: [...stored.snapshot.threads, { ...stored.snapshot.threads[0]!, itemCount: -1 }],+ threads: Array.from({ length: 65 }, (_, index) => row(index)),+ archivedThreads: Array.from({ length: 33 }, (_, index) => ({+ ...row(index + 100),+ archivedAt: DateTime.add(NOW, { hours: index }),+ })),},};- expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalid))).toBe(true);+ const actual = yield* encodeStoredShellSnapshot(mixed);+ expect(actual).toBe(yield* encodeOriginal(mixed));+ const parsed = JSON.parse(actual);+ expect(parsed.snapshot.threads).toHaveLength(65);+ expect(parsed.snapshot.threads[63]).not.toHaveProperty("titleRegeneration");+ expect(parsed.snapshot.threads[63]).not.toHaveProperty("unsettledAt");+ expect(parsed.snapshot.threads[64].snoozedUntil).toBe(+ DateTime.formatIso(DateTime.add(NOW, { minutes: 64 })),+ );+ expect(parsed.snapshot.archivedThreads).toHaveLength(33);+ expect(parsed.snapshot.archivedThreads[32].archivedAt).toBe(+ DateTime.formatIso(DateTime.add(NOW, { hours: 32 })),+ );+ }),+ );++ it.effect("yields to a host timer between every 32-row chunk", () =>+ Effect.gen(function* () {+ const setTimer = vi.spyOn(globalThis, "setTimeout");+ try {+ yield* encodeStoredShellSnapshot({+ ...stored,+ snapshot: {+ ...stored.snapshot,+ threads: Array.from({ length: 65 }, () => stored.snapshot.threads[0]!),+ archivedThreads: Array.from({ length: 33 }, () => stored.snapshot.archivedThreads[0]!),+ },+ });+ // Five row chunks (3 active + 2 archived): four yields between them, one before the envelope.+ expect(setTimer).toHaveBeenCalledTimes(5);+ } finally {+ vi.restoreAllMocks();+ }+ }),+ );++ it.effect("still rejects invalid active and archived rows after an encoding chunk yields", () =>+ Effect.gen(function* () {+ const invalidRow = { ...stored.snapshot.threads[0]!, itemCount: -1 };+ const invalidActive = {+ ...stored,+ snapshot: { ...stored.snapshot, threads: [...stored.snapshot.threads, invalidRow] },+ };+ const invalidArchived = {+ ...stored,+ snapshot: { ...stored.snapshot, archivedThreads: [invalidRow] },+ };+ const invalidEnvelope = { ...stored, snapshot: { ...stored.snapshot, snapshotSequence: -1 } };+ expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidActive))).toBe(true);+ expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidArchived))).toBe(true);+ expect(yield* Effect.isFailure(encodeOriginal(invalidEnvelope))).toBe(true);+ expect(yield* Effect.isFailure(encodeStoredShellSnapshot(invalidEnvelope))).toBe(true);+ }),+ );++ it.effect("keeps concurrent saves independent", () =>+ Effect.gen(function* () {+ const other = {+ ...stored,+ environmentId: EnvironmentId.make("environment-2"),+ snapshot: {+ ...stored.snapshot,+ threads: stored.snapshot.threads.slice(0, 40).map((thread) => ({+ ...thread,+ title: `Other ${thread.id}`,+ })),+ archivedThreads: [],+ },+ };+ const [first, second] = yield* Effect.all(+ [encodeStoredShellSnapshot(stored), encodeStoredShellSnapshot(other)],+ { concurrency: "unbounded" },+ );+ expect(first).toBe(yield* encodeOriginal(stored));+ expect(second).toBe(yield* encodeOriginal(other));}),);diff --git a/apps/mobile/src/connection/shell-cache-encoding.ts b/apps/mobile/src/connection/shell-cache-encoding.tsindex d06630cfd2f..23dfb8d510a 100644--- a/apps/mobile/src/connection/shell-cache-encoding.ts+++ b/apps/mobile/src/connection/shell-cache-encoding.ts@@ -3,36 +3,60 @@ import { OrchestrationV2ThreadShellJson } from "@t3tools/contracts";import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";+const ROWS_PER_CHUNK = 32;+// Effect's cooperative yield resumes through microtasks on React Native. A host-// timer lets input and rendering run between batches of shell rows instead.+// timer lets input and rendering run between chunks of shell rows instead.const yieldToHost = Effect.callback<void>((resume) => {const timer = setTimeout(() => resume(Effect.void), 0);return Effect.sync(() => clearTimeout(timer));});-// Share the row budget across saves and environments; this bounds batches, not elapsed time.-let encodedRows = 0;-const CooperativeThreadShell = OrchestrationV2ThreadShellJson.pipe(- Schema.middlewareEncoding<typeof OrchestrationV2ThreadShellJson, never>((effect) =>- Effect.flatMap(effect, (value) => {- encodedRows++;- if (encodedRows < 32) return Effect.succeed(value);- encodedRows = 0;- return Effect.as(yieldToHost, value);- }),+// Rows go through the canonical row codec in chunks. The envelope codec then+// validates and encodes everything else, passing the encoded rows through as-is.+const encodeThreadChunk = Schema.encodeEffect(Schema.Array(OrchestrationV2ThreadShellJson));+const EncodedRows = Schema.Array(Schema.Unknown);+const encodeEnvelope = Schema.encodeEffect(+ Schema.fromJsonString(+ StoredOrchestrationShellSnapshot.mapFields((fields) => ({+ ...fields,+ snapshot: fields.snapshot.mapFields((snapshotFields) => ({+ ...snapshotFields,+ threads: EncodedRows,+ archivedThreads: EncodedRows,+ })),+ })),),);-const CooperativeStoredShellSnapshot = StoredOrchestrationShellSnapshot.mapFields((fields) => ({- ...fields,- snapshot: fields.snapshot.mapFields((snapshotFields) => ({- ...snapshotFields,- threads: Schema.Array(CooperativeThreadShell),- archivedThreads: Schema.Array(CooperativeThreadShell),- })),-}));+/**+ * Encode the shell cache payload exactly like `fromJsonString(StoredOrchestrationShellSnapshot)`,+ * yielding to the host between bounded chunks of thread rows. The final envelope encode and+ * JSON stringify still run synchronously over the whole payload.+ */+export const encodeStoredShellSnapshot = Effect.fnUntraced(function* (+ stored: typeof StoredOrchestrationShellSnapshot.Type,+) {+ let hasWorked = false;+ const yieldBetweenChunks = Effect.suspend(() => {+ if (hasWorked) return yieldToHost;+ hasWorked = true;+ return Effect.void;+ });+ const encodeRows = (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>+ Effect.gen(function* () {+ const encoded: Array<unknown> = [];+ for (let start = 0; start < rows.length; start += ROWS_PER_CHUNK) {+ yield* yieldBetweenChunks;+ const chunk = yield* encodeThreadChunk(rows.slice(start, start + ROWS_PER_CHUNK));+ for (const row of chunk) encoded.push(row);+ }+ return encoded;+ });-/** Preserve the cache codec's validation and transforms while yielding during large saves. */-export const encodeStoredShellSnapshot = Schema.encodeEffect(- Schema.fromJsonString(CooperativeStoredShellSnapshot),-);+ const { snapshot } = stored;+ const threads = yield* encodeRows(snapshot.threads);+ const archivedThreads = yield* encodeRows(snapshot.archivedThreads);+ yield* yieldBetweenChunks;+ return yield* encodeEnvelope({ ...stored, snapshot: { ...snapshot, threads, archivedThreads } });+});