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

EventNdjsonLogger.ts

616 lines19.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2/**
3 * Best-effort provider event logging with one shared writer per thread.
4 *
5 * Native and canonical views share batching, rotation, and retention state so
6 * they cannot race while appending to the same thread-scoped file.
7 */
8import * as NodeFS from "node:fs";
9import * as NodePath from "node:path";
10​
11import type { ThreadId } from "@t3tools/contracts";
12import { RotatingFileSink } from "@t3tools/shared/logging";
13import { errorTag } from "@t3tools/shared/observability";
14import * as Clock from "effect/Clock";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as SynchronizedRef from "effect/SynchronizedRef";
21​
22import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
23import type { ResourceAttribution } from "../../resourceTelemetry/ResourceAttribution.ts";
24​
25const MEBIBYTE = 1024 * 1024;
26const DAY_MS = 24 * 60 * 60 * 1_000;
27const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
28const DEFAULT_MAX_FILES = 10;
29const DEFAULT_BATCH_WINDOW_MS = 1_000;
30const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
31const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
32const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
33const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
34const DEFAULT_MAX_BUFFERED_RECORDS = 512;
35const GLOBAL_THREAD_SEGMENT = "_global";
36const LOG_SCOPE = "provider-observability";
37const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
38​
39const transientCanonicalEventTypes = new Set([
40 "content.delta",
41 "hook.progress",
42 "item.updated",
43 "task.progress",
44 "thread.realtime.audio.delta",
45 "tool.progress",
46 "turn.proposed.delta",
47]);
48​
49export type EventNdjsonStream = "native" | "canonical" | "orchestration";
50​
51export interface EventNdjsonLogger {
52 readonly filePath: string;
53 readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
54 readonly close: () => Effect.Effect<void>;
56​
57export interface EventNdjsonLogStore {
58 readonly filePath: string;
59 readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;
60 readonly close: () => Effect.Effect<void>;
62​
63export interface EventNdjsonLogStoreOptions {
64 readonly maxBytes?: number;
65 readonly maxFiles?: number;
66 readonly batchWindowMs?: number;
67 readonly maxTotalBytes?: number;
68 readonly maxAgeMs?: number;
69 readonly retentionCheckIntervalMs?: number;
70 readonly maxBufferedBytes?: number;
71 readonly maxBufferedRecords?: number;
72 readonly attribution?: ResourceAttribution["Service"];
74​
75export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
76 readonly stream: EventNdjsonStream;
78​
79export class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(
80 "EventNdjsonLogConfigurationError",
81 {
82 filePath: Schema.String,
83 option: Schema.String,
84 value: Schema.Number,
85 minimum: Schema.Number,
86 },
87) {
88 override get message(): string {
89 return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
90 }
92​
93export class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(
94 "EventNdjsonLogDirectoryError",
95 {
96 directory: Schema.String,
97 cause: Schema.Defect(),
98 },
99) {
100 override get message(): string {
101 return `Failed to create provider event log directory '${this.directory}'`;
102 }
104​
105export type EventNdjsonLogStoreError =
106 | EventNdjsonLogConfigurationError
107 | EventNdjsonLogDirectoryError;
108​
109interface ResolvedOptions {
110 readonly maxBytes: number;
111 readonly maxFiles: number;
112 readonly batchWindowMs: number;
113 readonly maxTotalBytes: number;
114 readonly maxAgeMs: number;
115 readonly retentionCheckIntervalMs: number;
116 readonly maxBufferedBytes: number;
117 readonly maxBufferedRecords: number;
118 readonly attribution: ResourceAttribution["Service"] | undefined;
120​
121export interface PendingRecord {
122 readonly stream: EventNdjsonStream;
123 readonly threadSegment: string;
124 readonly line: string;
125 readonly bytes: number;
127​
128interface StoreState {
129 readonly pending: ReadonlyArray<PendingRecord>;
130 readonly pendingBytes: number;
131 readonly sinks: ReadonlyMap<string, RotatingFileSink>;
132 readonly flushScheduled: boolean;
133 readonly closed: boolean;
134 readonly lastRetentionAt: number;
136​
137interface AttributionSummary {
138 readonly stream: EventNdjsonStream;
139 readonly count: number;
140 readonly logicalWriteBytes: number;
142​
143interface FileOperationFailure {
144 readonly filePath: string;
145 readonly cause: unknown;
147​
148interface RetentionResult {
149 readonly failures: ReadonlyArray<FileOperationFailure>;
151​
152interface DrainResult {
153 readonly attributions: ReadonlyArray<AttributionSummary>;
154 readonly failures: ReadonlyArray<FileOperationFailure>;
156​
157function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
158 return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
160​
161function resolveThreadSegment(raw: string | null | undefined): string {
162 const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
163 return normalized ?? GLOBAL_THREAD_SEGMENT;
165​
166function resolveStreamLabel(stream: EventNdjsonStream): string {
167 return stream === "native" ? "NTIVE" : stream === "orchestration" ? "ORCH" : "CANON";
169​
170function providerLogPrefix(filePath: string): string {
171 const basename = NodePath.basename(filePath);
172 const extension = NodePath.extname(basename);
173 return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;
175​
176function providerLogPath(directory: string, prefix: string, threadSegment: string): string {
177 return NodePath.join(directory, `${prefix}${threadSegment}.log`);
179​
180function shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {
181 if (stream !== "canonical" || typeof event !== "object" || event === null) {
182 return true;
183 }
184 try {
185 const type = Reflect.get(event, "type");
186 return typeof type !== "string" || !transientCanonicalEventTypes.has(type);
187 } catch {
188 return true;
189 }
191​
192export function writeBatchedMessages(
193 sink: Pick<RotatingFileSink, "write">,
194 records: ReadonlyArray<PendingRecord>,
195 maxBytes: number,
196 onWritten: (records: ReadonlyArray<PendingRecord>) => void,
197): void {
198 let pendingRecords: Array<PendingRecord> = [];
199 let pendingBytes = 0;
200​
201 const flush = () => {
202 if (pendingRecords.length === 0) return;
203 const writtenRecords = pendingRecords;
204 sink.write(writtenRecords.map((record) => record.line).join(""));
205 onWritten(writtenRecords);
206 pendingRecords = [];
207 pendingBytes = 0;
208 };
209​
210 for (const record of records) {
211 if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
212 flush();
213 }
214 pendingRecords.push(record);
215 pendingBytes += record.bytes;
216 if (pendingBytes >= maxBytes) {
217 flush();
218 }
219 }
220 flush();
222​
223function isProviderLogFile(filePath: string, fileName: string, filePrefix: string): boolean {
224 if (!/\.log(?:\.\d+)?$/u.test(fileName)) return false;
225 if (fileName.startsWith(filePrefix)) return true;
226​
227 const descriptor = NodeFS.openSync(filePath, "r");
228 try {
229 const header = Buffer.alloc(256);
230 const bytesRead = NodeFS.readSync(descriptor, header, 0, header.byteLength, 0);
231 return /^\[[^\]\r\n]+\] (?:NTIVE|CANON|ORCH): /u.test(header.toString("utf8", 0, bytesRead));
232 } finally {
233 NodeFS.closeSync(descriptor);
234 }
236​
237function enforceRetention(input: {
238 readonly directory: string;
239 readonly maxTotalBytes: number;
240 readonly maxAgeMs: number;
241 readonly activeFilePaths: ReadonlySet<string>;
242 readonly filePrefix: string;
243 readonly now: number;
244}): RetentionResult {
245 const failures: Array<FileOperationFailure> = [];
246 const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
247​
248 let entries: ReadonlyArray<NodeFS.Dirent>;
249 try {
250 entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
251 } catch (cause) {
252 return { failures: [{ filePath: input.directory, cause }] };
253 }
254​
255 for (const entry of entries) {
256 if (!entry.isFile()) continue;
257 const filePath = NodePath.join(input.directory, entry.name);
258 try {
259 if (!isProviderLogFile(filePath, entry.name, input.filePrefix)) continue;
260 const stat = NodeFS.statSync(filePath);
261 files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
262 } catch (cause) {
263 failures.push({ filePath, cause });
264 }
265 }
266​
267 let totalBytes = files.reduce((total, file) => total + file.size, 0);
268 const remove = (file: (typeof files)[number]) => {
269 if (input.activeFilePaths.has(file.filePath)) return false;
270 try {
271 NodeFS.rmSync(file.filePath, { force: true });
272 totalBytes -= file.size;
273 return true;
274 } catch (cause) {
275 failures.push({ filePath: file.filePath, cause });
276 return false;
277 }
278 };
279​
280 const retained = files.filter((file) => {
281 if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
282 return !remove(file);
283 });
284​
285 for (const file of retained.toSorted(
286 (left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
287 )) {
288 if (totalBytes <= input.maxTotalBytes) break;
289 remove(file);
290 }
291​
292 return { failures };
294​
295function validateOption(input: {
296 readonly filePath: string;
297 readonly option: string;
298 readonly value: number;
299 readonly minimum: number;
300}): EventNdjsonLogConfigurationError | undefined {
301 if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
302 return new EventNdjsonLogConfigurationError(input);
304​
305function resolveOptions(
306 filePath: string,
307 options: EventNdjsonLogStoreOptions,
308): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {
309 const resolved = {
310 maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
311 maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
312 batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
313 maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
314 maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
315 retentionCheckIntervalMs:
316 options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
317 maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,
318 maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
319 attribution: options.attribution,
320 } satisfies ResolvedOptions;
321​
322 const validations = [
323 ["maxBytes", resolved.maxBytes, 1],
324 ["maxFiles", resolved.maxFiles, 1],
325 ["batchWindowMs", resolved.batchWindowMs, 0],
326 ["maxTotalBytes", resolved.maxTotalBytes, 1],
327 ["maxAgeMs", resolved.maxAgeMs, 1],
328 ["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
329 ["maxBufferedBytes", resolved.maxBufferedBytes, 1],
330 ["maxBufferedRecords", resolved.maxBufferedRecords, 1],
331 ] as const;
332​
333 for (const [option, value, minimum] of validations) {
334 const error = validateOption({ filePath, option, value, minimum });
335 if (error) return Effect.fail(error);
336 }
337 return Effect.succeed(resolved);
339​
340function drainPending(input: {
341 readonly directory: string;
342 readonly options: ResolvedOptions;
343 readonly state: StoreState;
344 readonly filePrefix: string;
345 readonly now: number;
346 readonly timerFired: boolean;
347 readonly close: boolean;
348}): readonly [DrainResult, StoreState] {
349 if (input.state.closed) {
350 return [{ attributions: [], failures: [] }, input.state];
351 }
352​
353 const sinks = new Map(input.state.sinks);
354 const failures: Array<FileOperationFailure> = [];
355 const attributionByStream = new Map<
356 EventNdjsonStream,
357 { count: number; logicalWriteBytes: number }
358 >();
359 const recordsBySegment = new Map<string, Array<PendingRecord>>();
360​
361 for (const record of input.state.pending) {
362 const records = recordsBySegment.get(record.threadSegment) ?? [];
363 records.push(record);
364 recordsBySegment.set(record.threadSegment, records);
365 }
366​
367 for (const [threadSegment, records] of recordsBySegment) {
368 const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);
369 let sink = sinks.get(threadSegment);
370 if (!sink) {
371 try {
372 sink = new RotatingFileSink({
373 filePath,
374 maxBytes: input.options.maxBytes,
375 maxFiles: input.options.maxFiles,
376 throwOnError: true,
377 });
378 sinks.set(threadSegment, sink);
379 } catch (cause) {
380 failures.push({ filePath, cause });
381 continue;
382 }
383 }
384​
385 try {
386 writeBatchedMessages(sink, records, input.options.maxBytes, (writtenRecords) => {
387 for (const record of writtenRecords) {
388 const current = attributionByStream.get(record.stream) ?? {
389 count: 0,
390 logicalWriteBytes: 0,
391 };
392 attributionByStream.set(record.stream, {
393 count: current.count + 1,
394 logicalWriteBytes: current.logicalWriteBytes + record.bytes,
395 });
396 }
397 });
398 } catch (cause) {
399 sinks.delete(threadSegment);
400 failures.push({ filePath, cause });
401 }
402 }
403​
404 const retentionDue =
405 input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
406 const retention = retentionDue
407 ? enforceRetention({
408 directory: input.directory,
409 maxTotalBytes: input.options.maxTotalBytes,
410 maxAgeMs: input.options.maxAgeMs,
411 activeFilePaths: new Set(
412 Array.from(sinks.keys(), (threadSegment) =>
413 providerLogPath(input.directory, input.filePrefix, threadSegment),
414 ),
415 ),
416 filePrefix: input.filePrefix,
417 now: input.now,
418 })
419 : { failures: [] };
420​
421 return [
422 {
423 attributions: Array.from(attributionByStream, ([stream, value]) => ({
424 stream,
425 ...value,
426 })),
427 failures: [...failures, ...retention.failures],
428 },
429 {
430 pending: [],
431 pendingBytes: 0,
432 sinks,
433 flushScheduled: input.timerFired ? false : input.state.flushScheduled,
434 closed: input.close,
435 lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
436 },
437 ];
439​
440const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
441 return yield* encodeUnknownJsonString(event).pipe(
442 Effect.catch((error) =>
443 logWarning("failed to serialize provider event log record", {
444 errorTag: errorTag(error),
445 }).pipe(Effect.as(undefined)),
446 ),
447 );
448});
449​
450export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
451 filePath: string,
452 options: EventNdjsonLogStoreOptions = {},
453): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
454 const resolved = yield* resolveOptions(filePath, options);
455 const directory = NodePath.dirname(filePath);
456 const filePrefix = providerLogPrefix(filePath);
457​
458 yield* Effect.try({
459 try: () => NodeFS.mkdirSync(directory, { recursive: true }),
460 catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
461 });
462​
463 const initializedAt = yield* Clock.currentTimeMillis;
464 const initialRetention = yield* Effect.sync(() =>
465 enforceRetention({
466 directory,
467 maxTotalBytes: resolved.maxTotalBytes,
468 maxAgeMs: resolved.maxAgeMs,
469 activeFilePaths: new Set(),
470 filePrefix,
471 now: initializedAt,
472 }),
473 );
474 for (const failure of initialRetention.failures) {
475 yield* logWarning("provider event log retention failed", {
476 filePath: failure.filePath,
477 errorTag: errorTag(failure.cause),
478 });
479 }
480​
481 const stateRef = yield* SynchronizedRef.make<StoreState>({
482 pending: [],
483 pendingBytes: 0,
484 sinks: new Map(),
485 flushScheduled: false,
486 closed: false,
487 lastRetentionAt: initializedAt,
488 });
489 const timerScope = yield* Scope.make();
490​
491 const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
492 const startedAt = yield* Clock.currentTimeMillis;
493 const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
494 Effect.sync(() =>
495 drainPending({
496 directory,
497 options: resolved,
498 state,
499 filePrefix,
500 now: startedAt,
501 timerFired,
502 close,
503 }),
504 ),
505 );
506​
507 for (const failure of result.failures) {
508 yield* logWarning("provider event log write or retention failed", {
509 filePath: failure.filePath,
510 errorTag: errorTag(failure.cause),
511 });
512 }
513​
514 if (resolved.attribution && result.attributions.length > 0) {
515 const completedAt = yield* Clock.currentTimeMillis;
516 const durationMs = Math.max(0, completedAt - startedAt);
517 const totalBytes = result.attributions.reduce(
518 (total, entry) => total + entry.logicalWriteBytes,
519 0,
520 );
521 yield* Effect.forEach(
522 result.attributions,
523 (entry) =>
524 resolved.attribution?.record({
525 component: "provider-event-log",
526 operation: `${entry.stream}.append`,
527 logicalWriteBytes: entry.logicalWriteBytes,
528 count: entry.count,
529 durationMs:
530 totalBytes === 0
531 ? 0
532 : Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
533 }) ?? Effect.void,
534 { discard: true },
535 );
536 }
537 });
538​
539 const scheduleFlush = Effect.fnUntraced(function* () {
540 yield* Effect.forkIn(
541 Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
542 timerScope,
543 { startImmediately: true },
544 );
545 });
546​
547 const close = Effect.fnUntraced(function* () {
548 yield* flush(false, true);
549 yield* Scope.close(timerScope, Exit.void);
550 });
551​
552 const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();
553 const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {
554 const existing = loggerViews.get(stream);
555 if (existing) return existing;
556​
557 const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
558 if (!shouldPersist(stream, event)) return;
559 const payload = yield* serializeEvent(event);
560 if (payload === undefined) return;
561​
562 const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
563 const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
564 const bytes = Buffer.byteLength(line);
565 const action = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
566 if (state.closed) {
567 return Effect.succeed([{ flush: false }, state] as const);
568 }
569 const pending = [
570 ...state.pending,
571 { stream, threadSegment: resolveThreadSegment(threadId), line, bytes },
572 ];
573 const pendingBytes = state.pendingBytes + bytes;
574 const flush =
575 resolved.batchWindowMs === 0 ||
576 pending.length >= resolved.maxBufferedRecords ||
577 pendingBytes >= resolved.maxBufferedBytes;
578 const schedule = !flush && !state.flushScheduled;
579 const nextState = {
580 ...state,
581 pending,
582 pendingBytes,
583 flushScheduled: state.flushScheduled || schedule,
584 };
585 return (schedule ? scheduleFlush() : Effect.void).pipe(
586 Effect.as([{ flush }, nextState] as const),
587 );
588 }).pipe(Effect.uninterruptible);
589​
590 if (action.flush) {
591 yield* flush(false, false);
592 }
593 });
594​
595 const view = { filePath, write, close: () => Effect.void } satisfies EventNdjsonLogger;
596 loggerViews.set(stream, view);
597 return view;
598 };
599​
600 return { filePath, logger, close } satisfies EventNdjsonLogStore;
601});
602​
603export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
604 filePath: string,
605 options: EventNdjsonLoggerOptions,
606): Effect.fn.Return<EventNdjsonLogger | undefined> {
607 const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
608 Effect.catch((error) =>
609 logWarning(error.message, { error }).pipe(
610 Effect.as<EventNdjsonLogStore | undefined>(undefined),
611 ),
612 ),
613 );
614 if (!store) return undefined;
615 return { ...store.logger(options.stream), close: store.close };
616});