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

shellCacheEncoding.ts

86 lines3.4 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 =
55 /* Cache encoding runs for shell update batches; avoid tracing each batch. */
56 Effect.fnUntraced(function* (misses: ReadonlyArray<OrchestrationV2ThreadShellJson>) {
57 yield* yieldBetweenChunks;
58 const chunk = yield* encodeThreadChunk(misses);
59 chunk.forEach((row, index) => encodedRows.set(misses[index]!, row));
60 });
61 const encodeRows =
62 /* Cache encoding runs for shell update batches; avoid tracing each batch. */
63 Effect.fnUntraced(function* (rows: ReadonlyArray<OrchestrationV2ThreadShellJson>) {
64 let misses: Array<OrchestrationV2ThreadShellJson> = [];
65 for (const row of rows) {
66 if (encodedRows.has(row)) continue;
67 misses.push(row);
68 if (misses.length === ROWS_PER_CHUNK) {
69 yield* encodeMisses(misses);
70 misses = [];
71 }
72 }
73 if (misses.length > 0) yield* encodeMisses(misses);
74 return rows.map((row) => encodedRows.get(row));
75 });
76​
77 const { snapshot } = stored;
78 const threads = yield* encodeRows(snapshot.threads);
79 const archivedThreads = yield* encodeRows(snapshot.archivedThreads);
80 if (hasWorked) yield* yieldToHost;
81 return yield* encodeEnvelope({
82 ...stored,
83 snapshot: { ...snapshot, threads, archivedThreads },
84 });
85 });