rotating-file-stream
Version:
Opens a stream.Writable to a file rotated by interval and/or size. A logrotate alternative.
349 lines (348 loc) • 16.7 kB
TypeScript
import { type EventEmitterEventMap } from "node:events";
import { Writable, type WritableEventMap } from "node:stream";
/**
* Error thrown by the package for library-originated failures (invalid configuration, invariant
* checks, unexpected thrown values, and similar). Node.js API errors are not wrapped.
*/
export declare class RotatingFileStreamError extends Error {
}
/** External compression command builder. */
export type Compressor = (source: string, dest: string) => string;
/** Compression option accepted by `createStream`. */
export type Compress = boolean | "gzip" | Compressor;
/** Arguments passed to a {@link StandardGenerator} when producing a rotated file name. */
export interface GeneratorArguments {
index: number;
time: Date;
}
/**
* File name generator used when classical UNIX logrotate behavior is enabled
* (`options.rotate`).
*
* Called with `null` for the not-rotated file name, or with the rotation index
* otherwise.
*/
export type ClassicalGenerator = (index: number | null) => string;
/**
* File name generator used for standard rotation.
*
* Called with `null` for the not-rotated file name, or with both `time` and
* `index` together otherwise.
*/
export type StandardGenerator = (args: GeneratorArguments | null) => string;
/** Either kind of accepted file name generator. */
export type Generator = ClassicalGenerator | StandardGenerator;
/** Event map exposed by `RotatingFileStream`. */
export interface RotatingFileStreamEventMap extends WritableEventMap, EventEmitterEventMap {
external: [stdout: string, stderr: string];
history: [];
open: [filename: string];
removed: [filename: string, number: boolean];
rotated: [filename: string];
rotation: [];
warning: [error: Error];
}
/** Typed event-emitter surface for `RotatingFileStream`. */
export declare interface RotatingFileStream extends Writable {
addListener<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
emit<E extends keyof RotatingFileStreamEventMap>(event: E, ...args: RotatingFileStreamEventMap[E]): boolean;
listenerCount<E extends keyof RotatingFileStreamEventMap>(event: E, listener?: (...args: RotatingFileStreamEventMap[E]) => void): number;
listeners<E extends keyof RotatingFileStreamEventMap>(event: E): ((...args: RotatingFileStreamEventMap[E]) => void)[];
off<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
on<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
once<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
prependListener<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
prependOnceListener<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
rawListeners<E extends keyof RotatingFileStreamEventMap>(event: E): ((...args: RotatingFileStreamEventMap[E]) => void)[];
removeAllListeners<E extends keyof RotatingFileStreamEventMap>(event?: E): this;
removeListener<E extends keyof RotatingFileStreamEventMap>(event: E, listener: (...args: RotatingFileStreamEventMap[E]) => void): this;
}
/** Supported interval units. */
export type IntervalUnit = "M" | "d" | "h" | "m" | "s";
/** Allowed hour-based interval values. */
type HourInterval = 1 | 2 | 3 | 4 | 6 | 8 | 12 | 24;
/** Allowed minute- and second-based interval values. */
type MinuteInterval = 1 | 2 | 3 | 4 | 5 | 6 | 10 | 12 | 15 | 20 | 30 | 60;
/** String form accepted for interval rotation options. */
export type Interval = `${number}${"M" | "d"}` | `${HourInterval}h` | `${MinuteInterval}${"m" | "s"}`;
/** Supported file size units. */
export type FileSizeUnit = "B" | "K" | "M" | "G";
/** String form accepted for size-related options. */
export type FileSize = `${number}${FileSizeUnit}`;
/** Conditional interval option type preserving literal validation. */
type IntervalOpt<I extends string = string> = string extends I ? string : I extends Interval ? I : never;
/** Conditional file size option type preserving literal validation. */
type FileSizeOpt<S extends string = string> = string extends S ? string : S extends FileSize ? S : never;
/** Public options accepted by `createStream`. */
export interface Options<I extends string = string, MS extends string = string, RS extends string = string> {
compress?: Compress;
encoding?: BufferEncoding;
history?: string;
immutable?: boolean;
initialRotation?: boolean;
interval?: IntervalOpt<I>;
intervalBoundary?: boolean;
intervalUTC?: boolean;
maxFiles?: number;
maxSize?: FileSizeOpt<MS>;
mode?: number;
omitExtension?: boolean;
path?: string;
rotate?: number;
size?: FileSizeOpt<RS>;
symLink?: boolean;
teeToStdout?: boolean;
}
/** Parsed, normalized options stored on the stream after `createStream` validation. */
interface BaseInternalOptions {
compress?: Compress;
encoding: BufferEncoding;
history?: string;
immutable?: boolean;
initialRotation?: boolean;
interval?: {
num: number;
unit: IntervalUnit;
};
intervalBoundary?: boolean;
intervalUTC?: boolean;
maxFiles?: number;
maxSize?: number;
mode: number;
omitExtension?: boolean;
path: string;
rotate?: number;
size?: number;
symLink?: boolean;
teeToStdout?: boolean;
}
/** Normalized options for classical rotation mode. */
export type InternalOptionsWithRotate = BaseInternalOptions & {
generator: ClassicalGenerator;
rotate: number;
};
/** Normalized options for standard rotation mode. */
export type InternalOptionsWithoutRotate = Omit<BaseInternalOptions, "rotate"> & {
generator: StandardGenerator;
rotate?: undefined;
};
/** Union of normalized options stored by `RotatingFileStream`. */
export type InternalOptions = InternalOptionsWithoutRotate | InternalOptionsWithRotate;
/** Internal callback placeholder mirroring `node:stream` writable hooks. */
export type Callback = (error?: Error | null) => void;
/** Encoding type accepted by the stream write hooks. */
export type WriteEncoding = BufferEncoding | "buffer";
/** Buffered chunk placeholder reserved for the stream rewrite. */
export interface Chunk {
chunk: Buffer;
encoding: WriteEncoding;
}
/**
* Writable stream that implements rotating file output.
*
* It is exported mainly for `instanceof` checks and typed event support; users
* are expected to create instances through `createStream`.
*/
export declare class RotatingFileStream extends Writable {
/** Path of the not-rotated file (`options.path` plus the generator name). */
private filename;
/** Open file handle for the current log file, or `null` when none is open. */
private handle;
/** Path of the immutable-mode file that was last rotated away from. */
private last;
/**
* Cap for a single interval `setTimeout` delay, in milliseconds.
*
* Intervals longer than this are scheduled as repeated shorter waits until the
* window end is reached (Node timers cannot sleep arbitrarily long in one shot).
*/
private maxTimeout;
/** End of the current interval window, as a timestamp. */
private next;
/** Normalized options stored on the stream after `createStream` validation. */
private options;
/**
* Base directory prepended to generated file names (same value as `options.path`).
*
* Relative to the process cwd when the option is relative; never rewritten to an
* absolute path, so event payloads match the names listeners received in v3.
*/
private path;
/** While `_construct` is running, {@link RotatingFileStream.reopen} must not emit `open` yet. */
private constructing;
/** Set after `finish` has been emitted; `close` emits `finish` if it has not already. */
private finished;
/** Start of the current interval window, as a timestamp. */
private prev;
/** In-flight {@link RotatingFileStream.rewrite}, or `null` when idle. */
private rewritePromise;
/** Instant at which the current rotation job started. */
private rotationTime;
/** Current size, in bytes, of the file being written. */
private size;
/** Pending interval timer, or `null` when none is scheduled. */
private timeout;
/** In-flight interval-driven rotation, or `null` when idle. */
private timeoutPromise;
/** Build a stream instance with normalized options. */
constructor(options: InternalOptions);
/** Open the current log file for append, creating missing parent directories if needed. */
_construct(done: Callback): void;
/** Cancel the interval timer, wait for any in-flight interval rotation, then close the handle. */
_destroy(error: Error | null, done: Callback): void;
/** Cancel the interval timer, wait for any in-flight interval rotation, then close the handle. */
_final(done: Callback): void;
/** Accept a single chunk and persist it through {@link RotatingFileStream.rewrite}. */
_write(chunk: Buffer, encoding: WriteEncoding, done: Callback): void;
/** Accept a batch of chunks and persist them through {@link RotatingFileStream.rewrite}. */
_writev(chunks: Chunk[], done: Callback): void;
/** Clear the pending interval timer, if any. */
private clear;
/** Close the current file handle when one is open and set it to `null`. */
private closeHandle;
/** Return whether `filename` exists on the filesystem. */
private exists;
/**
* Find an unused rotated file name for the current rotation job.
*
* `index` starts at `1` when `options.size` is set, otherwise at `0`.
*/
private findName;
/**
* Return the path of the not-rotated file when `index` is omitted, or of a rotated
* file by calling the configured generator with the matching arguments.
*
* The result is `options.path` plus the generator name (relative when `path` is),
* matching the strings emitted on `open`, `rotated`, and `removed`.
*
* When `options.intervalBoundary` is set, the `time` argument passed to the standard
* generator is the lower boundary of the current rotation period (`new Date(this.prev)`)
* rather than the instant when rotation started.
*/
private getFileName;
/**
* Set {@link RotatingFileStream.prev} and {@link RotatingFileStream.next} to the interval window that
* contains `now`, and return that window start.
*/
private intervalBounds;
/** Compute {@link RotatingFileStream.prev} and {@link RotatingFileStream.next} for month, day, or hour intervals. */
private intervalBoundsBig;
/**
* Schedule the next interval-driven rotation.
*
* When the current window has already ended, starts {@link RotatingFileStream.rotate}
* immediately; otherwise arms a `setTimeout` (capped by {@link RotatingFileStream.maxTimeout})
* that rechecks the remaining time.
*/
private interval;
/**
* Pick or create the immutable-mode log file for the current rotation job.
*
* Scans numbered generator outputs until it finds a missing file or one still
* under `options.size`. On the initial open (`first === true`) appends to that
* file; on rotation emits `rotated` for {@link RotatingFileStream.last} and
* switches to the next slot.
*/
private immutable;
/**
* Classical UNIX logrotate rotation: shift numbered backups and move the live file
* into slot `.1` (or compress it there when `options.compress` is set).
*/
private classical;
/**
* Compress `source` into `dest` and remove `source`.
*
* Uses internal gzip when `options.compress` is `"gzip"`, or runs an external shell command
* when it is a {@link Compressor} function. Defaults `source` to {@link RotatingFileStream.filename}.
*
* For external compression, always emits {@link RotatingFileStreamEventMap.external} with the
* command `stdout` and `stderr` (including when the command exits with a non-zero status),
* then rejects if the command failed.
*/
private compress;
/** Gzip `source` into `dest` by piping through a gzip transform stream. */
private gzip;
/**
* Move the current not-rotated file to an available rotated name and reopen an empty log.
*
* Standard rotation only; classical mode uses {@link RotatingFileStream.classical}.
*/
private move;
/** Return the current instant used for interval-bound calculations. */
private now;
/**
* Cancel the interval timer, wait for any in-flight interval rotation and writes,
* then close the handle.
*
* Shared by {@link RotatingFileStream._final} and {@link RotatingFileStream._destroy}.
*/
private refinal;
/** Open {@link RotatingFileStream.filename} for append, set {@link RotatingFileStream.size}, and emit `open`. */
private reopen;
/**
* Concatenate writeable chunks while respecting `options.size`, rotating as needed.
*
* Chunks that fit under the size limit are buffered together; when a chunk would
* reach the limit the buffer is written, rotation runs, and buffering restarts.
* A single chunk is never split across files. When `options.teeToStdout` is set,
* each chunk is also written to `process.stdout`.
*
* Publishes {@link RotatingFileStream.rewritePromise} for the duration of the work so
* an interval timer waits before closing the handle. Conversely, waits once for any
* in-flight interval-driven rotation ({@link RotatingFileStream.timeoutPromise}) before
* touching the file handle; the reverse lock keeps a new interval rotation from
* starting mid-rewrite.
*
* Invokes `done` when the write completes or fails.
*/
private rewrite;
/**
* Start a rotation job: reset size, clear the interval timer, emit `rotation`,
* close the handle, then run the configured rotation path.
*/
private rotate;
/**
* Finish a rotation job: enforce history limits when configured, emit `rotated`,
* then reopen the not-rotated file empty.
*/
private rotated;
/**
* Read, update, and rewrite the history file after a rotation.
*
* Trims tracked files by {@link Options.maxFiles} first, then by {@link Options.maxSize},
* unlinks removed entries, and emits `removed` and `history`.
*/
private history;
/** Read the full UTF-8 contents of a history file via {@link FileHandle.read}. */
private readHistoryContent;
/** Write UTF-8 history contents via {@link FileHandle.write}, creating parent directories if needed. */
private writeHistoryContent;
/** Remove a rotated file; an `ENOENT` is emitted as `warning` and ignored. */
private safeUnlink;
/**
* Ensure the parent path of `filename` exists by creating and removing a placeholder file.
*
* Used so a subsequent rename into that path cannot fail for a missing directory.
* An `ENOENT` from the placeholder unlink is emitted as `warning` and ignored.
*/
private touch;
/**
* Point the not-rotated file name at {@link RotatingFileStream.filename} via a symbolic link.
*
* Used when `options.symLink` is set together with `options.immutable`.
*/
private updateSymLink;
}
/** Options shape required when `rotate` is enabled. */
export type OptionsWithRotate<I extends string = string, MS extends string = string, RS extends string = string> = Options<I, MS, RS> & {
rotate: number;
};
/** Options shape used when `rotate` is absent. */
export type OptionsWithoutRotate<I extends string = string, MS extends string = string, RS extends string = string> = Omit<Options<I, MS, RS>, "rotate"> & {
rotate?: undefined;
};
/** Create a stream using classical rotation mode. */
export declare function createStream<I extends string = string, MS extends string = string, RS extends string = string>(filename: string | ClassicalGenerator, options: OptionsWithRotate<I, MS, RS>): RotatingFileStream;
/** Create a stream using standard rotation mode. */
export declare function createStream<I extends string = string, MS extends string = string, RS extends string = string>(filename: string | StandardGenerator, options?: OptionsWithoutRotate<I, MS, RS>): RotatingFileStream;
export {};