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

EventNdjsonLogger.ts

804 lines26.0 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 type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
13import { RotatingFileSink } from "@t3tools/shared/logging";
14import { errorTag } from "@t3tools/shared/observability";
15import * as Clock from "effect/Clock";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Schema from "effect/Schema";
20import * as Scope from "effect/Scope";
21import * as SynchronizedRef from "effect/SynchronizedRef";
22​
23import { toSafeThreadAttachmentSegment } from "../attachmentStore.ts";
24import type * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts";
25​
26const MEBIBYTE = 1024 * 1024;
27const DAY_MS = 24 * 60 * 60 * 1_000;
28const DEFAULT_MAX_BYTES = 10 * MEBIBYTE;
29const DEFAULT_MAX_FILES = 10;
30const DEFAULT_BATCH_WINDOW_MS = 1_000;
31const DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;
32const DEFAULT_MAX_AGE_MS = 14 * DAY_MS;
33const DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;
34const DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;
35const DEFAULT_MAX_BUFFERED_RECORDS = 512;
36const MAX_RECORD_CHARACTERS = 64 * 1024;
37const MAX_RECORD_FIELDS = 1_024;
38const MAX_RECORD_DEPTH = 16;
39const GLOBAL_THREAD_SEGMENT = "_global";
40const LOG_SCOPE = "provider-observability";
41const encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
42​
43const transientCanonicalEventTypes = new Set([
44 "content.delta",
45 "hook.progress",
46 "item.updated",
47 "task.progress",
48 "thread.realtime.audio.delta",
49 "tool.progress",
50 "turn.proposed.delta",
51]);
52const transientNativeMethods = new Set([
53 "item/agentMessage/delta",
54 "item/commandExecution/outputDelta",
55 "item/fileChange/outputDelta",
56 "item/plan/delta",
57 "item/reasoning/summaryTextDelta",
58 "item/reasoning/textDelta",
59 "thread/realtime/outputAudio/delta",
60 "thread/realtime/transcript/delta",
61 "turn/diff/updated",
62]);
63const transientAcpUpdates = new Set(["agent_message_chunk", "agent_thought_chunk"]);
64​
65export type EventNdjsonStream = "native" | "canonical" | "orchestration";
66​
67export interface EventNdjsonLogStore {
68 readonly filePath: string;
69 readonly logger: (stream: EventNdjsonStream) => ProviderEventLoggers.EventNdjsonLogger;
70 readonly close: () => Effect.Effect<void>;
72​
73export interface EventNdjsonLogStoreOptions {
74 readonly maxBytes?: number;
75 readonly maxFiles?: number;
76 readonly batchWindowMs?: number;
77 readonly maxTotalBytes?: number;
78 readonly maxAgeMs?: number;
79 readonly retentionCheckIntervalMs?: number;
80 readonly maxBufferedBytes?: number;
81 readonly maxBufferedRecords?: number;
82 readonly attribution?: ResourceAttribution.ResourceAttribution["Service"];
84​
85export interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {
86 readonly stream: EventNdjsonStream;
88​
89export class EventNdjsonLogConfigurationError extends Schema.TaggedError<EventNdjsonLogConfigurationError>()(
90 "EventNdjsonLogConfigurationError",
91 {
92 filePath: Schema.String,
93 option: Schema.String,
94 value: Schema.Number,
95 minimum: Schema.Number,
96 },
97) {
98 override get message(): string {
99 return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;
100 }
102​
103export class EventNdjsonLogDirectoryError extends Schema.TaggedError<EventNdjsonLogDirectoryError>()(
104 "EventNdjsonLogDirectoryError",
105 {
106 directory: Schema.String,
107 cause: Schema.Defect(),
108 },
109) {
110 override get message(): string {
111 return `Failed to create provider event log directory '${this.directory}'`;
112 }
114​
115export type EventNdjsonLogStoreError =
116 | EventNdjsonLogConfigurationError
117 | EventNdjsonLogDirectoryError;
118​
119interface ResolvedOptions {
120 readonly maxBytes: number;
121 readonly maxFiles: number;
122 readonly batchWindowMs: number;
123 readonly maxTotalBytes: number;
124 readonly maxAgeMs: number;
125 readonly retentionCheckIntervalMs: number;
126 readonly maxBufferedBytes: number;
127 readonly maxBufferedRecords: number;
128 readonly attribution: ResourceAttribution.ResourceAttribution["Service"] | undefined;
130​
131export interface PendingRecord {
132 readonly stream: EventNdjsonStream;
133 readonly threadSegment: string;
134 readonly line: string;
135 readonly bytes: number;
137​
138interface StoreState {
139 readonly pending: Array<PendingRecord>;
140 readonly pendingBytes: number;
141 readonly sinks: ReadonlyMap<string, RotatingFileSink>;
142 readonly flushScheduled: boolean;
143 readonly closed: boolean;
144 readonly lastRetentionAt: number;
146​
147interface AttributionSummary {
148 readonly stream: EventNdjsonStream;
149 readonly count: number;
150 readonly logicalWriteBytes: number;
152​
153interface FileOperationFailure {
154 readonly filePath: string;
155 readonly cause: unknown;
157​
158interface RetentionResult {
159 readonly failures: ReadonlyArray<FileOperationFailure>;
161​
162interface DrainResult {
163 readonly attributions: ReadonlyArray<AttributionSummary>;
164 readonly failures: ReadonlyArray<FileOperationFailure>;
166​
167function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
168 return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
170​
171function resolveThreadSegment(raw: string | null | undefined): string {
172 const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
173 return normalized ?? GLOBAL_THREAD_SEGMENT;
175​
176function resolveStreamLabel(stream: EventNdjsonStream): string {
177 return stream === "native" ? "NTIVE" : stream === "orchestration" ? "ORCH" : "CANON";
179​
180function providerLogPrefix(filePath: string): string {
181 const basename = NodePath.basename(filePath);
182 const extension = NodePath.extname(basename);
183 return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;
185​
186function providerLogPath(directory: string, prefix: string, threadSegment: string): string {
187 return NodePath.join(directory, `${prefix}${threadSegment}.log`);
189​
190export function shouldPersistProviderEvent(stream: EventNdjsonStream, event: unknown): boolean {
191 if (stream === "orchestration" || typeof event !== "object" || event === null) {
192 return true;
193 }
194 try {
195 const type = Reflect.get(event, "type");
196 if (typeof type === "string" && transientCanonicalEventTypes.has(type)) {
197 return false;
198 }
199 if (stream !== "native") return true;
200​
201 const nested = Reflect.get(event, "event");
202 const envelope = typeof nested === "object" && nested !== null ? nested : event;
203 // Decoded frames carry the same information as raw frames without another
204 // copy of every token delta. Decode failures have their own diagnostic frame.
205 if (Reflect.get(envelope, "stage") === "raw") return false;
206 const decodedPayload = Reflect.get(envelope, "payload");
207 const nativeEvent =
208 Reflect.get(envelope, "stage") === "decoded" &&
209 typeof decodedPayload === "object" &&
210 decodedPayload !== null
211 ? decodedPayload
212 : envelope;
213 const method = Reflect.get(nativeEvent, "method");
214 if (
215 typeof method === "string" &&
216 (transientNativeMethods.has(method) ||
217 method.startsWith("claude/stream_event/content_block_delta/"))
218 ) {
219 return false;
220 }
221​
222 const nativeType = Reflect.get(nativeEvent, "type");
223 if (nativeType === "message.part.delta") return false;
224 if (nativeType === "stream_event") {
225 const streamEvent = Reflect.get(nativeEvent, "event");
226 if (
227 typeof streamEvent === "object" &&
228 streamEvent !== null &&
229 Reflect.get(streamEvent, "type") === "content_block_delta"
230 ) {
231 return false;
232 }
233 }
234​
235 const payload = Reflect.get(nativeEvent, "payload");
236 if (typeof payload !== "object" || payload === null) return true;
237​
238 if (method === "session/update") {
239 const update = Reflect.get(payload, "update");
240 if (typeof update !== "object" || update === null) return true;
241 const updateType = Reflect.get(update, "sessionUpdate");
242 return typeof updateType !== "string" || !transientAcpUpdates.has(updateType);
243 }
244​
245 if (nativeType === "message.part.updated") {
246 const properties = Reflect.get(payload, "properties");
247 if (typeof properties !== "object" || properties === null) return true;
248 const part = Reflect.get(properties, "part");
249 if (typeof part !== "object" || part === null) return true;
250 const partType = Reflect.get(part, "type");
251 if (partType === "text" || partType === "reasoning") return false;
252 if (partType === "tool") {
253 // Running snapshots repeat growing output. Pending and terminal states stay in the log.
254 const state = Reflect.get(part, "state");
255 if (typeof state === "object" && state !== null) {
256 return Reflect.get(state, "status") !== "running";
257 }
258 }
259 return true;
260 }
261​
262 return true;
263 } catch {
264 return true;
265 }
267​
268const summaryFields = [
269 "provider",
270 "protocol",
271 "kind",
272 "providerSessionId",
273 "direction",
274 "stage",
275 "type",
276 "subtype",
277 "method",
278 "id",
279 "threadId",
280 "turnId",
281 "requestId",
282 "session_id",
283 "status",
284 "is_error",
285 "api_error_status",
286 "terminal_reason",
287 "stop_reason",
288 "operation",
289 "code",
290 "willRetry",
291 "message",
292 "event",
293 "payload",
294 "params",
295 "result",
296 "thread",
297 "turn",
298 "error",
299 "turns",
300 "items",
301 "content",
302] as const;
303​
304function summarizeProviderEvent(event: unknown): unknown {
305 let remainingFields = 128;
306 let remainingCharacters = 8 * 1024;
307 const summarize = (value: unknown, depth: number): unknown => {
308 if (typeof value === "string") {
309 if (value.length > Math.min(1_024, remainingCharacters)) {
310 return { omittedCharacters: value.length };
311 }
312 remainingCharacters -= value.length;
313 return value;
314 }
315 if (value === null || typeof value === "number" || typeof value === "boolean") return value;
316 if (typeof value !== "object") return undefined;
317 if (Array.isArray(value)) return { itemCount: value.length };
318 const summary: Record<string, unknown> = { truncated: true };
319 if (depth >= 6) return summary;
320 for (const key of summaryFields) {
321 if (remainingFields <= 0) break;
322 const nested = Reflect.get(value, key);
323 if (nested === undefined) continue;
324 remainingFields -= 1;
325 summary[key] = summarize(nested, depth + 1);
326 }
327 return summary;
328 };
329 try {
330 return summarize(event, 0);
331 } catch {
332 return { truncated: true };
333 }
335​
336/** Bounds traversal before adapters copy payloads or the logger encodes them. */
337export function boundProviderEventForLogging(event: unknown): unknown {
338 let remainingCharacters = MAX_RECORD_CHARACTERS;
339 let remainingFields = MAX_RECORD_FIELDS;
340 const ancestors = new WeakSet<object>();
341 const fits = (value: unknown, depth: number): boolean => {
342 if (typeof value === "string") {
343 remainingCharacters -= value.length;
344 return remainingCharacters >= 0;
345 }
346 if (typeof value !== "object" || value === null) return true;
347 if (depth > MAX_RECORD_DEPTH || ancestors.has(value)) return false;
348 if (Array.isArray(value) && value.length > remainingFields) return false;
349 ancestors.add(value);
350 for (const key in value) {
351 if (!Object.hasOwn(value, key)) continue;
352 remainingFields -= 1;
353 remainingCharacters -= key.length;
354 if (
355 remainingFields < 0 ||
356 remainingCharacters < 0 ||
357 !fits(Reflect.get(value, key), depth + 1)
358 )
359 return false;
360 }
361 ancestors.delete(value);
362 return true;
363 };
364 try {
365 if (fits(event, 0)) return event;
366 } catch {
367 // A failing accessor must not escape into provider processing.
368 }
369 return summarizeProviderEvent(event);
371​
372export function writeBatchedMessages(
373 sink: Pick<RotatingFileSink, "write">,
374 records: ReadonlyArray<PendingRecord>,
375 maxBytes: number,
376 onWritten: (records: ReadonlyArray<PendingRecord>) => void,
377): void {
378 let pendingRecords: Array<PendingRecord> = [];
379 let pendingBytes = 0;
380​
381 const flush = () => {
382 if (pendingRecords.length === 0) return;
383 const writtenRecords = pendingRecords;
384 sink.write(writtenRecords.map((record) => record.line).join(""));
385 onWritten(writtenRecords);
386 pendingRecords = [];
387 pendingBytes = 0;
388 };
389​
390 for (const record of records) {
391 if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {
392 flush();
393 }
394 pendingRecords.push(record);
395 pendingBytes += record.bytes;
396 if (pendingBytes >= maxBytes) {
397 flush();
398 }
399 }
400 flush();
402​
403function isProviderLogFile(filePath: string, fileName: string, filePrefix: string): boolean {
404 if (!/\.log(?:\.\d+)?$/u.test(fileName)) return false;
405 if (fileName.startsWith(filePrefix)) return true;
406​
407 const descriptor = NodeFS.openSync(filePath, "r");
408 try {
409 const header = Buffer.alloc(256);
410 const bytesRead = NodeFS.readSync(descriptor, header, 0, header.byteLength, 0);
411 return /^\[[^\]\r\n]+\] (?:NTIVE|CANON|ORCH): /u.test(header.toString("utf8", 0, bytesRead));
412 } finally {
413 NodeFS.closeSync(descriptor);
414 }
416​
417function enforceRetention(input: {
418 readonly directory: string;
419 readonly maxTotalBytes: number;
420 readonly maxAgeMs: number;
421 readonly activeFilePaths: ReadonlySet<string>;
422 readonly filePrefix: string;
423 readonly now: number;
424}): RetentionResult {
425 const failures: Array<FileOperationFailure> = [];
426 const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];
427​
428 let entries: ReadonlyArray<NodeFS.Dirent>;
429 try {
430 entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });
431 } catch (cause) {
432 return { failures: [{ filePath: input.directory, cause }] };
433 }
434​
435 for (const entry of entries) {
436 if (!entry.isFile()) continue;
437 const filePath = NodePath.join(input.directory, entry.name);
438 try {
439 if (!isProviderLogFile(filePath, entry.name, input.filePrefix)) continue;
440 const stat = NodeFS.statSync(filePath);
441 files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });
442 } catch (cause) {
443 failures.push({ filePath, cause });
444 }
445 }
446​
447 let totalBytes = files.reduce((total, file) => total + file.size, 0);
448 const remove = (file: (typeof files)[number]) => {
449 if (input.activeFilePaths.has(file.filePath)) return false;
450 try {
451 NodeFS.rmSync(file.filePath, { force: true });
452 totalBytes -= file.size;
453 return true;
454 } catch (cause) {
455 failures.push({ filePath: file.filePath, cause });
456 return false;
457 }
458 };
459​
460 const retained = files.filter((file) => {
461 if (input.now - file.mtimeMs <= input.maxAgeMs) return true;
462 return !remove(file);
463 });
464​
465 for (const file of retained.toSorted(
466 (left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),
467 )) {
468 if (totalBytes <= input.maxTotalBytes) break;
469 remove(file);
470 }
471​
472 return { failures };
474​
475function validateOption(input: {
476 readonly filePath: string;
477 readonly option: string;
478 readonly value: number;
479 readonly minimum: number;
480}): EventNdjsonLogConfigurationError | undefined {
481 if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;
482 return new EventNdjsonLogConfigurationError(input);
484​
485function resolveOptions(
486 filePath: string,
487 options: EventNdjsonLogStoreOptions,
488): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {
489 const resolved = {
490 maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
491 maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,
492 batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,
493 maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
494 maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
495 retentionCheckIntervalMs:
496 options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,
497 maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,
498 maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,
499 attribution: options.attribution,
500 } satisfies ResolvedOptions;
501​
502 const validations = [
503 ["maxBytes", resolved.maxBytes, 1],
504 ["maxFiles", resolved.maxFiles, 1],
505 ["batchWindowMs", resolved.batchWindowMs, 0],
506 ["maxTotalBytes", resolved.maxTotalBytes, 1],
507 ["maxAgeMs", resolved.maxAgeMs, 1],
508 ["retentionCheckIntervalMs", resolved.retentionCheckIntervalMs, 1],
509 ["maxBufferedBytes", resolved.maxBufferedBytes, 1],
510 ["maxBufferedRecords", resolved.maxBufferedRecords, 1],
511 ] as const;
512​
513 for (const [option, value, minimum] of validations) {
514 const error = validateOption({ filePath, option, value, minimum });
515 if (error) return Effect.fail(error);
516 }
517 return Effect.succeed(resolved);
519​
520function drainPending(input: {
521 readonly directory: string;
522 readonly options: ResolvedOptions;
523 readonly state: StoreState;
524 readonly filePrefix: string;
525 readonly now: number;
526 readonly timerFired: boolean;
527 readonly close: boolean;
528}): readonly [DrainResult, StoreState] {
529 if (input.state.closed) {
530 return [{ attributions: [], failures: [] }, input.state];
531 }
532​
533 const sinks = new Map(input.state.sinks);
534 const failures: Array<FileOperationFailure> = [];
535 const attributionByStream = new Map<
536 EventNdjsonStream,
537 { count: number; logicalWriteBytes: number }
538 >();
539 const recordsBySegment = new Map<string, Array<PendingRecord>>();
540​
541 for (const record of input.state.pending) {
542 const records = recordsBySegment.get(record.threadSegment) ?? [];
543 records.push(record);
544 recordsBySegment.set(record.threadSegment, records);
545 }
546​
547 for (const [threadSegment, records] of recordsBySegment) {
548 const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);
549 let sink = sinks.get(threadSegment);
550 if (!sink) {
551 try {
552 sink = new RotatingFileSink({
553 filePath,
554 maxBytes: input.options.maxBytes,
555 maxFiles: input.options.maxFiles,
556 throwOnError: true,
557 });
558 sinks.set(threadSegment, sink);
559 } catch (cause) {
560 failures.push({ filePath, cause });
561 continue;
562 }
563 }
564​
565 try {
566 writeBatchedMessages(sink, records, input.options.maxBytes, (writtenRecords) => {
567 for (const record of writtenRecords) {
568 const current = attributionByStream.get(record.stream) ?? {
569 count: 0,
570 logicalWriteBytes: 0,
571 };
572 attributionByStream.set(record.stream, {
573 count: current.count + 1,
574 logicalWriteBytes: current.logicalWriteBytes + record.bytes,
575 });
576 }
577 });
578 } catch (cause) {
579 sinks.delete(threadSegment);
580 failures.push({ filePath, cause });
581 }
582 }
583​
584 const retentionDue =
585 input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;
586 const retention = retentionDue
587 ? enforceRetention({
588 directory: input.directory,
589 maxTotalBytes: input.options.maxTotalBytes,
590 maxAgeMs: input.options.maxAgeMs,
591 activeFilePaths: new Set(
592 Array.from(sinks.keys(), (threadSegment) =>
593 providerLogPath(input.directory, input.filePrefix, threadSegment),
594 ),
595 ),
596 filePrefix: input.filePrefix,
597 now: input.now,
598 })
599 : { failures: [] };
600​
601 return [
602 {
603 attributions: Array.from(attributionByStream, ([stream, value]) => ({
604 stream,
605 ...value,
606 })),
607 failures: [...failures, ...retention.failures],
608 },
609 {
610 pending: [],
611 pendingBytes: 0,
612 sinks,
613 flushScheduled: input.timerFired ? false : input.state.flushScheduled,
614 closed: input.close,
615 lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,
616 },
617 ];
619​
620const serializeEvent = Effect.fnUntraced(function* (event: unknown) {
621 return yield* encodeUnknownJsonString(event).pipe(
622 Effect.catch((error) =>
623 logWarning("failed to serialize provider event log record", {
624 errorTag: errorTag(error),
625 }).pipe(Effect.as(undefined)),
626 ),
627 );
628});
629​
630export const makeEventNdjsonLogStore = Effect.fnUntraced(function* (
631 filePath: string,
632 options: EventNdjsonLogStoreOptions = {},
633): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {
634 const resolved = yield* resolveOptions(filePath, options);
635 const directory = NodePath.dirname(filePath);
636 const filePrefix = providerLogPrefix(filePath);
637​
638 yield* Effect.try({
639 try: () => NodeFS.mkdirSync(directory, { recursive: true }),
640 catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),
641 });
642​
643 const initializedAt = yield* Clock.currentTimeMillis;
644 const initialRetention = yield* Effect.sync(() =>
645 enforceRetention({
646 directory,
647 maxTotalBytes: resolved.maxTotalBytes,
648 maxAgeMs: resolved.maxAgeMs,
649 activeFilePaths: new Set(),
650 filePrefix,
651 now: initializedAt,
652 }),
653 );
654 for (const failure of initialRetention.failures) {
655 yield* logWarning("provider event log retention failed", {
656 filePath: failure.filePath,
657 errorTag: errorTag(failure.cause),
658 });
659 }
660​
661 const stateRef = yield* SynchronizedRef.make<StoreState>({
662 pending: [],
663 pendingBytes: 0,
664 sinks: new Map(),
665 flushScheduled: false,
666 closed: false,
667 lastRetentionAt: initializedAt,
668 });
669 const timerScope = yield* Scope.make();
670​
671 const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {
672 const startedAt = yield* Clock.currentTimeMillis;
673 const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
674 Effect.sync(() =>
675 drainPending({
676 directory,
677 options: resolved,
678 state,
679 filePrefix,
680 now: startedAt,
681 timerFired,
682 close,
683 }),
684 ),
685 );
686​
687 for (const failure of result.failures) {
688 yield* logWarning("provider event log write or retention failed", {
689 filePath: failure.filePath,
690 errorTag: errorTag(failure.cause),
691 });
692 }
693​
694 if (resolved.attribution && result.attributions.length > 0) {
695 const completedAt = yield* Clock.currentTimeMillis;
696 const durationMs = Math.max(0, completedAt - startedAt);
697 const totalBytes = result.attributions.reduce(
698 (total, entry) => total + entry.logicalWriteBytes,
699 0,
700 );
701 yield* Effect.forEach(
702 result.attributions,
703 (entry) =>
704 resolved.attribution?.record({
705 component: "provider-event-log",
706 operation: `${entry.stream}.append`,
707 logicalWriteBytes: entry.logicalWriteBytes,
708 count: entry.count,
709 durationMs:
710 totalBytes === 0
711 ? 0
712 : Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),
713 }) ?? Effect.void,
714 { discard: true },
715 );
716 }
717 });
718​
719 const scheduleFlush = Effect.fnUntraced(function* () {
720 yield* Effect.forkIn(
721 Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),
722 timerScope,
723 { startImmediately: true },
724 );
725 });
726​
727 const close = Effect.fnUntraced(function* () {
728 yield* flush(false, true);
729 yield* Scope.close(timerScope, Exit.void);
730 });
731​
732 const loggerViews = new Map<EventNdjsonStream, ProviderEventLoggers.EventNdjsonLogger>();
733 const logger = (stream: EventNdjsonStream): ProviderEventLoggers.EventNdjsonLogger => {
734 const existing = loggerViews.get(stream);
735 if (existing) return existing;
736​
737 const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {
738 if (!shouldPersistProviderEvent(stream, event)) return;
739 let payload = yield* serializeEvent(boundProviderEventForLogging(event));
740 if (payload === undefined) return;
741 // Escaping can expand strings beyond their input size. Keep that bounded
742 // serialization out of the file too, while retaining routing/error fields.
743 if (Buffer.byteLength(payload) > MAX_RECORD_CHARACTERS) {
744 payload = yield* serializeEvent(summarizeProviderEvent(event));
745 if (payload === undefined) return;
746 }
747​
748 const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
749 const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\n`;
750 const bytes = Buffer.byteLength(line);
751 const action = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
752 if (state.closed) {
753 return Effect.succeed([{ flush: false }, state] as const);
754 }
755 const pending = state.pending;
756 pending.push({ stream, threadSegment: resolveThreadSegment(threadId), line, bytes });
757 const pendingBytes = state.pendingBytes + bytes;
758 const flush =
759 resolved.batchWindowMs === 0 ||
760 pending.length >= resolved.maxBufferedRecords ||
761 pendingBytes >= resolved.maxBufferedBytes;
762 const schedule = !flush && !state.flushScheduled;
763 const nextState = {
764 ...state,
765 pending,
766 pendingBytes,
767 flushScheduled: state.flushScheduled || schedule,
768 };
769 return (schedule ? scheduleFlush() : Effect.void).pipe(
770 Effect.as([{ flush }, nextState] as const),
771 );
772 }).pipe(Effect.uninterruptible);
773​
774 if (action.flush) {
775 yield* flush(false, false);
776 }
777 });
778​
779 const view = {
780 filePath,
781 write,
782 close: () => Effect.void,
783 } satisfies ProviderEventLoggers.EventNdjsonLogger;
784 loggerViews.set(stream, view);
785 return view;
786 };
787​
788 return { filePath, logger, close } satisfies EventNdjsonLogStore;
789});
790​
791export const makeEventNdjsonLogger = Effect.fnUntraced(function* (
792 filePath: string,
793 options: EventNdjsonLoggerOptions,
794): Effect.fn.Return<ProviderEventLoggers.EventNdjsonLogger | undefined> {
795 const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(
796 Effect.catch((error) =>
797 logWarning(error.message, { error }).pipe(
798 Effect.as<EventNdjsonLogStore | undefined>(undefined),
799 ),
800 ),
801 );
802 if (!store) return undefined;
803 return { ...store.logger(options.stream), close: store.close };
804});