Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import fs from "node:fs";
3import path from "node:path";
4
5export interface RotatingFileSinkOptions {
6 readonly filePath: string;
7 readonly maxBytes: number;
8 readonly maxFiles: number;
9 readonly throwOnError?: boolean;
10}
11
12export class RotatingFileSink {
13 private readonly filePath: string;
14 private readonly maxBytes: number;
15 private readonly maxFiles: number;
16 private readonly throwOnError: boolean;
17 private currentSize = 0;
18
19 constructor(options: RotatingFileSinkOptions) {
20 if (options.maxBytes < 1) {
21 throw new Error(`maxBytes must be >= 1 (received ${options.maxBytes})`);
22 }
23 if (options.maxFiles < 1) {
24 throw new Error(`maxFiles must be >= 1 (received ${options.maxFiles})`);
25 }
26
27 this.filePath = options.filePath;
28 this.maxBytes = options.maxBytes;
29 this.maxFiles = options.maxFiles;
30 this.throwOnError = options.throwOnError ?? false;
31
32 fs.mkdirSync(path.dirname(this.filePath), { recursive: true });
33 this.pruneOverflowBackups();
34 this.currentSize = this.readCurrentSize();
35 }
36
37 write(chunk: string | Buffer): void {
38 const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
39 if (buffer.length === 0) return;
40
41 try {
42 if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {
43 this.rotate();
44 }
45
46 fs.appendFileSync(this.filePath, buffer);
47 this.currentSize += buffer.length;
48
49 if (this.currentSize > this.maxBytes) {
50 this.rotate();
51 }
52 } catch {
53 this.currentSize = this.readCurrentSize();
54 if (this.throwOnError) {
55 throw new Error(`Failed to write log chunk to ${this.filePath}`);
56 }
57 }
58 }
59
60 private rotate(): void {
61 try {
62 const oldest = this.withSuffix(this.maxFiles);
63 if (fs.existsSync(oldest)) {
64 fs.rmSync(oldest, { force: true });
65 }
66
67 for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
68 const source = this.withSuffix(index);
69 const target = this.withSuffix(index + 1);
70 if (fs.existsSync(source)) {
71 fs.renameSync(source, target);
72 }
73 }
74
75 if (fs.existsSync(this.filePath)) {
76 fs.renameSync(this.filePath, this.withSuffix(1));
77 }
78
79 this.currentSize = 0;
80 } catch {
81 this.currentSize = this.readCurrentSize();
82 if (this.throwOnError) {
83 throw new Error(`Failed to rotate log file ${this.filePath}`);
84 }
85 }
86 }
87
88 private pruneOverflowBackups(): void {
89 try {
90 const dir = path.dirname(this.filePath);
91 const baseName = path.basename(this.filePath);
92 for (const entry of fs.readdirSync(dir)) {
93 if (!entry.startsWith(`${baseName}.`)) continue;
94 const suffix = Number(entry.slice(baseName.length + 1));
95 if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
96 fs.rmSync(path.join(dir, entry), { force: true });
97 }
98 } catch {
99 if (this.throwOnError) {
100 throw new Error(`Failed to prune log backups for ${this.filePath}`);
101 }
102 }
103 }
104
105 private readCurrentSize(): number {
106 try {
107 return fs.statSync(this.filePath).size;
108 } catch {
109 return 0;
110 }
111 }
112
113 private withSuffix(index: number): string {
114 return `${this.filePath}.${index}`;
115 }
116}