File size: 5,900 Bytes
4e23b01 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | import { appendFileSync, mkdirSync } from 'node:fs';
import { mkdir, open, rename, stat, unlink } from 'node:fs/promises';
import { dirname } from 'node:path';
import { syncDir } from '#/utils/fs';
export const PENDING_MAX = 1000;
const STDERR_NOTICE_INTERVAL_MS = 30_000;
class AsyncSerialQueue {
private tail: Promise<unknown> = Promise.resolve();
run<T>(task: () => Promise<T>): Promise<T> {
const next = this.tail.then(task, task);
this.tail = next.catch(() => {});
return next;
}
}
export interface Sink {
enqueue(line: string): void;
flush(): Promise<boolean>;
close(): Promise<void>;
flushSync(): void;
}
interface RotatingFileSinkOptions {
readonly path: string;
readonly maxBytes: number;
readonly files: number;
}
export class RotatingFileSink implements Sink {
private readonly queue = new AsyncSerialQueue();
private pending: string[] = [];
private dropped = 0;
private closed = false;
private lastStderrNotice = 0;
private currentBytes = -1;
private directorySynced = false;
constructor(private readonly options: RotatingFileSinkOptions) {}
enqueue(line: string): void {
if (this.closed) return;
if (this.pending.length >= PENDING_MAX) {
this.pending.shift();
this.dropped++;
}
this.pending.push(line);
this.scheduleDrain();
}
async flush(): Promise<boolean> {
return this.queue.run(() => this.drain());
}
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
try {
await this.flush();
} catch {
}
}
flushSync(): void {
if (this.closed || this.pending.length === 0) return;
try {
mkdirSync(dirname(this.options.path), { recursive: true });
const body = this.pending.join('') + this.takeDroppedNotice();
this.pending = [];
appendFileSync(this.options.path, body);
} catch (error) {
this.noteFailure(error);
}
}
private scheduleDrain(): void {
if (this.closed) return;
queueMicrotask(() => {
if (this.closed || this.pending.length === 0) return;
this.queue.run(() => this.drain()).catch(() => {});
});
}
private async drain(): Promise<boolean> {
if (this.pending.length === 0) return true;
const droppedLine = this.takeDroppedNotice();
const lines = droppedLine === '' ? [...this.pending] : [...this.pending, droppedLine];
this.pending = [];
try {
await mkdir(dirname(this.options.path), { recursive: true });
if (this.currentBytes < 0) {
this.currentBytes = await this.statSize(this.options.path);
}
await this.appendLines(lines);
if (!this.directorySynced) {
await syncDir(dirname(this.options.path));
this.directorySynced = true;
}
return true;
} catch (error) {
this.noteFailure(error);
this.restorePending(lines);
return false;
}
}
private restorePending(lines: readonly string[]): void {
const restored = [...lines, ...this.pending];
const overflow = restored.length - PENDING_MAX;
if (overflow <= 0) {
this.pending = restored;
return;
}
this.dropped += overflow;
this.pending = restored.slice(overflow);
}
private async appendLines(lines: readonly string[]): Promise<void> {
let chunk = '';
let chunkBytes = 0;
for (const line of lines) {
const lineBytes = Buffer.byteLength(line, 'utf-8');
if (
chunkBytes > 0 &&
(chunkBytes + lineBytes > this.options.maxBytes ||
this.currentBytes + chunkBytes + lineBytes > this.options.maxBytes)
) {
await this.appendChunk(chunk);
chunk = '';
chunkBytes = 0;
}
if (
chunkBytes === 0 &&
this.currentBytes > 0 &&
this.currentBytes + lineBytes > this.options.maxBytes
) {
await this.rotate();
}
chunk += line;
chunkBytes += lineBytes;
}
if (chunkBytes > 0) {
await this.appendChunk(chunk);
}
}
private async appendChunk(chunk: string): Promise<void> {
const fh = await open(this.options.path, 'a');
try {
await fh.appendFile(chunk, 'utf-8');
await fh.sync();
} finally {
await fh.close();
}
this.currentBytes += Buffer.byteLength(chunk, 'utf-8');
if (this.currentBytes >= this.options.maxBytes) {
await this.rotate();
}
}
private async rotate(): Promise<void> {
const { path, files } = this.options;
for (let i = files - 2; i >= 1; i--) {
const from = `${path}.${i}`;
const to = `${path}.${i + 1}`;
try {
await rename(from, to);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
}
try {
await rename(path, `${path}.1`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
try {
await unlink(`${path}.${files}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
this.currentBytes = 0;
this.directorySynced = false;
}
private async statSize(p: string): Promise<number> {
try {
const s = await stat(p);
return s.size;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return 0;
throw error;
}
}
private takeDroppedNotice(): string {
if (this.dropped === 0) return '';
const line = `... dropped ${this.dropped} entries ...\n`;
this.dropped = 0;
return line;
}
private noteFailure(error: unknown): void {
const now = Date.now();
if (now - this.lastStderrNotice < STDERR_NOTICE_INTERVAL_MS) return;
this.lastStderrNotice = now;
const code = (error as NodeJS.ErrnoException)?.code ?? 'UNKNOWN';
try {
process.stderr.write(`[logger] write failed: ${code}\n`);
} catch {}
}
}
|