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

logging.test.ts

111 lines4.2 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import { afterEach, describe, expect, it } from "vite-plus/test";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { it as effectIt } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10​
11import { RotatingFileSink, makeAsyncRotatingFileSink } from "./logging.ts";
12​
13const tempDirectories: string[] = [];
14​
15const makeTempDirectory = (): string => {
16 const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-logging-"));
17 tempDirectories.push(directory);
18 return directory;
19};
20​
21const captureError = (run: () => unknown): unknown => {
22 try {
23 run();
24 } catch (cause) {
25 return cause;
26 }
27 throw new Error("Expected operation to throw");
28};
29​
30afterEach(() => {
31 for (const directory of tempDirectories.splice(0)) {
32 NodeFS.rmSync(directory, { recursive: true, force: true });
33 }
34});
35​
36effectIt.layer(NodeServices.layer)("asynchronous rotating file sink", (it) => {
37 it.effect("serializes concurrent appends across rotation and resumes an existing file", () =>
38 Effect.gen(function* () {
39 const directory = makeTempDirectory();
40 const filePath = NodePath.join(directory, "async.log");
41 NodeFS.writeFileSync(`${filePath}.50`, "obsolete");
42 const lines = Array.from(
43 { length: 100 },
44 (_, index) => `${index.toString().padStart(3, "0")}\n`,
45 );
46 const sink = yield* makeAsyncRotatingFileSink({ filePath, maxBytes: 32, maxFiles: 20 });
47 yield* Effect.forEach(lines, (line) => sink.write(line), {
48 concurrency: "unbounded",
49 discard: true,
50 });
51 const resumed = yield* makeAsyncRotatingFileSink({ filePath, maxBytes: 32, maxFiles: 20 });
52 yield* resumed.write("100\n");
53 expect(NodeFS.existsSync(`${filePath}.50`)).toBe(false);
54 const backups = NodeFS.readdirSync(directory)
55 .filter((name) => name.startsWith("async.log."))
56 .sort((a, b) => Number(b.slice(10)) - Number(a.slice(10)));
57 const contents = [...backups, "async.log"].map((name) =>
58 NodeFS.readFileSync(NodePath.join(directory, name), "utf8"),
59 );
60 expect(contents.every((chunk) => Buffer.byteLength(chunk) <= 32)).toBe(true);
61 expect(contents.join("")).toBe(lines.join("") + "100\n");
62 }),
63 );
64​
65 it.effect("reports a failed append and recovers its size before the next rotation", () =>
66 Effect.gen(function* () {
67 const directory = makeTempDirectory();
68 const filePath = NodePath.join(directory, "recovery.log");
69 NodeFS.writeFileSync(filePath, "old\n");
70 const fs = yield* FileSystem.FileSystem;
71 let attempts = 0;
72 const sink = yield* makeAsyncRotatingFileSink({ filePath, maxBytes: 8, maxFiles: 2 }).pipe(
73 Effect.provideService(FileSystem.FileSystem, {
74 ...fs,
75 writeFile: (path, bytes, options) =>
76 ++attempts === 1
77 ? fs.writeFile(directory, bytes, options)
78 : fs.writeFile(path, bytes, options),
79 }),
80 );
81 const failed = yield* sink.write("new\n").pipe(Effect.result);
82 expect(failed._tag).toBe("Failure");
83 if (failed._tag === "Failure") expect(failed.failure.operation).toBe("write");
84 yield* sink.write("new\n");
85 yield* sink.write("end\n");
86 expect(NodeFS.readFileSync(`${filePath}.1`, "utf8")).toBe("old\nnew\n");
87 expect(NodeFS.readFileSync(filePath, "utf8")).toBe("end\n");
88 }),
89 );
90});
91​
92describe("RotatingFileSink", () => {
93 it("never reports a rotation failure after successfully appending a chunk", () => {
94 const directory = makeTempDirectory();
95 const filePath = NodePath.join(directory, "log.ndjson");
96 NodeFS.mkdirSync(`${filePath}.1`);
97 const sink = new RotatingFileSink({
98 filePath,
99 maxBytes: 1,
100 maxFiles: 1,
101 throwOnError: true,
102 });
103​
104 sink.write("oversized");
105​
106 expect(NodeFS.readFileSync(filePath, "utf8")).toBe("oversized");
107 const thrown = captureError(() => sink.write("next"));
108 expect(thrown).toMatchObject({ operation: "rotate", filePath });
109 expect(NodeFS.readFileSync(filePath, "utf8")).toBe("oversized");
110 });
111});