Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as Schema from "effect/Schema";
5
6export interface RotatingFileSinkOptions {
7 readonly filePath: string;
8 readonly maxBytes: number;
9 readonly maxFiles: number;
10 readonly throwOnError?: boolean;
11}
12
13export class RotatingFileSinkConfigurationError extends Schema.TaggedErrorClass<RotatingFileSinkConfigurationError>()(
14 "RotatingFileSinkConfigurationError",
15 {
16 option: Schema.Literals(["maxBytes", "maxFiles"]),
17 received: Schema.Number,
18 minimum: Schema.Number,
19 },
20) {
21 override get message(): string {
22 return `${this.option} must be >= ${this.minimum} (received ${this.received})`;
23 }
24}
25
26export class RotatingFileSinkError extends Schema.TaggedErrorClass<RotatingFileSinkError>()(
27 "RotatingFileSinkError",
28 {
29 operation: Schema.Literals(["initialize", "read", "write", "rotate", "prune"]),
30 filePath: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return `Failed to ${this.operation} rotating log file ${this.filePath}`;
36 }
37}
38
39const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
40
41const isFileNotFoundError = (cause: unknown): cause is NodeJS.ErrnoException =>
42 cause instanceof Error && "code" in cause && cause.code === "ENOENT";
43
44export class RotatingFileSink {
45 private readonly filePath: string;
46 private readonly maxBytes: number;
47 private readonly maxFiles: number;
48 private readonly throwOnError: boolean;
49 private currentSize = 0;
50
51 constructor(options: RotatingFileSinkOptions) {
52 if (options.maxBytes < 1) {
53 throw new RotatingFileSinkConfigurationError({
54 option: "maxBytes",
55 received: options.maxBytes,
56 minimum: 1,
57 });
58 }
59 if (options.maxFiles < 1) {
60 throw new RotatingFileSinkConfigurationError({
61 option: "maxFiles",
62 received: options.maxFiles,
63 minimum: 1,
64 });
65 }
66
67 this.filePath = options.filePath;
68 this.maxBytes = options.maxBytes;
69 this.maxFiles = options.maxFiles;
70 this.throwOnError = options.throwOnError ?? false;
71
72 try {
73 NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });
74 } catch (cause) {
75 throw new RotatingFileSinkError({
76 operation: "initialize",
77 filePath: this.filePath,
78 cause,
79 });
80 }
81 this.pruneOverflowBackups();
82 this.currentSize = this.readCurrentSize();
83 }
84
85 write(chunk: string | Buffer): void {
86 const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
87 if (buffer.length === 0) return;
88
89 try {
90 if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {
91 this.rotate();
92 }
93
94 NodeFS.appendFileSync(this.filePath, buffer);
95 this.currentSize += buffer.length;
96
97 if (this.currentSize > this.maxBytes) {
98 this.rotate();
99 }
100 } catch (cause) {
101 if (isRotatingFileSinkError(cause)) {
102 throw cause;
103 }
104 if (this.throwOnError) {
105 throw new RotatingFileSinkError({
106 operation: "write",
107 filePath: this.filePath,
108 cause,
109 });
110 }
111 this.currentSize = this.readCurrentSize();
112 }
113 }
114
115 private rotate(): void {
116 try {
117 const oldest = this.withSuffix(this.maxFiles);
118 if (NodeFS.existsSync(oldest)) {
119 NodeFS.rmSync(oldest, { force: true });
120 }
121
122 for (let index = this.maxFiles - 1; index >= 1; index -= 1) {
123 const source = this.withSuffix(index);
124 const target = this.withSuffix(index + 1);
125 if (NodeFS.existsSync(source)) {
126 NodeFS.renameSync(source, target);
127 }
128 }
129
130 if (NodeFS.existsSync(this.filePath)) {
131 NodeFS.renameSync(this.filePath, this.withSuffix(1));
132 }
133
134 this.currentSize = 0;
135 } catch (cause) {
136 if (this.throwOnError) {
137 throw new RotatingFileSinkError({
138 operation: "rotate",
139 filePath: this.filePath,
140 cause,
141 });
142 }
143 this.currentSize = this.readCurrentSize();
144 }
145 }
146
147 private pruneOverflowBackups(): void {
148 try {
149 const dir = NodePath.dirname(this.filePath);
150 const baseName = NodePath.basename(this.filePath);
151 for (const entry of NodeFS.readdirSync(dir)) {
152 if (!entry.startsWith(`${baseName}.`)) continue;
153 const suffix = Number(entry.slice(baseName.length + 1));
154 if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;
155 NodeFS.rmSync(NodePath.join(dir, entry), { force: true });
156 }
157 } catch (cause) {
158 if (this.throwOnError) {
159 throw new RotatingFileSinkError({
160 operation: "prune",
161 filePath: this.filePath,
162 cause,
163 });
164 }
165 }
166 }
167
168 private readCurrentSize(): number {
169 try {
170 return NodeFS.statSync(this.filePath).size;
171 } catch (cause) {
172 if (isFileNotFoundError(cause)) {
173 return 0;
174 }
175 throw new RotatingFileSinkError({
176 operation: "read",
177 filePath: this.filePath,
178 cause,
179 });
180 }
181 }
182
183 private withSuffix(index: number): string {
184 return `${this.filePath}.${index}`;
185 }
186}