Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5
6import { ThreadId } from "@t3tools/contracts";
7import { assert, describe, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Logger from "effect/Logger";
10import * as Schema from "effect/Schema";
11
12import { makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
13
14const encodeUnknownJson = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
15
16function parseLogLine(line: string) {
17 const match = /^\[([^\]]+)\] ([A-Z]+): (.+)$/.exec(line);
18 assert.notEqual(match, null);
19 if (!match) {
20 throw new Error(`invalid log line: ${line}`);
21 }
22 const observedAt = match[1];
23 const stream = match[2];
24 const payload = match[3];
25 if (!observedAt || !stream || payload === undefined) {
26 throw new Error(`invalid log line: ${line}`);
27 }
28 return {
29 observedAt,
30 stream,
31 payload,
32 };
33}
34
35describe("EventNdjsonLogger", () => {
36 it.effect("logs bounded diagnostics when an event cannot be serialized", () => {
37 const messages: Array<unknown> = [];
38 const logCapture = Logger.make<unknown, void>(({ message }) => {
39 if (Array.isArray(message)) {
40 messages.push(...message);
41 } else {
42 messages.push(message);
43 }
44 });
45 const secret = "secret-circular-event-value";
46
47 return Effect.gen(function* () {
48 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
49 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
50 const circular: Record<string, unknown> = { secret };
51 circular.self = circular;
52
53 try {
54 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
55 assert.exists(logger);
56 if (!logger) return;
57 yield* logger.write(circular, ThreadId.make("thread-1"));
58
59 const serialized = encodeUnknownJson(messages);
60 assert.notInclude(serialized, secret);
61 assert.include(serialized, '"errorTag":"SchemaError"');
62 } finally {
63 NodeFS.rmSync(tempDir, { recursive: true, force: true });
64 }
65 }).pipe(Effect.provide(Logger.layer([logCapture], { mergeWithExisting: false })));
66 });
67
68 it.effect("writes effect-style lines to thread-scoped files", () =>
69 Effect.gen(function* () {
70 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
71 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
72
73 try {
74 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" });
75 assert.notEqual(logger, undefined);
76 if (!logger) {
77 return;
78 }
79
80 yield* logger.write(
81 { threadId: "provider-thread-1", id: "evt-1" },
82 ThreadId.make("thread-1"),
83 );
84 yield* logger.write(
85 { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
86 ThreadId.make("thread-2"),
87 );
88 yield* logger.close();
89
90 const threadOnePath = NodePath.join(tempDir, "thread-1.log");
91 const threadTwoPath = NodePath.join(tempDir, "thread-2.log");
92 assert.equal(NodeFS.existsSync(threadOnePath), true);
93 assert.equal(NodeFS.existsSync(threadTwoPath), true);
94
95 const first = parseLogLine(NodeFS.readFileSync(threadOnePath, "utf8").trim());
96 const second = parseLogLine(NodeFS.readFileSync(threadTwoPath, "utf8").trim());
97
98 assert.equal(Number.isNaN(Date.parse(first.observedAt)), false);
99 assert.equal(first.stream, "NTIVE");
100 assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}');
101
102 assert.equal(Number.isNaN(Date.parse(second.observedAt)), false);
103 assert.equal(second.stream, "NTIVE");
104 assert.equal(
105 second.payload,
106 '{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}',
107 );
108 } finally {
109 NodeFS.rmSync(tempDir, { recursive: true, force: true });
110 }
111 }),
112 );
113
114 it.effect(
115 "falls back to a global segment when orchestration thread id is missing or invalid",
116 () =>
117 Effect.gen(function* () {
118 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
119 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
120
121 try {
122 const logger = yield* makeEventNdjsonLogger(basePath, { stream: "orchestration" });
123 assert.notEqual(logger, undefined);
124 if (!logger) {
125 return;
126 }
127
128 yield* logger.write({ id: "evt-no-thread" }, null);
129 yield* logger.write({ id: "evt-invalid-thread" }, "!!!" as unknown as ThreadId);
130 yield* logger.close();
131
132 const globalPath = NodePath.join(tempDir, "_global.log");
133 assert.equal(NodeFS.existsSync(globalPath), true);
134 const lines = NodeFS.readFileSync(globalPath, "utf8")
135 .trim()
136 .split("\n")
137 .map((line) => parseLogLine(line));
138 assert.equal(lines.length, 2);
139 assert.equal(Number.isNaN(Date.parse(lines[0]?.observedAt ?? "")), false);
140 assert.equal(Number.isNaN(Date.parse(lines[1]?.observedAt ?? "")), false);
141 assert.equal(lines[0]?.stream, "CANON");
142 assert.equal(lines[0]?.payload, '{"id":"evt-no-thread"}');
143 assert.equal(lines[1]?.stream, "CANON");
144 assert.equal(lines[1]?.payload, '{"id":"evt-invalid-thread"}');
145 } finally {
146 NodeFS.rmSync(tempDir, { recursive: true, force: true });
147 }
148 }),
149 );
150
151 it.effect("serializes concurrent first writes for the same segment", () =>
152 Effect.gen(function* () {
153 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
154 const basePath = NodePath.join(tempDir, "provider-canonical.ndjson");
155
156 try {
157 const logger = yield* makeEventNdjsonLogger(basePath, {
158 stream: "canonical",
159 batchWindowMs: 0,
160 });
161 assert.notEqual(logger, undefined);
162 if (!logger) {
163 return;
164 }
165
166 yield* Effect.all(
167 [
168 logger.write({ id: "evt-concurrent-1" }, null),
169 logger.write({ id: "evt-concurrent-2" }, null),
170 ],
171 { concurrency: "unbounded" },
172 );
173 yield* logger.close();
174
175 const globalPath = NodePath.join(tempDir, "_global.log");
176 assert.equal(NodeFS.existsSync(globalPath), true);
177 const lines = NodeFS.readFileSync(globalPath, "utf8")
178 .trim()
179 .split("\n")
180 .map((line) => parseLogLine(line));
181
182 assert.equal(lines.length, 2);
183 assert.deepEqual(lines.map((line) => line.payload).toSorted(), [
184 '{"id":"evt-concurrent-1"}',
185 '{"id":"evt-concurrent-2"}',
186 ]);
187 } finally {
188 NodeFS.rmSync(tempDir, { recursive: true, force: true });
189 }
190 }),
191 );
192
193 it.effect("rotates per-thread files when max size is exceeded", () =>
194 Effect.gen(function* () {
195 const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-"));
196 const basePath = NodePath.join(tempDir, "provider-native.ndjson");
197
198 try {
199 const logger = yield* makeEventNdjsonLogger(basePath, {
200 stream: "native",
201 maxBytes: 120,
202 maxFiles: 2,
203 });
204 assert.notEqual(logger, undefined);
205 if (!logger) {
206 return;
207 }
208
209 for (let index = 0; index < 10; index += 1) {
210 yield* logger.write(
211 {
212 threadId: "provider-thread-rotate",
213 id: `evt-${index}`,
214 payload: "x".repeat(40),
215 },
216 ThreadId.make("thread-rotate"),
217 );
218 }
219 yield* logger.close();
220
221 const fileStem = "thread-rotate.log";
222 const matchingFiles = NodeFS.readdirSync(tempDir)
223 .filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
224 .toSorted();
225
226 assert.equal(
227 matchingFiles.some((entry) => entry === `${fileStem}.1`),
228 true,
229 );
230 assert.equal(
231 matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
232 true,
233 );
234 assert.equal(
235 matchingFiles.some((entry) => entry === `${fileStem}.3`),
236 false,
237 );
238 } finally {
239 NodeFS.rmSync(tempDir, { recursive: true, force: true });
240 }
241 }),
242 );
243});