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

EventNdjsonLogger.ts

828 lines26.6 KB

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