Open History to see the last commit
1import { RotatingFileSink } from "@t3tools/shared/logging";
2import { Effect } from "effect";
3
4import type { TraceRecord } from "./TraceRecord.ts";
5
6const FLUSH_BUFFER_THRESHOLD = 32;
7
8export interface TraceSinkOptions {
9 readonly filePath: string;
10 readonly maxBytes: number;
11 readonly maxFiles: number;
12 readonly batchWindowMs: number;
13}
14
15export interface TraceSink {
16 readonly filePath: string;
17 push: (record: TraceRecord) => void;
18 flush: Effect.Effect<void>;
19 close: () => Effect.Effect<void>;
20}
21
22export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
23 const sink = new RotatingFileSink({
24 filePath: options.filePath,
25 maxBytes: options.maxBytes,
26 maxFiles: options.maxFiles,
27 });
28
29 let buffer: Array<string> = [];
30
31 const flushUnsafe = () => {
32 if (buffer.length === 0) {
33 return;
34 }
35
36 const chunk = buffer.join("");
37 buffer = [];
38
39 try {
40 sink.write(chunk);
41 } catch {
42 buffer.unshift(chunk);
43 }
44 };
45
46 const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false));
47
48 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
49 yield* Effect.forkScoped(
50 Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
51 );
52
53 return {
54 filePath: options.filePath,
55 push(record) {
56 try {
57 buffer.push(`${JSON.stringify(record)}\n`);
58 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
59 flushUnsafe();
60 }
61 } catch {
62 return;
63 }
64 },
65 flush,
66 close: () => flush,
67 } satisfies TraceSink;
68});