Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * Raw filesystem access for transcript scanning.
4 *
5 * Isolated here so the rest of the usage code stays on Effect's `FileSystem`.
6 * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB
7 * across ~1,500 files, and buffer-level streaming is roughly an order of
8 * magnitude cheaper than materialising each file. The equivalent Effect stream
9 * pipeline is idiomatic but not fast enough to sit behind a page load.
10 *
11 * Transcripts are append-only, so a parse also reports the byte position it
12 * stopped at. A later scan of the same file resumes from that position and
13 * parses only the appended bytes, which is what keeps a warm scan cheap while a
14 * session is actively writing a multi-hundred-megabyte rollout.
15 *
16 * @module usageTranscriptReader
17 */
18import * as NodeFSP from "node:fs/promises";
19import * as NodePath from "node:path";
20import * as NodeStringDecoder from "node:string_decoder";
21
22import type {
23 SelectedFields,
24 TranscriptUsageFormat,
25 UsageRecord,
26} from "@t3tools/provider-core/server/usage";
27import * as Option from "effect/Option";
28import * as Schema from "effect/Schema";
29
30import { createTranscriptJsonReader } from "../project/AgentSessionJson.ts";
31
32export interface TranscriptFile {
33 readonly path: string;
34 readonly size: number;
35 readonly mtimeMs: number;
36}
37
38/**
39 * Where a parse stopped, with enough state to continue from there.
40 *
41 * The guard hash fingerprints the bytes immediately before `resumeOffset`. A
42 * resume only proceeds when those bytes still match: transcripts are
43 * append-only by design, but a rotated or rewritten file silently mis-parsed
44 * from the middle would corrupt usage totals. The window is a cheap tripwire
45 * for those realistic failure shapes, all of which disturb the file's tail at
46 * that exact offset; it deliberately does not hash the whole prefix, which
47 * would cost the full re-read the resume exists to avoid.
48 */
49export interface TranscriptParsePosition {
50 /** Byte offset just past the last newline-terminated line consumed. */
51 readonly resumeOffset: number;
52 /** Length of the fingerprinted window ending at `resumeOffset`. */
53 readonly guardLength: number;
54 /** FNV-1a hash of that window. */
55 readonly guardHash: number;
56 /**
57 * The format's reducer state as of `resumeOffset`, encoded by its schema;
58 * `null` for stateless formats.
59 */
60 readonly state: unknown;
61}
62
63export interface TranscriptParseResult {
64 /** Records from newline-terminated lines at or after the parse start. */
65 readonly records: readonly UsageRecord[];
66 /**
67 * Records from a trailing segment the writer has not newline-terminated yet.
68 * Kept out of `records` because `position` deliberately excludes that
69 * segment: the next scan re-reads it once the writer finishes the line.
70 */
71 readonly tailRecords: readonly UsageRecord[];
72 readonly position: TranscriptParsePosition;
73 /** Whether the parse continued from `resumeFrom` rather than byte 0. */
74 readonly resumed: boolean;
75}
76
77/** 64 bytes of JSONL tail is ample to distinguish a replaced file. */
78export const GUARD_LENGTH = 64;
79// Native parsing is faster for common 1–4 MiB context/tool records. Above
80// 8 MiB, project usage without allocating the whole record. This switches
81// readers; it never discards a record because of its size.
82const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024;
83const NEWLINE = 0x0a;
84/** `stat` calls one transcript walk keeps in flight. The libuv pool has 4 threads. */
85const STAT_CONCURRENCY = 32;
86const CARRIAGE_RETURN = 0x0d;
87
88function selectUsageFields(fields: SelectedFields) {
89 return (path: ReadonlyArray<string | number | null>): boolean => {
90 let selected: true | SelectedFields = fields;
91 for (const key of path) {
92 if (selected === true) return true;
93 if (typeof key !== "string" || !Object.hasOwn(selected, key)) return false;
94 selected = selected[key]!;
95 }
96 return true;
97 };
98}
99
100function fnv1a(buffer: Buffer): number {
101 let hash = 0x811c9dc5;
102 for (let index = 0; index < buffer.length; index += 1) {
103 hash ^= buffer[index]!;
104 hash = Math.imul(hash, 0x01000193);
105 }
106 return hash >>> 0;
107}
108
109/**
110 * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.
111 *
112 * Errors on individual entries are swallowed: session files rotate and get
113 * removed while the walk is in flight, and a partial listing is far better than
114 * failing the page.
115 *
116 * `fileName` restricts the walk to a single basename (Grok's `updates.jsonl`).
117 * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that
118 * never carry usage, so the basename filter keeps a cold scan off those files.
119 *
120 * Directories are listed depth-first, one at a time, then the candidates are
121 * stat'd by a fixed pool of workers: a warm scan stats thousands of files, and
122 * one at a time each waits its own trip through the thread pool. Results keep
123 * `readdir` order, which the aggregator's first-seen dedupe relies on.
124 */
125export async function listTranscriptFiles(
126 root: string,
127 sinceMs: number,
128 options?: { readonly fileName?: string },
129): Promise<readonly TranscriptFile[]> {
130 const fileName = options?.fileName;
131 const candidates: string[] = [];
132 const walk = async (dir: string): Promise<void> => {
133 let entries;
134 try {
135 entries = await NodeFSP.readdir(dir, { withFileTypes: true });
136 } catch {
137 return;
138 }
139 for (const entry of entries) {
140 const child = NodePath.join(dir, entry.name);
141 if (entry.isDirectory()) await walk(child);
142 else if (fileName !== undefined ? entry.name === fileName : entry.name.endsWith(".jsonl")) {
143 candidates.push(child);
144 }
145 }
146 };
147 await walk(root);
148
149 const found: Array<TranscriptFile | undefined> = Array.from({ length: candidates.length });
150 // Each worker pulls the next candidate from one shared iterator.
151 const queue = candidates.entries();
152 const statQueued = async (): Promise<void> => {
153 for (const [index, path] of queue) {
154 try {
155 const stats = await NodeFSP.stat(path);
156 if (stats.mtimeMs >= sinceMs) {
157 found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs };
158 }
159 } catch {
160 // Vanished between readdir and stat.
161 }
162 }
163 };
164 await Promise.all(
165 Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued),
166 );
167 return found.filter((file) => file !== undefined);
168}
169
170/**
171 * Filesystem identity of a directory, as `device:inode`.
172 *
173 * Used to tell "two servers reading the same transcript directory" apart from
174 * "two machines whose hostname and home path happen to match". Returns an empty
175 * string when the directory cannot be stat'd.
176 */
177export async function readDirectoryVolumeId(path: string): Promise<string> {
178 try {
179 const stats = await NodeFSP.stat(path);
180 return `${stats.dev}:${stats.ino}`;
181 } catch {
182 return "";
183 }
184}
185
186async function guardMatches(
187 handle: NodeFSP.FileHandle,
188 position: TranscriptParsePosition,
189): Promise<boolean> {
190 if (position.guardLength <= 0 || position.guardLength > GUARD_LENGTH) return false;
191 try {
192 const window = Buffer.alloc(position.guardLength);
193 const { bytesRead } = await handle.read(
194 window,
195 0,
196 position.guardLength,
197 position.resumeOffset - position.guardLength,
198 );
199 return bytesRead === position.guardLength && fnv1a(window) === position.guardHash;
200 } catch {
201 return false;
202 }
203}
204
205/**
206 * Streams one transcript and returns the usage records it contains, or `null`
207 * when the file could not be read.
208 *
209 * The distinction matters to the caller's cache: a genuinely empty transcript
210 * is a stable fact worth memoising, while a transient read failure memoised
211 * under the same `(size, mtime)` key would silently drop that file's usage
212 * until the file next changes.
213 *
214 * With `resumeFrom`, parsing continues from that position when its guard bytes
215 * still match, so only appended lines are read; otherwise the whole file is
216 * re-parsed from the start and `resumed` reports `false`.
217 *
218 * A stateful format resumes with the state saved at that position; a saved
219 * state its schema rejects re-parses the file whole.
220 */
221export async function readTranscriptRecords<State>(
222 filePath: string,
223 format: TranscriptUsageFormat<State>,
224 resumeFrom?: TranscriptParsePosition,
225 options?: { readonly streamingThresholdBytes?: number },
226): Promise<TranscriptParseResult | null> {
227 const streamingThresholdBytes = options?.streamingThresholdBytes ?? STREAMING_THRESHOLD_BYTES;
228 let handle: NodeFSP.FileHandle;
229 try {
230 handle = await NodeFSP.open(filePath, "r");
231 } catch {
232 return null;
233 }
234
235 try {
236 const codec = format.state;
237 const decodeState = codec === undefined ? undefined : Schema.decodeUnknownOption(codec.schema);
238 const encodeState = codec === undefined ? undefined : Schema.encodeSync(codec.schema);
239 // Stateless formats never read their state argument.
240 let state = codec === undefined ? (undefined as State) : codec.initial();
241 let resumed = false;
242 let start = 0;
243 const savedState =
244 resumeFrom === undefined || decodeState === undefined || resumeFrom.state === null
245 ? Option.none()
246 : decodeState(resumeFrom.state);
247 if (
248 resumeFrom !== undefined &&
249 resumeFrom.resumeOffset > 0 &&
250 (codec === undefined || Option.isSome(savedState)) &&
251 (await guardMatches(handle, resumeFrom))
252 ) {
253 if (Option.isSome(savedState)) state = savedState.value;
254 start = resumeFrom.resumeOffset;
255 resumed = true;
256 }
257
258 const parseLine = (line: string, lineState: State, out: UsageRecord[]): void => {
259 if (!format.mightCarryUsage(line)) return;
260 for (const record of format.parseLine(line, lineState)) out.push(record);
261 };
262
263 const toLineString = (lineBuffer: Buffer): string => {
264 const content =
265 lineBuffer.length > 0 && lineBuffer[lineBuffer.length - 1] === CARRIAGE_RETURN
266 ? lineBuffer.subarray(0, -1)
267 : lineBuffer;
268 return content.toString("utf8");
269 };
270
271 const records: UsageRecord[] = [];
272 // Byte offsets remain independent of UTF-8 decoding. Only complete lines
273 // commit the resume point; an unfinished tail is replayed on the next scan.
274 let resumeOffset = start;
275 let scanOffset = start;
276 let pendingChunks: Buffer[] = [];
277 let pendingBytes = 0;
278 let streaming: ReturnType<typeof createTranscriptJsonReader> | undefined;
279 let decoder: NodeStringDecoder.StringDecoder | undefined;
280 const selectPath = selectUsageFields(format.selectFields);
281
282 const append = (segment: Buffer) => {
283 if (!streaming && pendingBytes + segment.length <= streamingThresholdBytes) {
284 if (segment.length > 0) pendingChunks.push(segment);
285 pendingBytes += segment.length;
286 return;
287 }
288 if (!streaming) {
289 // Usage has no import-history budget: retain all selected usage fields,
290 // regardless of the size of the surrounding unselected tool content.
291 streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity });
292 decoder = new NodeStringDecoder.StringDecoder("utf8");
293 for (const pending of pendingChunks) streaming.write(decoder.write(pending));
294 pendingChunks = [];
295 pendingBytes = 0;
296 }
297 streaming.write(decoder!.write(segment));
298 };
299 const finish = (lineState: State, out: UsageRecord[]) => {
300 if (streaming) {
301 streaming.write(decoder!.end());
302 const projected = streaming.finish();
303 for (const record of format.parseProjected(projected, lineState)) out.push(record);
304 } else if (pendingBytes > 0) {
305 const line =
306 pendingChunks.length === 1
307 ? pendingChunks[0]!
308 : Buffer.concat(pendingChunks, pendingBytes);
309 parseLine(toLineString(line), lineState, out);
310 }
311 pendingChunks = [];
312 pendingBytes = 0;
313 streaming = undefined;
314 decoder = undefined;
315 };
316 const stream = handle.createReadStream({
317 start,
318 autoClose: false,
319 highWaterMark: 256 * 1024,
320 }) as AsyncIterable<Buffer>;
321 for await (const chunk of stream) {
322 let lineStart = 0;
323 while (lineStart < chunk.length) {
324 const newlineIndex = chunk.indexOf(NEWLINE, lineStart);
325 if (newlineIndex === -1) {
326 append(chunk.subarray(lineStart));
327 break;
328 }
329 // Most lines fit in the current chunk. Avoid buffering/streaming
330 // machinery on this hot path.
331 if (!streaming && pendingBytes === 0) {
332 parseLine(toLineString(chunk.subarray(lineStart, newlineIndex)), state, records);
333 } else {
334 append(chunk.subarray(lineStart, newlineIndex));
335 finish(state, records);
336 }
337 lineStart = newlineIndex + 1;
338 resumeOffset = scanOffset + lineStart;
339 }
340 scanOffset += chunk.length;
341 }
342
343 // The unfinished tail parses against a copy, so the saved state stays at
344 // `resumeOffset` and the next scan replays the tail from it.
345 const encodedState = encodeState === undefined ? null : encodeState(state);
346 const tailRecords: UsageRecord[] = [];
347 finish(
348 decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)),
349 tailRecords,
350 );
351
352 const guardLength = Math.min(GUARD_LENGTH, resumeOffset);
353 let guardHash = 0;
354 if (guardLength > 0) {
355 const window = Buffer.alloc(guardLength);
356 await handle.read(window, 0, guardLength, resumeOffset - guardLength);
357 guardHash = fnv1a(window);
358 }
359
360 return {
361 records,
362 tailRecords,
363 position: {
364 resumeOffset,
365 guardLength,
366 guardHash,
367 state: encodedState,
368 },
369 resumed,
370 };
371 } catch {
372 return null;
373 } finally {
374 await handle.close().catch(() => undefined);
375 }
376}