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

EventNdjsonLogger.test.ts

209 lines6.8 KB

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