Open History to see the last commit
1import {
2 OrchestrationV2ProjectedTurnItem,
3 OrchestrationV2ThreadDetailSnapshot,
4 OrchestrationV2ThreadProjection,
5} from "@t3tools/contracts";
6import * as Effect from "effect/Effect";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9
10const ENCODE_BATCH_ITEMS = 256;
11const CHUNK_CHARS = 256 * 1024;
12
13type Encode = (input: unknown) => Effect.Effect<unknown, Schema.SchemaError>;
14
15// The endpoint encodes its success with toCodecJson (HttpApiEndpoint): values come out as JSON.
16const encodeJson = (schema: Schema.Top): Encode =>
17 Schema.encodeUnknownEffect(
18 Schema.toCodecJson(schema) as unknown as Schema.Codec<unknown, unknown>,
19 );
20
21const encodeSnapshot = encodeJson(OrchestrationV2ThreadDetailSnapshot);
22const encodeProjectionField = new Map<string, Encode>(
23 Object.entries(OrchestrationV2ThreadProjection.fields).map(([key, schema]) => [
24 key,
25 encodeJson(schema),
26 ]),
27);
28const encodeRowsWithoutItem = encodeJson(
29 Schema.Array(OrchestrationV2ProjectedTurnItem.mapFields(({ item: _item, ...fields }) => fields)),
30);
31// A row encodes its fields in schema order; a reused item matches that only as the last field.
32const ROW_ITEM_IS_LAST = Object.keys(OrchestrationV2ProjectedTurnItem.fields).at(-1) === "item";
33
34const batchesOf = <A>(values: ReadonlyArray<A>) =>
35 Array.from({ length: Math.ceil(values.length / ENCODE_BATCH_ITEMS) }, (_, index) =>
36 values.slice(index * ENCODE_BATCH_ITEMS, (index + 1) * ENCODE_BATCH_ITEMS),
37 );
38
39// Visible rows repeat local turn items; reuse their encoding instead of encoding each item twice.
40// Untraced: it runs once per batch, inside the traced encode.
41const encodeVisibleRows = Effect.fnUntraced(function* (
42 rows: ReadonlyArray<{ readonly item: unknown }>,
43 encodedItems: ReadonlyMap<unknown, unknown>,
44 encodeRows: Encode,
45) {
46 const rests = (yield* encodeRowsWithoutItem(
47 rows.map(({ item: _item, ...rest }) => rest),
48 )) as ReadonlyArray<object>;
49 const encoded: Array<unknown> = [];
50 const missed: Array<number> = [];
51 rows.forEach((row, index) => {
52 const item = ROW_ITEM_IS_LAST ? encodedItems.get(row.item) : undefined;
53 if (item === undefined) missed.push(index);
54 encoded.push(item === undefined ? undefined : { ...rests[index], item });
55 });
56 if (missed.length > 0) {
57 const full = (yield* encodeRows(missed.map((index) => rows[index]))) as ReadonlyArray<unknown>;
58 missed.forEach((index, position) => (encoded[index] = full[position]));
59 }
60 return encoded;
61});
62
63type Json =
64 | null
65 | boolean
66 | number
67 | string
68 | ReadonlyArray<Json>
69 | { readonly [key: string]: Json };
70type Container = ReadonlyArray<Json> | { readonly [key: string]: Json };
71
72const isContainer = (value: Json): value is Container =>
73 typeof value === "object" && value !== null;
74
75// Deeper values are written level by level: JSON.stringify recurses, and deep enough it throws.
76// Kept low so the lookahead below stays cheap on deeply nested values.
77const MAX_NATIVE_DEPTH = 128;
78
79// Lookahead: whether its JSON is about longer than a chunk (escapes can add more) or nests too
80// deep for one JSON.stringify. Stops as soon as either holds, so it costs a chunk at most.
81const tooLargeForOneString = (root: Json) => {
82 let budget = CHUNK_CHARS;
83 const pending: Array<readonly [Json, number]> = [[root, 0]];
84 while (pending.length > 0 && budget >= 0) {
85 const [value, depth] = pending.pop()!;
86 if (typeof value === "string") budget -= value.length + 2;
87 else if (!isContainer(value)) budget -= 8;
88 else if (depth >= MAX_NATIVE_DEPTH) return true;
89 else if (Array.isArray(value)) {
90 // Every element costs at least its comma, so a longer array is over budget already.
91 if ((budget -= value.length + 2) >= 0) {
92 for (const element of value) pending.push([element, depth + 1]);
93 }
94 } else {
95 budget -= 2;
96 for (const key in value) {
97 if ((budget -= key.length + 3) < 0) break;
98 pending.push([(value as Readonly<Record<string, Json>>)[key]!, depth + 1]);
99 }
100 }
101 }
102 return budget < 0;
103};
104
105// Never between the halves of a surrogate pair: apart, each half encodes differently.
106const sliceEnd = (text: string, start: number) => {
107 const end = Math.min(start + CHUNK_CHARS, text.length);
108 const last = text.charCodeAt(end - 1);
109 return end < text.length && last >= 0xd800 && last <= 0xdbff ? end - 1 : end;
110};
111
112function* stringParts(text: string): Generator<string> {
113 if (text.length <= CHUNK_CHARS) {
114 yield JSON.stringify(text);
115 return;
116 }
117 yield '"';
118 for (let start = 0; start < text.length;) {
119 const end = sliceEnd(text, start);
120 yield JSON.stringify(text.slice(start, end)).slice(1, -1);
121 start = end;
122 }
123 yield '"';
124}
125
126/** JSON.stringify of a JSON value in parts of about a chunk or less, without recursion. */
127function* jsonParts(root: Json): Generator<string> {
128 if (!tooLargeForOneString(root)) {
129 yield JSON.stringify(root);
130 return;
131 }
132 if (!isContainer(root)) {
133 yield* stringParts(root as string);
134 return;
135 }
136 // Only the open containers are held: each with its keys, if an object, and the next index.
137 const stack: Array<{
138 readonly container: Container;
139 readonly keys: ReadonlyArray<string> | undefined;
140 index: number;
141 }> = [];
142 let next: Json | undefined = root;
143 while (true) {
144 if (next !== undefined) {
145 if (typeof next === "string") yield* stringParts(next);
146 else if (!isContainer(next) || (next !== root && !tooLargeForOneString(next))) {
147 yield JSON.stringify(next);
148 } else {
149 const keys = Array.isArray(next) ? undefined : Object.keys(next);
150 yield keys === undefined ? "[" : "{";
151 stack.push({ container: next, keys, index: 0 });
152 }
153 next = undefined;
154 }
155 const frame = stack.at(-1);
156 if (frame === undefined) return;
157 const { container, keys } = frame;
158 if (frame.index === (keys ?? (container as ReadonlyArray<Json>)).length) {
159 stack.pop();
160 yield keys === undefined ? "]" : "}";
161 continue;
162 }
163 if (frame.index > 0) yield ",";
164 if (keys === undefined) next = (container as ReadonlyArray<Json>)[frame.index]!;
165 else {
166 const key = keys[frame.index]!;
167 yield* stringParts(key);
168 yield ":";
169 next = (container as Readonly<Record<string, Json>>)[key]!;
170 }
171 frame.index++;
172 }
173}
174
175function* objectParts(
176 value: Readonly<Record<string, Json>>,
177 memberParts: (key: string, member: Json) => Iterable<string>,
178): Generator<string> {
179 yield "{";
180 let separator = "";
181 for (const key of Object.keys(value)) {
182 yield separator;
183 yield* stringParts(key);
184 yield ":";
185 yield* memberParts(key, value[key]!);
186 separator = ",";
187 }
188 yield "}";
189}
190
191function* elementsParts(elements: ReadonlyArray<Json>): Generator<string> {
192 yield "[";
193 for (let index = 0; index < elements.length; index++) {
194 if (index > 0) yield ",";
195 yield* jsonParts(elements[index]!);
196 }
197 yield "]";
198}
199
200// Parts are sized before escaping, which can make one six times longer: cut the written text.
201function* chunks(parts: Iterable<string>): Generator<Uint8Array> {
202 let pending = "";
203 for (const part of parts) {
204 pending += part;
205 while (pending.length >= CHUNK_CHARS) {
206 const end = sliceEnd(pending, 0);
207 yield Buffer.from(pending.slice(0, end), "utf8");
208 pending = pending.slice(end);
209 }
210 }
211 if (pending.length > 0) yield Buffer.from(pending, "utf8");
212}
213
214/**
215 * The thread snapshot's body, byte for byte what HttpApiBuilder sends: `JSON.stringify` of its
216 * toCodecJson encoding. It encodes in batches before returning, so a schema failure still precedes
217 * the response; the text is made chunk by chunk as the body is read.
218 */
219export const encodeThreadSnapshotBody = Effect.fn("ThreadSnapshotBody.encode")(function* (
220 snapshot: OrchestrationV2ThreadDetailSnapshot,
221) {
222 const projection = snapshot.projection as unknown as Readonly<Record<string, unknown>>;
223 const arrayKeys = [...encodeProjectionField.keys()].filter((key) =>
224 Array.isArray(projection[key]),
225 );
226 const envelope = (yield* encodeSnapshot({
227 ...snapshot,
228 projection: { ...projection, ...Object.fromEntries(arrayKeys.map((key) => [key, []])) },
229 })) as Readonly<Record<string, Json>>;
230 const encodedItems = new Map<unknown, unknown>();
231 const arrays = new Map<string, ReadonlyArray<Json>>();
232 for (const key of arrayKeys) {
233 const encode = encodeProjectionField.get(key)!;
234 const batches: Array<ReadonlyArray<unknown>> = [];
235 for (const batch of batchesOf(projection[key] as ReadonlyArray<unknown>)) {
236 const encoded =
237 key === "visibleTurnItems"
238 ? yield* encodeVisibleRows(
239 batch as ReadonlyArray<{ readonly item: unknown }>,
240 encodedItems,
241 encode,
242 )
243 : ((yield* encode(batch)) as ReadonlyArray<unknown>);
244 if (key === "turnItems")
245 batch.forEach((item, index) => encodedItems.set(item, encoded[index]));
246 batches.push(encoded);
247 yield* Effect.yieldNow;
248 }
249 arrays.set(key, batches.flat() as ReadonlyArray<Json>);
250 }
251 encodedItems.clear();
252 // The encoded arrays replace the envelope's empty ones, in the envelope's key order.
253 return Stream.suspend(() =>
254 Stream.fromIterable(
255 chunks(
256 objectParts(envelope, (key, value) =>
257 key === "projection"
258 ? objectParts(value as Readonly<Record<string, Json>>, (field, member) => {
259 const elements = arrays.get(field);
260 return elements === undefined ? jsonParts(member) : elementsParts(elements);
261 })
262 : jsonParts(value),
263 ),
264 ),
265 { chunkSize: 1 },
266 ),
267 );
268});