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

EventNdjsonLogger.ts

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