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

EventNdjsonLogger.test.ts

166 lines5.5 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.makeUnsafe("thread-1"),
46 );
47 yield* logger.write(
48 { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" },
49 ThreadId.makeUnsafe("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("rotates per-thread files when max size is exceeded", () =>
116 Effect.gen(function* () {
117 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-"));
118 const basePath = path.join(tempDir, "provider-native.ndjson");
119​
120 try {
121 const logger = yield* makeEventNdjsonLogger(basePath, {
122 stream: "native",
123 maxBytes: 120,
124 maxFiles: 2,
125 });
126 assert.notEqual(logger, undefined);
127 if (!logger) {
128 return;
129 }
130​
131 for (let index = 0; index < 10; index += 1) {
132 yield* logger.write(
133 {
134 threadId: "provider-thread-rotate",
135 id: `evt-${index}`,
136 payload: "x".repeat(40),
137 },
138 ThreadId.makeUnsafe("thread-rotate"),
139 );
140 }
141 yield* logger.close();
142​
143 const fileStem = "thread-rotate.log";
144 const matchingFiles = fs
145 .readdirSync(tempDir)
146 .filter((entry) => entry === fileStem || entry.startsWith(`${fileStem}.`))
147 .toSorted();
148​
149 assert.equal(
150 matchingFiles.some((entry) => entry === `${fileStem}.1`),
151 true,
152 );
153 assert.equal(
154 matchingFiles.some((entry) => entry === fileStem || entry === `${fileStem}.2`),
155 true,
156 );
157 assert.equal(
158 matchingFiles.some((entry) => entry === `${fileStem}.3`),
159 false,
160 );
161 } finally {
162 fs.rmSync(tempDir, { recursive: true, force: true });
163 }
164 }),
165 );
166});