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

logging.ts

407 lines13.6 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeFS from "node:fs";
3import * as NodePath from "node:path";
4import * as Schema from "effect/Schema";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Semaphore from "effect/Semaphore";
9​
10export interface RotatingFileSinkOptions {
11 readonly filePath: string;
12 readonly maxBytes: number;
13 readonly maxFiles: number;
14 readonly throwOnError?: boolean;
16​
17export class RotatingFileSinkConfigurationError extends Schema.TaggedError<RotatingFileSinkConfigurationError>()(
18 "RotatingFileSinkConfigurationError",
19 {
20 option: Schema.Literals(["maxBytes", "maxFiles"]),
21 received: Schema.Number,
22 minimum: Schema.Number,
23 },
24) {
25 override get message(): string {
26 return `${this.option} must be >= ${this.minimum} (received ${this.received})`;
27 }
29​
30export class RotatingFileSinkError extends Schema.TaggedError<RotatingFileSinkError>()(
31 "RotatingFileSinkError",
32 {
33 operation: Schema.Literals(["initialize", "read", "write", "rotate", "prune"]),
34 filePath: Schema.String,
35 cause: Schema.Defect(),
36 },
37) {
38 override get message(): string {
39 return `Failed to ${this.operation} rotating log file ${this.filePath}`;
40 }
42​
43const isRotatingFileSinkError = Schema.is(RotatingFileSinkError);
44​
45const isFileNotFoundError = (cause: unknown): cause is NodeJS.ErrnoException =>
46 cause instanceof Error && "code" in cause && cause.code === "ENOENT";
47​
48interface RotationFileSystem<E> {
49 exists(path: string): Effect.Effect<boolean, E>;
50 isDirectory(path: string): Effect.Effect<boolean, E>;
51 rename(source: string, target: string): Effect.Effect<void, E>;
52 remove(path: string): Effect.Effect<void, E>;
53 read(path: string): Effect.Effect<string, E>;
54 write(path: string, content: string): Effect.Effect<void, E>;
56​
57const RotationPlan = Schema.fromJsonString(
58 Schema.Struct({ oldest: Schema.Finite, backups: Schema.Array(Schema.Finite) }),
59);
60const decodeRotationPlan = Schema.decodeUnknownEffect(RotationPlan);
61const encodeRotationPlan = Schema.encodeEffect(RotationPlan);
62​
63const ROTATION_SUFFIX = ".rotating";
64​
65export function rotationSidecarBase(fileName: string): string | undefined {
66 const index = fileName.lastIndexOf(ROTATION_SUFFIX);
67 if (index < 0) return undefined;
68 const suffix = fileName.slice(index + ROTATION_SUFFIX.length);
69 if (suffix === "" || suffix === ".oldest" || suffix === ".json" || suffix === ".json.tmp") {
70 return fileName.slice(0, index);
71 }
73​
74function makeRotation<E>(fs: RotationFileSystem<E>, filePath: string, maxFiles: number) {
75 const backup = (index: number) => `${filePath}.${index}`;
76 const staged = filePath + ROTATION_SUFFIX;
77 const journal = `${staged}.json`;
78 const draft = `${journal}.tmp`;
79 const parked = `${staged}.oldest`;
80 const target = (index: number, oldest: number) => (index === oldest ? parked : backup(index + 1));
81​
82 const settle = Effect.gen(function* () {
83 if (!(yield* fs.exists(journal))) return true;
84 if (!(yield* fs.exists(staged))) {
85 // Publication committed. Cleanup may wait, but the parked slot cannot be reused yet.
86 return yield* Effect.andThen(fs.remove(parked), fs.remove(journal)).pipe(Effect.isSuccess);
87 }
88 const { oldest, backups } = yield* decodeRotationPlan(yield* fs.read(journal));
89 // Undo in reverse order. An occupied source means that move has not run or was already undone.
90 for (const index of [...backups].reverse()) {
91 const moved = target(index, oldest);
92 if (!(yield* fs.exists(backup(index))) && (yield* fs.exists(moved))) {
93 yield* fs.rename(moved, backup(index));
94 }
95 }
96 yield* fs.remove(journal);
97 return true;
98 });
99​
100 const publish = Effect.gen(function* () {
101 const backups: number[] = [];
102 for (let index = maxFiles; index >= 1; index--) {
103 const source = backup(index);
104 if (!(yield* fs.exists(source))) continue;
105 if (index === maxFiles && (yield* fs.isDirectory(source))) yield* fs.remove(source);
106 backups.push(index);
107 }
108 yield* fs.write(draft, yield* encodeRotationPlan({ oldest: maxFiles, backups }));
109 yield* fs.rename(draft, journal);
110 for (const index of backups) yield* fs.rename(backup(index), target(index, maxFiles));
111 yield* fs.rename(staged, backup(1));
112 return yield* settle;
113 });
114​
115 const restoreActive = Effect.gen(function* () {
116 if ((yield* fs.exists(staged)) && !(yield* fs.exists(filePath))) {
117 yield* fs.rename(staged, filePath);
118 }
119 });
120​
121 const recover = Effect.gen(function* () {
122 if (!(yield* settle)) return false;
123 if (!(yield* fs.exists(staged))) return true;
124 yield* fs.remove(draft);
125 if (yield* fs.exists(filePath)) return yield* publish;
126 yield* restoreActive;
127 return true;
128 });
129​
130 const rotate = Effect.gen(function* () {
131 if (!(yield* fs.exists(filePath))) return true;
132 // A denied active-file rename must leave the backups untouched.
133 yield* fs.rename(filePath, staged);
134 return yield* publish.pipe(
135 Effect.tapError(() =>
136 Effect.andThen(settle, Effect.andThen(fs.remove(draft), restoreActive)).pipe(Effect.ignore),
137 ),
138 );
139 });
140​
141 return { recover, rotate };
143​
144export class RotatingFileSink {
145 private readonly filePath: string;
146 private readonly maxBytes: number;
147 private readonly maxFiles: number;
148 private readonly throwOnError: boolean;
149 private readonly rotation: ReturnType<typeof makeRotation<RotatingFileSinkError>>;
150 private needsRecovery: boolean;
151 private currentSize = 0;
152​
153 constructor(options: RotatingFileSinkOptions) {
154 if (options.maxBytes < 1) {
155 throw new RotatingFileSinkConfigurationError({
156 option: "maxBytes",
157 received: options.maxBytes,
158 minimum: 1,
159 });
160 }
161 if (options.maxFiles < 1) {
162 throw new RotatingFileSinkConfigurationError({
163 option: "maxFiles",
164 received: options.maxFiles,
165 minimum: 1,
166 });
167 }
168​
169 this.filePath = options.filePath;
170 this.maxBytes = options.maxBytes;
171 this.maxFiles = options.maxFiles;
172 this.throwOnError = options.throwOnError ?? false;
173​
174 try {
175 NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });
176 } catch (cause) {
177 throw new RotatingFileSinkError({
178 operation: "initialize",
179 filePath: this.filePath,
180 cause,
181 });
182 }
183 const run = <A>(operation: () => A) =>
184 Effect.try({
185 try: operation,
186 catch: (cause) =>
187 new RotatingFileSinkError({ operation: "rotate", filePath: this.filePath, cause }),
188 });
189 this.rotation = makeRotation(
190 {
191 exists: (path) => Effect.sync(() => NodeFS.existsSync(path)),
192 isDirectory: (path) => run(() => NodeFS.lstatSync(path).isDirectory()),
193 rename: (source, target) => run(() => NodeFS.renameSync(source, target)),
194 remove: (path) => run(() => NodeFS.rmSync(path, { force: true })),
195 read: (path) => run(() => NodeFS.readFileSync(path, "utf8")),
196 write: (path, content) => run(() => NodeFS.writeFileSync(path, content)),
197 },
198 this.filePath,
199 this.maxFiles,
200 );
201 this.needsRecovery = Effect.runSync(
202 this.rotation.recover.pipe(
203 Effect.orElseSucceed(() => false),
204 Effect.map((ready) => !ready),
205 ),
206 );
207 if (!this.needsRecovery) this.pruneOverflowBackups();
208 this.currentSize = this.readCurrentSize();
209 }
210​
211 write(chunk: string | Buffer): void {
212 const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
213 if (buffer.length === 0) return;
214​
215 try {
216 if (this.needsRecovery) {
217 if (this.runRotation(this.rotation.recover)) this.pruneOverflowBackups();
218 this.currentSize = this.readCurrentSize();
219 }
220 if (
221 !this.needsRecovery &&
222 this.currentSize > 0 &&
223 this.currentSize + buffer.length > this.maxBytes
224 ) {
225 this.runRotation(this.rotation.rotate);
226 this.currentSize = this.readCurrentSize();
227 }
228​
229 NodeFS.appendFileSync(this.filePath, buffer);
230 this.currentSize += buffer.length;
231 } catch (cause) {
232 if (isRotatingFileSinkError(cause)) {
233 throw cause;
234 }
235 if (this.throwOnError) {
236 throw new RotatingFileSinkError({
237 operation: "write",
238 filePath: this.filePath,
239 cause,
240 });
241 }
242 this.currentSize = this.readCurrentSize();
243 }
244 }
245​
246 private runRotation(operation: typeof this.rotation.rotate): boolean {
247 try {
248 const ready = Effect.runSync(operation);
249 this.needsRecovery = !ready;
250 return ready;
251 } catch (cause) {
252 this.needsRecovery = true;
253 if (this.throwOnError) {
254 if (isRotatingFileSinkError(cause)) throw cause;
255 throw new RotatingFileSinkError({
256 operation: "rotate",
257 filePath: this.filePath,
258 cause,
259 });
260 }
261 return false;
262 }
263 }
264​
265 private pruneOverflowBackups(): void {
266 try {
267 const dir = NodePath.dirname(this.filePath);
268 const baseName = NodePath.basename(this.filePath);
269 for (const entry of NodeFS.readdirSync(dir)) {
270 if (!entry.startsWith(`${baseName}.`)) continue;
271 const suffixText = entry.slice(baseName.length + 1);
272 const suffix = Number(suffixText);
273 if (!Number.isInteger(suffix) || String(suffix) !== suffixText || suffix <= this.maxFiles)
274 continue;
275 NodeFS.rmSync(NodePath.join(dir, entry), { force: true });
276 }
277 } catch (cause) {
278 if (this.throwOnError) {
279 throw new RotatingFileSinkError({
280 operation: "prune",
281 filePath: this.filePath,
282 cause,
283 });
284 }
285 }
286 }
287​
288 private readCurrentSize(): number {
289 try {
290 return NodeFS.statSync(this.filePath).size;
291 } catch (cause) {
292 if (isFileNotFoundError(cause)) {
293 return 0;
294 }
295 throw new RotatingFileSinkError({
296 operation: "read",
297 filePath: this.filePath,
298 cause,
299 });
300 }
301 }
303​
304export const makeAsyncRotatingFileSink = Effect.fnUntraced(function* (
305 options: Omit<RotatingFileSinkOptions, "throwOnError">,
306) {
307 const fs = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 if (options.maxBytes < 1)
310 return yield* new RotatingFileSinkConfigurationError({
311 option: "maxBytes",
312 received: options.maxBytes,
313 minimum: 1,
314 });
315 if (options.maxFiles < 1)
316 return yield* new RotatingFileSinkConfigurationError({
317 option: "maxFiles",
318 received: options.maxFiles,
319 minimum: 1,
320 });
321 const failure = (operation: RotatingFileSinkError["operation"]) => (cause: unknown) =>
322 new RotatingFileSinkError({ operation, filePath: options.filePath, cause });
323 const directory = path.dirname(options.filePath);
324 const basename = path.basename(options.filePath);
325 yield* fs
326 .makeDirectory(directory, { recursive: true })
327 .pipe(Effect.mapError(failure("initialize")));
328 const rotation = makeRotation(
329 {
330 exists: fs.exists,
331 isDirectory: (path) => fs.lstat(path).pipe(Effect.map((stat) => stat.type === "Directory")),
332 rename: fs.rename,
333 remove: (path) => fs.remove(path, { force: true }),
334 read: fs.readFileString,
335 write: fs.writeFileString,
336 },
337 options.filePath,
338 options.maxFiles,
339 );
340 let needsRecovery = yield* rotation.recover.pipe(
341 Effect.orElseSucceed(() => false),
342 Effect.map((ready) => !ready),
343 );
344 const pruneOverflowBackups = Effect.gen(function* () {
345 for (const entry of yield* fs.readDirectory(directory)) {
346 if (!entry.startsWith(`${basename}.`)) continue;
347 const suffixText = entry.slice(basename.length + 1);
348 const suffix = Number(suffixText);
349 if (!Number.isInteger(suffix) || String(suffix) !== suffixText || suffix <= options.maxFiles)
350 continue;
351 yield* fs.remove(path.join(directory, entry), { force: true });
352 }
353 }).pipe(Effect.mapError(failure("prune")));
354 if (!needsRecovery) yield* pruneOverflowBackups;
355 const readSize = fs.stat(options.filePath).pipe(
356 Effect.map((stat) => Number(stat.size)),
357 Effect.catch((cause) =>
358 cause.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(failure("read")(cause)),
359 ),
360 );
361 let currentSize = yield* readSize;
362 const semaphore = yield* Semaphore.make(1);
363 const runRotation = (operation: typeof rotation.rotate) =>
364 operation.pipe(
365 Effect.mapError(failure("rotate")),
366 Effect.tapError(() =>
367 Effect.sync(() => {
368 needsRecovery = true;
369 }),
370 ),
371 );
372 const write = (chunk: string | Buffer) =>
373 semaphore
374 .withPermits(1)(
375 Effect.gen(function* () {
376 const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
377 if (buffer.length === 0) return;
378 if (needsRecovery) {
379 const recovered = yield* runRotation(rotation.recover);
380 if (recovered) yield* pruneOverflowBackups;
381 currentSize = yield* readSize;
382 needsRecovery = !recovered;
383 }
384 if (!needsRecovery && currentSize > 0 && currentSize + buffer.length > options.maxBytes) {
385 needsRecovery = !(yield* runRotation(rotation.rotate));
386 currentSize = 0;
387 }
388 yield* fs
389 .writeFile(options.filePath, buffer, { flag: "a" })
390 .pipe(Effect.mapError(failure("write")));
391 currentSize += buffer.length;
392 }).pipe(
393 Effect.tapError(() =>
394 readSize.pipe(
395 Effect.tap((size) =>
396 Effect.sync(() => {
397 currentSize = size;
398 }),
399 ),
400 Effect.ignore,
401 ),
402 ),
403 ),
404 )
405 .pipe(Effect.uninterruptible);
406 return { write };
407});