Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell-cache-encoding.ts

38 lines1.5 KB

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​
6// Effect's cooperative yield resumes through microtasks on React Native. A host
7// timer lets input and rendering run between batches of shell rows instead.
8const yieldToHost = Effect.callback<void>((resume) => {
9 const timer = setTimeout(() => resume(Effect.void), 0);
10 return Effect.sync(() => clearTimeout(timer));
11});
12​
13// Share the row budget across saves and environments; this bounds batches, not elapsed time.
14let encodedRows = 0;
15const CooperativeThreadShell = OrchestrationV2ThreadShellJson.pipe(
16 Schema.middlewareEncoding<typeof OrchestrationV2ThreadShellJson, never>((effect) =>
17 Effect.flatMap(effect, (value) => {
18 encodedRows++;
19 if (encodedRows < 32) return Effect.succeed(value);
20 encodedRows = 0;
21 return Effect.as(yieldToHost, value);
22 }),
23 ),
24);
25​
26const CooperativeStoredShellSnapshot = StoredOrchestrationShellSnapshot.mapFields((fields) => ({
27 ...fields,
28 snapshot: fields.snapshot.mapFields((snapshotFields) => ({
29 ...snapshotFields,
30 threads: Schema.Array(CooperativeThreadShell),
31 archivedThreads: Schema.Array(CooperativeThreadShell),
32 })),
33}));
34​
35/** Preserve the cache codec's validation and transforms while yielding during large saves. */
36export const encodeStoredShellSnapshot = Schema.encodeEffect(
37 Schema.fromJsonString(CooperativeStoredShellSnapshot),
38);