Open History to see the last commit
1import { StoredOrchestrationShellSnapshot } from "@t3tools/client-runtime/platform";
2import { OrchestrationV2ThreadShellJson } from "@t3tools/contracts";
3import * as Effect from "effect/Effect";
4import * as Schema from "effect/Schema";
5
6const ROWS_PER_CHUNK = 32;
7
8// Effect's cooperative yield resumes through microtasks on React Native. A host
9// timer lets input and rendering run between chunks of shell rows instead.
10const yieldToHost = Effect.callback<void>((resume) => {
11 const timer = setTimeout(() => resume(Effect.void), 0);
12 return Effect.sync(() => clearTimeout(timer));
13});
14
15// Rows go through the canonical row codec in chunks. The envelope codec then
16// validates and encodes everything else, passing the encoded rows through as-is.
17const encodeThreadChunk = Schema.encodeEffect(Schema.Array(OrchestrationV2ThreadShellJson));
18const EncodedRows = Schema.Array(Schema.Unknown);
19const encodeEnvelope = Schema.encodeEffect(
20 Schema.fromJsonString(
21 StoredOrchestrationShellSnapshot.mapFields((fields) => ({
22 ...fields,
23 snapshot: fields.snapshot.mapFields((snapshotFields) => ({
24 ...snapshotFields,
25 threads: EncodedRows,
26 archivedThreads: EncodedRows,
27 })),
28 })),
29 ),
30);
31
32/**
33 * Encode the shell cache payload exactly like `fromJsonString(StoredOrchestrationShellSnapshot)`,
34 * yielding to the host between bounded chunks of thread rows. The final envelope encode and
35 * JSON stringify still run synchronously over the whole payload.
36 */
37export const encodeStoredShellSnapshot = Effect.fnUntraced(function* (
38 stored: typeof StoredOrchestrationShellSnapshot.Type,
39) {
40 let hasWorked = false;
41 const yieldBetweenChunks = Effect.suspend(() => {
42 if (hasWorked) return yieldToHost;
43 hasWorked = true;
44 return Effect.void;
45 });
46 const encodeRows = (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>
47 Effect.gen(function* () {
48 const encoded: Array<unknown> = [];
49 for (let start = 0; start < rows.length; start += ROWS_PER_CHUNK) {
50 yield* yieldBetweenChunks;
51 const chunk = yield* encodeThreadChunk(rows.slice(start, start + ROWS_PER_CHUNK));
52 for (const row of chunk) encoded.push(row);
53 }
54 return encoded;
55 });
56
57 const { snapshot } = stored;
58 const threads = yield* encodeRows(snapshot.threads);
59 const archivedThreads = yield* encodeRows(snapshot.archivedThreads);
60 yield* yieldBetweenChunks;
61 return yield* encodeEnvelope({ ...stored, snapshot: { ...snapshot, threads, archivedThreads } });
62});