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

EventNdjsonLogger.ts

291 lines8.2 KB

1/**
2 * Provider event logger helper.
3 *
4 * Best-effort writer for observability logs. Each record is formatted as a
5 * single effect-style text line in a thread-scoped file. Failures are
6 * downgraded to warnings so provider runtime behavior is unaffected.
7 */
8import fs from "node:fs";
9import path from "node:path";
10​
11import type { ThreadId } from "@t3tools/contracts";
12import { RotatingFileSink } from "@t3tools/shared/logging";
13import { Effect, Exit, Logger, Scope, SynchronizedRef } from "effect";
14​
15import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts";
16​
17const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
18const DEFAULT_MAX_FILES = 10;
19const DEFAULT_BATCH_WINDOW_MS = 200;
20const GLOBAL_THREAD_SEGMENT = "_global";
21const LOG_SCOPE = "provider-observability";
22​
23export type EventNdjsonStream = "native" | "canonical" | "orchestration";
24​
25export interface EventNdjsonLogger {
26 readonly filePath: string;
27 write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;
28 close: () => Effect.Effect<void>;
30​
31export interface EventNdjsonLoggerOptions {
32 readonly stream: EventNdjsonStream;
33 readonly maxBytes?: number;
34 readonly maxFiles?: number;
35 readonly batchWindowMs?: number;
37​
38interface ThreadWriter {
39 writeMessage: (message: string) => Effect.Effect<void>;
40 close: () => Effect.Effect<void>;
42​
43interface LoggerState {
44 readonly threadWriters: Map<string, ThreadWriter>;
45 readonly failedSegments: Set<string>;
47​
48function logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {
49 return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));
51​
52function resolveThreadSegment(raw: string | null | undefined): string {
53 const normalized = typeof raw === "string" ? toSafeThreadAttachmentSegment(raw) : null;
54 return normalized ?? GLOBAL_THREAD_SEGMENT;
56​
57function formatLoggerMessage(message: unknown): string {
58 if (Array.isArray(message)) {
59 return message.map((part) => (typeof part === "string" ? part : String(part))).join(" ");
60 }
61 return typeof message === "string" ? message : String(message);
63​
64function makeLineLogger(streamLabel: string): Logger.Logger<unknown, string> {
65 return Logger.make(
66 ({ date, message }) =>
67 `[${date.toISOString()}] ${streamLabel}: ${formatLoggerMessage(message)}\n`,
68 );
70​
71function resolveStreamLabel(stream: EventNdjsonStream): string {
72 switch (stream) {
73 case "native":
74 return "NTIVE";
75 case "canonical":
76 case "orchestration":
77 default:
78 return "CANON";
79 }
81​
82const toLogMessage = Effect.fn("toLogMessage")(function* (
83 event: unknown,
84): Effect.fn.Return<string | undefined> {
85 const serialized = yield* Effect.sync(() => {
86 try {
87 return { ok: true as const, value: JSON.stringify(event) };
88 } catch (error) {
89 return { ok: false as const, error };
90 }
91 });
92​
93 if (!serialized.ok) {
94 yield* logWarning("failed to serialize provider event log record", {
95 error: serialized.error,
96 });
97 return undefined;
98 }
99​
100 if (typeof serialized.value !== "string") {
101 return undefined;
102 }
103​
104 return serialized.value;
105});
106​
107const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
108 readonly filePath: string;
109 readonly maxBytes: number;
110 readonly maxFiles: number;
111 readonly batchWindowMs: number;
112 readonly streamLabel: string;
113}): Effect.fn.Return<ThreadWriter | undefined> {
114 const sinkResult = yield* Effect.sync(() => {
115 try {
116 return {
117 ok: true as const,
118 sink: new RotatingFileSink({
119 filePath: input.filePath,
120 maxBytes: input.maxBytes,
121 maxFiles: input.maxFiles,
122 throwOnError: true,
123 }),
124 };
125 } catch (error) {
126 return { ok: false as const, error };
127 }
128 });
129​
130 if (!sinkResult.ok) {
131 yield* logWarning("failed to initialize provider thread log file", {
132 filePath: input.filePath,
133 error: sinkResult.error,
134 });
135 return undefined;
136 }
137​
138 const sink = sinkResult.sink;
139 const scope = yield* Scope.make();
140 const lineLogger = makeLineLogger(input.streamLabel);
141 const batchedLogger = yield* Logger.batched(lineLogger, {
142 window: input.batchWindowMs,
143 flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
144 const flushResult = yield* Effect.sync(() => {
145 try {
146 for (const message of messages) {
147 sink.write(message);
148 }
149 return { ok: true as const };
150 } catch (error) {
151 return { ok: false as const, error };
152 }
153 });
154​
155 if (!flushResult.ok) {
156 yield* logWarning("provider event log batch flush failed", {
157 filePath: input.filePath,
158 error: flushResult.error,
159 });
160 }
161 }),
162 }).pipe(Effect.provideService(Scope.Scope, scope));
163​
164 const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
165​
166 return {
167 writeMessage(message: string) {
168 return Effect.log(message).pipe(Effect.provide(loggerLayer));
169 },
170 close() {
171 return Scope.close(scope, Exit.void);
172 },
173 } satisfies ThreadWriter;
174});
175​
176export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
177 filePath: string,
178 options: EventNdjsonLoggerOptions,
179): Effect.fn.Return<EventNdjsonLogger | undefined> {
180 const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
181 const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
182 const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
183 const streamLabel = resolveStreamLabel(options.stream);
184​
185 const directoryReady = yield* Effect.sync(() => {
186 try {
187 fs.mkdirSync(path.dirname(filePath), { recursive: true });
188 return true;
189 } catch (error) {
190 return { ok: false as const, error };
191 }
192 });
193 if (directoryReady !== true) {
194 yield* logWarning("failed to create provider event log directory", {
195 filePath,
196 error: directoryReady.error,
197 });
198 return undefined;
199 }
200​
201 const stateRef = yield* SynchronizedRef.make<LoggerState>({
202 threadWriters: new Map(),
203 failedSegments: new Set(),
204 });
205​
206 const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
207 threadSegment: string,
208 ): Effect.fn.Return<ThreadWriter | undefined> {
209 return yield* SynchronizedRef.modifyEffect(stateRef, (state) => {
210 if (state.failedSegments.has(threadSegment)) {
211 return Effect.succeed([undefined, state] as const);
212 }
213​
214 const existing = state.threadWriters.get(threadSegment);
215 if (existing) {
216 return Effect.succeed([existing, state] as const);
217 }
218​
219 return makeThreadWriter({
220 filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
221 maxBytes,
222 maxFiles,
223 batchWindowMs,
224 streamLabel,
225 }).pipe(
226 Effect.map((writer) => {
227 if (!writer) {
228 const nextFailedSegments = new Set(state.failedSegments);
229 nextFailedSegments.add(threadSegment);
230 return [
231 undefined,
232 {
233 ...state,
234 failedSegments: nextFailedSegments,
235 },
236 ] as const;
237 }
238​
239 const nextThreadWriters = new Map(state.threadWriters);
240 nextThreadWriters.set(threadSegment, writer);
241 return [
242 writer,
243 {
244 ...state,
245 threadWriters: nextThreadWriters,
246 },
247 ] as const;
248 }),
249 );
250 });
251 });
252​
253 const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
254 const threadSegment = resolveThreadSegment(threadId);
255 const message = yield* toLogMessage(event);
256 if (!message) {
257 return;
258 }
259​
260 const writer = yield* resolveThreadWriter(threadSegment);
261 if (!writer) {
262 return;
263 }
264​
265 yield* writer.writeMessage(message);
266 });
267​
268 const close = Effect.fn("close")(function* () {
269 yield* SynchronizedRef.modifyEffect(stateRef, (state) =>
270 Effect.gen(function* () {
271 for (const writer of state.threadWriters.values()) {
272 yield* writer.close();
273 }
274​
275 return [
276 undefined,
277 {
278 threadWriters: new Map<string, ThreadWriter>(),
279 failedSegments: new Set<string>(),
280 },
281 ] as const;
282 }),
283 );
284 });
285​
286 return {
287 filePath,
288 write,
289 close,
290 } satisfies EventNdjsonLogger;
291});