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

shellCacheEncoding.ts

84 lines3.3 KB

1import { OrchestrationV2ThreadShellJson } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4​
5import { StoredOrchestrationShellSnapshot } from "./orchestrationCache.ts";
6​
7const ROWS_PER_CHUNK = 32;
8​
9// Effect's own yield resumes through `setImmediate` where the host defines it and a
10// zero-delay timer otherwise. React Native's `setImmediate` is a microtask shim, so
11// nothing from the host runs before the fiber resumes. A timer yields on every host;
12// a browser can pass a yield that its timer clamping and throttling do not slow.
13const yieldToHostTimer = Effect.callback<void>((resume) => {
14 // @effect-diagnostics-next-line globalTimersInEffect:off - A host timer, not Effect.sleep, is the point.
15 const timer = setTimeout(() => resume(Effect.void), 0);
16 return Effect.sync(() => clearTimeout(timer));
17});
18​
19const encodeThreadChunk = Schema.encodeEffect(Schema.Array(OrchestrationV2ThreadShellJson));
20const EncodedRows = Schema.Array(Schema.Unknown);
21const encodeEnvelope = Schema.encodeEffect(
22 Schema.fromJsonString(
23 StoredOrchestrationShellSnapshot.mapFields((fields) => ({
24 ...fields,
25 snapshot: fields.snapshot.mapFields((snapshotFields) => ({
26 ...snapshotFields,
27 threads: EncodedRows,
28 archivedThreads: EncodedRows,
29 })),
30 })),
31 ),
32);
33​
34/**
35 * Shell rows are immutable and the shell reducer keeps unchanged rows by
36 * reference, so each encoder remembers the canonical encoding of rows it has
37 * already encoded successfully and only runs the row codec for new rows.
38 *
39 * `yieldToHost` defaults to a zero-delay timer.
40 */
41export function makeStoredShellSnapshotEncoder(
42 options: { readonly yieldToHost?: Effect.Effect<void> } = {},
43) {
44 const yieldToHost = options.yieldToHost ?? yieldToHostTimer;
45 const encodedRows = new WeakMap<OrchestrationV2ThreadShellJson, unknown>();
46​
47 return Effect.fnUntraced(function* (stored: typeof StoredOrchestrationShellSnapshot.Type) {
48 let hasWorked = false;
49 const yieldBetweenChunks = Effect.suspend(() => {
50 if (hasWorked) return yieldToHost;
51 hasWorked = true;
52 return Effect.void;
53 });
54 const encodeMisses = (misses: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>
55 Effect.gen(function* () {
56 yield* yieldBetweenChunks;
57 const chunk = yield* encodeThreadChunk(misses);
58 chunk.forEach((row, index) => encodedRows.set(misses[index]!, row));
59 });
60 const encodeRows = (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) =>
61 Effect.gen(function* () {
62 let misses: Array<OrchestrationV2ThreadShellJson> = [];
63 for (const row of rows) {
64 if (encodedRows.has(row)) continue;
65 misses.push(row);
66 if (misses.length === ROWS_PER_CHUNK) {
67 yield* encodeMisses(misses);
68 misses = [];
69 }
70 }
71 if (misses.length > 0) yield* encodeMisses(misses);
72 return rows.map((row) => encodedRows.get(row));
73 });
74​
75 const { snapshot } = stored;
76 const threads = yield* encodeRows(snapshot.threads);
77 const archivedThreads = yield* encodeRows(snapshot.archivedThreads);
78 if (hasWorked) yield* yieldToHost;
79 return yield* encodeEnvelope({
80 ...stored,
81 snapshot: { ...snapshot, threads, archivedThreads },
82 });
83 });