[codex] Structure rotating log sink errors (#3279)

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex authored and GitHub committed 2026-06-20 15:24:38 -07:00
1 parent 90f1936fad
commit e042c25f56
2 files changed
+235 -14

No files matched your search

+151
View File
@@ -0,0 +1,151 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { afterEach, describe, expect, it } from "vite-plus/test";
import {
RotatingFileSink,
RotatingFileSinkConfigurationError,
RotatingFileSinkError,
} from "./logging.ts";
const tempDirectories: string[] = [];
const makeTempDirectory = (): string => {
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-logging-"));
tempDirectories.push(directory);
return directory;
};
const captureError = (run: () => unknown): unknown => {
try {
run();
} catch (cause) {
return cause;
}
throw new Error("Expected operation to throw");
};
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
NodeFS.rmSync(directory, { recursive: true, force: true });
}
});
describe("RotatingFileSink", () => {
it.each([
{ option: "maxBytes" as const, maxBytes: 0, maxFiles: 1 },
{ option: "maxFiles" as const, maxBytes: 1, maxFiles: 0 },
])("reports invalid $option configuration structurally", (input) => {
const thrown = captureError(
() =>
new RotatingFileSink({
filePath: "/unused/log.ndjson",
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
}),
);
expect(thrown).toBeInstanceOf(RotatingFileSinkConfigurationError);
expect(thrown).toMatchObject({
option: input.option,
received: 0,
minimum: 1,
});
expect((thrown as Error).message).toBe(`${input.option} must be >= 1 (received 0)`);
});
it("preserves directory initialization failures", () => {
const directory = makeTempDirectory();
const parentFile = NodePath.join(directory, "not-a-directory");
const filePath = NodePath.join(parentFile, "log.ndjson");
NodeFS.writeFileSync(parentFile, "occupied");
const thrown = captureError(() => new RotatingFileSink({ filePath, maxBytes: 1, maxFiles: 1 }));
expect(thrown).toBeInstanceOf(RotatingFileSinkError);
expect(thrown).toMatchObject({ operation: "initialize", filePath });
expect((thrown as RotatingFileSinkError).cause).toBeInstanceOf(Error);
});
it("only treats a missing log file as an empty current size", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "a".repeat(300));
const thrown = captureError(() => new RotatingFileSink({ filePath, maxBytes: 1, maxFiles: 1 }));
expect(thrown).toBeInstanceOf(RotatingFileSinkError);
expect(thrown).toMatchObject({ operation: "read", filePath });
expect((thrown as RotatingFileSinkError).cause).toMatchObject({ code: "ENAMETOOLONG" });
});
it("starts an absent log file at zero bytes", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "log.ndjson");
const sink = new RotatingFileSink({ filePath, maxBytes: 100, maxFiles: 1 });
sink.write("entry");
expect(NodeFS.readFileSync(filePath, "utf8")).toBe("entry");
});
it("preserves write failures", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "log.ndjson");
NodeFS.mkdirSync(filePath);
const sink = new RotatingFileSink({
filePath,
maxBytes: Number.MAX_SAFE_INTEGER,
maxFiles: 1,
throwOnError: true,
});
const thrown = captureError(() => sink.write("entry"));
expect(thrown).toBeInstanceOf(RotatingFileSinkError);
expect(thrown).toMatchObject({ operation: "write", filePath });
expect((thrown as RotatingFileSinkError).cause).toMatchObject({ code: "EISDIR" });
});
it("preserves rotation failures without an artificial write wrapper", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "log.ndjson");
NodeFS.writeFileSync(filePath, "a");
NodeFS.mkdirSync(`${filePath}.1`);
const sink = new RotatingFileSink({
filePath,
maxBytes: 1,
maxFiles: 1,
throwOnError: true,
});
const thrown = captureError(() => sink.write("b"));
expect(thrown).toBeInstanceOf(RotatingFileSinkError);
expect(thrown).toMatchObject({ operation: "rotate", filePath });
expect((thrown as RotatingFileSinkError).cause).toBeInstanceOf(Error);
});
it("preserves backup pruning failures", () => {
const directory = makeTempDirectory();
const filePath = NodePath.join(directory, "log.ndjson");
const overflowBackup = `${filePath}.2`;
NodeFS.mkdirSync(overflowBackup);
NodeFS.writeFileSync(NodePath.join(overflowBackup, "entry"), "occupied");
const thrown = captureError(
() =>
new RotatingFileSink({
filePath,
maxBytes: 1,
maxFiles: 1,
throwOnError: true,
}),
);
expect(thrown).toBeInstanceOf(RotatingFileSinkError);
expect(thrown).toMatchObject({ operation: "prune", filePath });
expect((thrown as RotatingFileSinkError).cause).toBeInstanceOf(Error);
});
});
+84 -14
View File
@@ -1,6 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as Schema from "effect/Schema";
export interface RotatingFileSinkOptions {
readonly filePath: string;
@@ -9,6 +10,37 @@ export interface RotatingFileSinkOptions {
readonly throwOnError?: boolean;
}
export class RotatingFileSinkConfigurationError extends Schema.TaggedErrorClass<RotatingFileSinkConfigurationError>()(
"RotatingFileSinkConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
received: Schema.Number,
minimum: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= ${this.minimum} (received ${this.received})`;
}
}
export class RotatingFileSinkError extends Schema.TaggedErrorClass<RotatingFileSinkError>()(
"RotatingFileSinkError",
{
operation: Schema.Literals(["initialize", "read", "write", "rotate", "prune"]),
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} rotating log file ${this.filePath}`;
}
}
const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
const isFileNotFoundError = (cause: unknown): cause is NodeJS.ErrnoException =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
export class RotatingFileSink {
private readonly filePath: string;
private readonly maxBytes: number;
@@ -18,10 +50,18 @@ export class RotatingFileSink {
constructor(options: RotatingFileSinkOptions) {
if (options.maxBytes < 1) {
throw new Error(`maxBytes must be >= 1 (received ${options.maxBytes})`);
throw new RotatingFileSinkConfigurationError({
option: "maxBytes",
received: options.maxBytes,
minimum: 1,
});
}
if (options.maxFiles < 1) {
throw new Error(`maxFiles must be >= 1 (received ${options.maxFiles})`);
throw new RotatingFileSinkConfigurationError({
option: "maxFiles",
received: options.maxFiles,
minimum: 1,
});
}
this.filePath = options.filePath;
@@ -29,7 +69,15 @@ export class RotatingFileSink {
this.maxFiles = options.maxFiles;
this.throwOnError = options.throwOnError ?? false;
NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });
try {
NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });
} catch (cause) {
throw new RotatingFileSinkError({
operation: "initialize",
filePath: this.filePath,
cause,
});
}
this.pruneOverflowBackups();
this.currentSize = this.readCurrentSize();
}
@@ -49,11 +97,18 @@ export class RotatingFileSink {
if (this.currentSize > this.maxBytes) {
this.rotate();
}
} catch {
this.currentSize = this.readCurrentSize();
if (this.throwOnError) {
throw new Error(`Failed to write log chunk to ${this.filePath}`);
} catch (cause) {
if (isRotatingFileSinkError(cause)) {
throw cause;
}
if (this.throwOnError) {
throw new RotatingFileSinkError({
operation: "write",
filePath: this.filePath,
cause,
});
}
this.currentSize = this.readCurrentSize();
}
}
@@ -77,11 +132,15 @@ export class RotatingFileSink {
}
this.currentSize = 0;
} catch {
this.currentSize = this.readCurrentSize();
} catch (cause) {
if (this.throwOnError) {
throw new Error(`Failed to rotate log file ${this.filePath}`);
throw new RotatingFileSinkError({
operation: "rotate",
filePath: this.filePath,
cause,
});
}
this.currentSize = this.readCurrentSize();
}
}
@@ -95,9 +154,13 @@ export class RotatingFileSink {
if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
NodeFS.rmSync(NodePath.join(dir, entry), { force: true });
}
} catch {
} catch (cause) {
if (this.throwOnError) {
throw new Error(`Failed to prune log backups for ${this.filePath}`);
throw new RotatingFileSinkError({
operation: "prune",
filePath: this.filePath,
cause,
});
}
}
}
@@ -105,8 +168,15 @@ export class RotatingFileSink {
private readCurrentSize(): number {
try {
return NodeFS.statSync(this.filePath).size;
} catch {
return 0;
} catch (cause) {
if (isFileNotFoundError(cause)) {
return 0;
}
throw new RotatingFileSinkError({
operation: "read",
filePath: this.filePath,
cause,
});
}
}