@c9up/spectrum 0.1.18 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -7
- package/dist/Logger.d.ts +6 -2
- package/dist/Logger.d.ts.map +1 -1
- package/dist/Logger.js +214 -80
- package/dist/Logger.js.map +1 -1
- package/dist/LoggerManager.d.ts +5 -0
- package/dist/LoggerManager.d.ts.map +1 -1
- package/dist/LoggerManager.js +10 -3
- package/dist/LoggerManager.js.map +1 -1
- package/dist/RustLogBridge.d.ts +27 -2
- package/dist/RustLogBridge.d.ts.map +1 -1
- package/dist/RustLogBridge.js +45 -31
- package/dist/RustLogBridge.js.map +1 -1
- package/dist/SpectrumProvider.d.ts +6 -2
- package/dist/SpectrumProvider.d.ts.map +1 -1
- package/dist/SpectrumProvider.js +18 -12
- package/dist/SpectrumProvider.js.map +1 -1
- package/dist/channels/ConsoleChannel.d.ts +8 -1
- package/dist/channels/ConsoleChannel.d.ts.map +1 -1
- package/dist/channels/ConsoleChannel.js +18 -14
- package/dist/channels/ConsoleChannel.js.map +1 -1
- package/dist/channels/FileChannel.d.ts +32 -9
- package/dist/channels/FileChannel.d.ts.map +1 -1
- package/dist/channels/FileChannel.js +264 -202
- package/dist/channels/FileChannel.js.map +1 -1
- package/dist/errors.d.ts +9 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/jsonLine.d.ts +49 -0
- package/dist/jsonLine.d.ts.map +1 -0
- package/dist/jsonLine.js +165 -0
- package/dist/jsonLine.js.map +1 -0
- package/dist/redact.d.ts +16 -3
- package/dist/redact.d.ts.map +1 -1
- package/dist/redact.js +121 -10
- package/dist/redact.js.map +1 -1
- package/dist/sanitize.d.ts +11 -5
- package/dist/sanitize.d.ts.map +1 -1
- package/dist/sanitize.js +36 -12
- package/dist/sanitize.js.map +1 -1
- package/dist/services/main.d.ts.map +1 -1
- package/dist/services/main.js +12 -1
- package/dist/services/main.js.map +1 -1
- package/dist/stdSerializers.d.ts +48 -0
- package/dist/stdSerializers.d.ts.map +1 -0
- package/dist/stdSerializers.js +129 -0
- package/dist/stdSerializers.js.map +1 -0
- package/dist/stringify.d.ts +33 -0
- package/dist/stringify.d.ts.map +1 -0
- package/dist/stringify.js +148 -0
- package/dist/stringify.js.map +1 -0
- package/dist/targets.d.ts +29 -7
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +130 -31
- package/dist/targets.js.map +1 -1
- package/dist/testing/FakeLogger.js +20 -5
- package/dist/testing/FakeLogger.js.map +1 -1
- package/dist/types.d.ts +71 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +21 -3
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
- package/src/Logger.ts +277 -85
- package/src/LoggerManager.ts +10 -3
- package/src/RustLogBridge.ts +59 -30
- package/src/SpectrumProvider.ts +31 -18
- package/src/channels/ConsoleChannel.ts +30 -14
- package/src/channels/FileChannel.ts +319 -220
- package/src/errors.ts +13 -0
- package/src/index.ts +17 -3
- package/src/jsonLine.ts +223 -0
- package/src/redact.ts +133 -9
- package/src/sanitize.ts +36 -12
- package/src/services/main.ts +13 -1
- package/src/stdSerializers.ts +147 -0
- package/src/stringify.ts +175 -0
- package/src/targets.ts +193 -42
- package/src/testing/FakeLogger.ts +23 -5
- package/src/types.ts +100 -5
- package/stubs/config/logger.stub +11 -1
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* File logging channel — writes log entries to a file as JSON lines.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* HTTP hot path
|
|
4
|
+
* `write()` never touches the disk: it queues the line and returns. One
|
|
5
|
+
* asynchronous pump opens the file, writes the queue in order, and rotates it
|
|
6
|
+
* when the next line would cross `maxSizeBytes`, so the HTTP hot path never
|
|
7
|
+
* waits on the filesystem.
|
|
8
|
+
*
|
|
9
|
+
* Two promises hold that together, both as pino's file destination keeps them:
|
|
10
|
+
* a line accepted before the process exits is on disk after it (the queue is
|
|
11
|
+
* written synchronously on `exit`), and a destination that stops keeping up
|
|
12
|
+
* costs bounded memory (past `maxBufferBytes` lines are dropped and counted,
|
|
13
|
+
* and the count is written once the queue drains).
|
|
7
14
|
*
|
|
8
15
|
* @implements MISS-14, MISS-15
|
|
9
16
|
*/
|
|
@@ -11,286 +18,378 @@
|
|
|
11
18
|
import * as fs from "node:fs";
|
|
12
19
|
import * as fsp from "node:fs/promises";
|
|
13
20
|
import * as path from "node:path";
|
|
21
|
+
import { promisify } from "node:util";
|
|
22
|
+
import { SpectrumError } from "../errors.js";
|
|
23
|
+
import { jsonLine } from "../jsonLine.js";
|
|
14
24
|
import type { LogChannel, LogEntry } from "../types.js";
|
|
15
25
|
|
|
16
26
|
export interface FileChannelConfig {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
27
|
+
/** The file to append to (created, with its directory, if missing). */
|
|
28
|
+
path?: string;
|
|
29
|
+
/**
|
|
30
|
+
* An already-open descriptor to write to instead of a path — what a
|
|
31
|
+
* `destination: 3` target names. Never rotated, and left open on close:
|
|
32
|
+
* the channel did not open it.
|
|
33
|
+
*/
|
|
34
|
+
fd?: number;
|
|
35
|
+
/** `false` starts the file over on first open instead of appending. Default true. */
|
|
36
|
+
append?: boolean;
|
|
37
|
+
/** Rotate before the live file would grow past this. Default 10 MiB. */
|
|
38
|
+
maxSizeBytes?: number;
|
|
39
|
+
/** Files kept, the live one included. Default 5. */
|
|
40
|
+
maxFiles?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Bytes accepted but not yet written that the channel will hold. Past it,
|
|
43
|
+
* new lines are dropped and counted. Default 16 MiB.
|
|
44
|
+
*/
|
|
45
|
+
maxBufferBytes?: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const openFd = promisify(fs.open);
|
|
49
|
+
const writeFd = promisify(fs.write);
|
|
50
|
+
const closeFd = promisify(fs.close);
|
|
51
|
+
const fstatFd = promisify(fs.fstat);
|
|
52
|
+
|
|
53
|
+
/** How much of the queue goes to the kernel in one write. */
|
|
54
|
+
const CHUNK_BYTES = 64 * 1024;
|
|
55
|
+
|
|
56
|
+
interface Queued {
|
|
57
|
+
line: string;
|
|
58
|
+
bytes: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function positiveInteger(
|
|
62
|
+
name: string,
|
|
63
|
+
value: number | undefined,
|
|
64
|
+
fallback: number,
|
|
65
|
+
): number {
|
|
66
|
+
if (value === undefined) return fallback;
|
|
67
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
68
|
+
throw new SpectrumError(
|
|
69
|
+
"E_SPECTRUM_INVALID_FILE_OPTIONS",
|
|
70
|
+
`FileChannel ${name} must be a positive integer, got ${String(value)}`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
20
74
|
}
|
|
21
75
|
|
|
22
76
|
export class FileChannel implements LogChannel {
|
|
23
77
|
name = "file";
|
|
24
|
-
#filePath: string;
|
|
25
|
-
|
|
26
|
-
#
|
|
27
|
-
|
|
78
|
+
readonly #filePath: string;
|
|
79
|
+
/** Whether `#fd` was handed in rather than opened here. */
|
|
80
|
+
readonly #fdGiven: boolean;
|
|
81
|
+
/** Truncate on the next open: `append: false`, until the first open. */
|
|
82
|
+
#truncate: boolean;
|
|
83
|
+
readonly #maxSize: number;
|
|
84
|
+
readonly #maxFiles: number;
|
|
85
|
+
readonly #maxBuffer: number;
|
|
86
|
+
#fd: number | null = null;
|
|
87
|
+
/** Bytes in the live file, as far as this channel has written them. */
|
|
28
88
|
#currentSize = 0;
|
|
29
|
-
|
|
30
|
-
#
|
|
89
|
+
/** Lines accepted and not yet handed to the kernel. */
|
|
90
|
+
#queue: Queued[] = [];
|
|
91
|
+
/** Bytes of the queue plus the chunk being written. */
|
|
92
|
+
#pendingBytes = 0;
|
|
93
|
+
/** Lines refused since the last notice, because the queue was full. */
|
|
94
|
+
#dropped = 0;
|
|
95
|
+
/** The running pump, so there is only ever one and close() can wait for it. */
|
|
96
|
+
#pump: Promise<void> | null = null;
|
|
97
|
+
/** A rotation that failed lets the next chunk through rather than retrying forever. */
|
|
98
|
+
#skipRotation = false;
|
|
31
99
|
/**
|
|
32
|
-
* Terminal once `close()` has run
|
|
33
|
-
*
|
|
34
|
-
* Nulling the stream was not enough: `write()` reopens a null stream, and so
|
|
35
|
-
* does a rotation, so a line written after close silently reopened the file
|
|
36
|
-
* and appended to it. A closed channel stays closed.
|
|
100
|
+
* Terminal once `close()` has run: a line written after close is refused,
|
|
101
|
+
* and nothing reopens the file.
|
|
37
102
|
*/
|
|
38
103
|
#closed = false;
|
|
39
|
-
#
|
|
104
|
+
#closing?: Promise<void>;
|
|
105
|
+
readonly #ref = new WeakRef(this);
|
|
40
106
|
|
|
41
107
|
constructor(config: FileChannelConfig) {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
108
|
+
const { path: filePath, fd } = config;
|
|
109
|
+
if ((filePath === undefined) === (fd === undefined)) {
|
|
110
|
+
throw new SpectrumError(
|
|
111
|
+
"E_SPECTRUM_INVALID_FILE_OPTIONS",
|
|
112
|
+
"FileChannel needs exactly one of `path` and `fd`",
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (fd !== undefined && !(Number.isInteger(fd) && fd >= 0)) {
|
|
116
|
+
throw new SpectrumError(
|
|
117
|
+
"E_SPECTRUM_INVALID_FILE_OPTIONS",
|
|
118
|
+
`FileChannel fd must be a non-negative integer, got ${String(fd)}`,
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
this.#filePath = filePath ?? `fd ${String(fd)}`;
|
|
122
|
+
this.#fdGiven = fd !== undefined;
|
|
123
|
+
this.#truncate = config.append === false;
|
|
124
|
+
if (fd !== undefined) this.#fd = fd;
|
|
125
|
+
// Checked here, not trusted: -1 rotated on every line and deleted the
|
|
126
|
+
// log, and NaN (an unset env var through Number()) never rotated at all.
|
|
127
|
+
this.#maxSize = positiveInteger(
|
|
128
|
+
"maxSizeBytes",
|
|
129
|
+
config.maxSizeBytes,
|
|
130
|
+
10 * 1024 * 1024,
|
|
131
|
+
);
|
|
132
|
+
this.#maxFiles = positiveInteger("maxFiles", config.maxFiles, 5);
|
|
133
|
+
this.#maxBuffer = positiveInteger(
|
|
134
|
+
"maxBufferBytes",
|
|
135
|
+
config.maxBufferBytes,
|
|
136
|
+
16 * 1024 * 1024,
|
|
137
|
+
);
|
|
45
138
|
}
|
|
46
139
|
|
|
47
140
|
write(entry: LogEntry): void {
|
|
48
141
|
if (this.#closed) return;
|
|
49
|
-
const line = `${
|
|
142
|
+
const line = `${jsonLine(entry)}\n`;
|
|
50
143
|
const bytes = Buffer.byteLength(line, "utf8");
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
this.#pending.push(line);
|
|
144
|
+
if (this.#pendingBytes + bytes > this.#maxBuffer) {
|
|
145
|
+
this.#dropped += 1;
|
|
54
146
|
return;
|
|
55
147
|
}
|
|
148
|
+
this.#queue.push({ line, bytes });
|
|
149
|
+
this.#pendingBytes += bytes;
|
|
150
|
+
FileChannel.#track(this.#ref);
|
|
151
|
+
this.#kick();
|
|
152
|
+
}
|
|
56
153
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
154
|
+
#kick(): void {
|
|
155
|
+
if (this.#pump !== null) return;
|
|
156
|
+
this.#pump = this.#drain().finally(() => {
|
|
157
|
+
this.#pump = null;
|
|
158
|
+
// A line queued between the loop's last check and here.
|
|
159
|
+
if (this.#queue.length > 0 || this.#dropped > 0) this.#kick();
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async #drain(): Promise<void> {
|
|
164
|
+
for (;;) {
|
|
165
|
+
if (this.#queue.length === 0) {
|
|
166
|
+
if (this.#dropped === 0) return;
|
|
167
|
+
this.#enqueueDropNotice();
|
|
65
168
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
// Now that we've reopened, drain them — in order, before the new
|
|
69
|
-
// line — instead of losing them until the next rotation happens to
|
|
70
|
-
// fire. #flushPending may itself trigger a rotation if a buffered
|
|
71
|
-
// line overflows, so re-check before writing the current line.
|
|
72
|
-
this.#flushPending();
|
|
73
|
-
if (this.#rotating) {
|
|
74
|
-
this.#pending.push(line);
|
|
169
|
+
if (this.#fd === null && !(await this.#open())) {
|
|
170
|
+
this.#discardQueue("could not be opened");
|
|
75
171
|
return;
|
|
76
172
|
}
|
|
173
|
+
const chunk = this.#takeChunk();
|
|
174
|
+
if (chunk === null) {
|
|
175
|
+
await this.#rotate();
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
await this.#writeChunk(chunk.text, chunk.bytes);
|
|
77
179
|
}
|
|
180
|
+
}
|
|
78
181
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Lines from the head of the queue that fit in the live file, up to
|
|
184
|
+
* {@link CHUNK_BYTES}; `null` when the head line needs a rotation first.
|
|
185
|
+
*
|
|
186
|
+
* An empty file takes its first line whatever its size: a line cannot be
|
|
187
|
+
* split, and one bigger than `maxSizeBytes` would otherwise rotate forever
|
|
188
|
+
* without ever being written.
|
|
189
|
+
*/
|
|
190
|
+
#takeChunk(): { text: string; bytes: number } | null {
|
|
191
|
+
let text = "";
|
|
192
|
+
let bytes = 0;
|
|
193
|
+
while (this.#queue.length > 0) {
|
|
194
|
+
const head = this.#queue[0];
|
|
195
|
+
if (head === undefined) break;
|
|
196
|
+
const size = this.#currentSize + bytes;
|
|
197
|
+
const overflows =
|
|
198
|
+
!this.#fdGiven && size > 0 && size + head.bytes > this.#maxSize;
|
|
199
|
+
if (overflows && !this.#skipRotation) break;
|
|
200
|
+
if (bytes > 0 && bytes + head.bytes > CHUNK_BYTES) break;
|
|
201
|
+
this.#queue.shift();
|
|
202
|
+
text += head.line;
|
|
203
|
+
bytes += head.bytes;
|
|
204
|
+
this.#skipRotation = false;
|
|
88
205
|
}
|
|
206
|
+
return bytes === 0 ? null : { text, bytes };
|
|
89
207
|
}
|
|
90
208
|
|
|
91
|
-
#
|
|
92
|
-
// A rotation in flight when `close()` lands must not bring the file back.
|
|
93
|
-
if (this.#closed) return;
|
|
94
|
-
// mkdirSync + statSync only on first open (boot) — never on the hot path.
|
|
95
|
-
// The fast write path goes straight through this.#stream.write() (non-blocking).
|
|
96
|
-
if (!this.#dirReady) {
|
|
97
|
-
const dir = path.dirname(this.#filePath);
|
|
98
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
99
|
-
this.#dirReady = true;
|
|
100
|
-
}
|
|
209
|
+
async #open(): Promise<boolean> {
|
|
101
210
|
try {
|
|
102
|
-
|
|
211
|
+
await fsp.mkdir(path.dirname(this.#filePath), { recursive: true });
|
|
212
|
+
const fd = await openFd(this.#filePath, this.#truncate ? "w" : "a");
|
|
213
|
+
this.#truncate = false;
|
|
214
|
+
try {
|
|
215
|
+
this.#currentSize = (await fstatFd(fd)).size;
|
|
216
|
+
} catch {
|
|
217
|
+
this.#currentSize = 0;
|
|
218
|
+
}
|
|
219
|
+
this.#fd = fd;
|
|
220
|
+
return true;
|
|
103
221
|
} catch {
|
|
104
|
-
|
|
222
|
+
return false;
|
|
105
223
|
}
|
|
106
|
-
this.#stream = fs.createWriteStream(this.#filePath, { flags: "a" });
|
|
107
|
-
this.#stream.on("error", (err) => {
|
|
108
|
-
process.stderr.write(
|
|
109
|
-
`[Spectrum] FileChannel stream error: ${err.message}\n`,
|
|
110
|
-
);
|
|
111
|
-
});
|
|
112
224
|
}
|
|
113
225
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
// The promise is KEPT, not just started. A rotation renames files and
|
|
138
|
-
// opens a new stream; `close()` arriving in the middle of that used to
|
|
139
|
-
// write the buffer to a stream the rotation was replacing and return,
|
|
140
|
-
// while the renames carried on behind it. The last lines — the ones
|
|
141
|
-
// explaining why the process is going down — could land in a file that
|
|
142
|
-
// was about to be moved, or in one nothing would look at.
|
|
143
|
-
this.#rotation = new Promise<void>((resolve) => {
|
|
144
|
-
queueMicrotask(() => {
|
|
145
|
-
this.#rotate().finally(() => {
|
|
146
|
-
this.#rotating = false;
|
|
147
|
-
this.#flushPending();
|
|
148
|
-
this.#rotation = null;
|
|
149
|
-
resolve();
|
|
150
|
-
});
|
|
151
|
-
});
|
|
152
|
-
});
|
|
226
|
+
async #writeChunk(text: string, bytes: number): Promise<void> {
|
|
227
|
+
const fd = this.#fd;
|
|
228
|
+
if (fd === null) return;
|
|
229
|
+
const buffer = Buffer.from(text, "utf8");
|
|
230
|
+
try {
|
|
231
|
+
let offset = 0;
|
|
232
|
+
while (offset < buffer.length) {
|
|
233
|
+
const { bytesWritten } = await writeFd(
|
|
234
|
+
fd,
|
|
235
|
+
buffer,
|
|
236
|
+
offset,
|
|
237
|
+
buffer.length - offset,
|
|
238
|
+
);
|
|
239
|
+
offset += bytesWritten;
|
|
240
|
+
}
|
|
241
|
+
} catch (err) {
|
|
242
|
+
process.stderr.write(
|
|
243
|
+
`[Spectrum] FileChannel write failed for '${this.#filePath}': ${err instanceof Error ? err.message : String(err)}\n`,
|
|
244
|
+
);
|
|
245
|
+
} finally {
|
|
246
|
+
this.#currentSize += bytes;
|
|
247
|
+
this.#pendingBytes -= bytes;
|
|
248
|
+
}
|
|
153
249
|
}
|
|
154
250
|
|
|
251
|
+
/** Shift the generations up and leave the live path free for a new file. */
|
|
155
252
|
async #rotate(): Promise<void> {
|
|
253
|
+
const fd = this.#fd;
|
|
254
|
+
this.#fd = null;
|
|
255
|
+
if (fd !== null) await closeFd(fd).catch(() => undefined);
|
|
156
256
|
try {
|
|
157
|
-
|
|
158
|
-
|
|
257
|
+
if (this.#maxFiles === 1) {
|
|
258
|
+
// No generation is kept: the live file starts over.
|
|
259
|
+
await fsp.rm(this.#filePath, { force: true });
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
159
262
|
const oldest = `${this.#filePath}.${this.#maxFiles - 1}`;
|
|
160
263
|
await fsp.rm(oldest, { force: true });
|
|
161
|
-
|
|
162
|
-
// Shift the numbered generations up, oldest first: .1 → .2, .2 → .3…
|
|
163
|
-
//
|
|
164
|
-
// The i===1 pass used to take the LIVE file rather than `.1`, so `.1`
|
|
165
|
-
// was never written and the rename below found nothing left to move.
|
|
166
|
-
// With maxFiles=3 that kept one generation where two were configured,
|
|
167
|
-
// and every rotation destroyed the one before it.
|
|
264
|
+
// Oldest first: .1 → .2, .2 → .3…
|
|
168
265
|
for (let i = this.#maxFiles - 2; i >= 1; i--) {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
`${this.#filePath}.${i + 1}`,
|
|
173
|
-
);
|
|
174
|
-
} catch {
|
|
175
|
-
// That generation does not exist yet — skip
|
|
176
|
-
}
|
|
266
|
+
await fsp
|
|
267
|
+
.rename(`${this.#filePath}.${i}`, `${this.#filePath}.${i + 1}`)
|
|
268
|
+
.catch(() => undefined); // that generation does not exist yet
|
|
177
269
|
}
|
|
178
|
-
|
|
179
|
-
try {
|
|
180
|
-
await fsp.rename(this.#filePath, `${this.#filePath}.1`);
|
|
181
|
-
} catch {
|
|
182
|
-
// Nothing to rotate
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
this.#openStream();
|
|
270
|
+
await fsp.rename(this.#filePath, `${this.#filePath}.1`);
|
|
186
271
|
} catch {
|
|
187
|
-
|
|
188
|
-
this.#
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
`[Spectrum] FileChannel: rotation failed, logging suspended for '${this.#filePath}'\n`,
|
|
192
|
-
);
|
|
193
|
-
this.#stream = null;
|
|
194
|
-
}
|
|
272
|
+
process.stderr.write(
|
|
273
|
+
`[Spectrum] FileChannel: rotation failed for '${this.#filePath}', writing on past maxSizeBytes\n`,
|
|
274
|
+
);
|
|
275
|
+
this.#skipRotation = true;
|
|
195
276
|
}
|
|
196
277
|
}
|
|
197
278
|
|
|
198
|
-
#
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
}
|
|
279
|
+
#enqueueDropNotice(): void {
|
|
280
|
+
const count = this.#dropped;
|
|
281
|
+
this.#dropped = 0;
|
|
282
|
+
const line = `${jsonLine({
|
|
283
|
+
timestamp: new Date().toISOString(),
|
|
284
|
+
level: "warn",
|
|
285
|
+
module: "spectrum",
|
|
286
|
+
message: `FileChannel dropped ${count} line(s): the destination did not keep up`,
|
|
287
|
+
dropped: count,
|
|
288
|
+
})}\n`;
|
|
289
|
+
const bytes = Buffer.byteLength(line, "utf8");
|
|
290
|
+
this.#queue.push({ line, bytes });
|
|
291
|
+
this.#pendingBytes += bytes;
|
|
212
292
|
}
|
|
213
293
|
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
this.#
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
294
|
+
#discardQueue(reason: string): void {
|
|
295
|
+
const lost = this.#queue.length;
|
|
296
|
+
this.#queue = [];
|
|
297
|
+
this.#pendingBytes = 0;
|
|
298
|
+
this.#dropped = 0;
|
|
299
|
+
process.stderr.write(
|
|
300
|
+
`[Spectrum] FileChannel: '${this.#filePath}' ${reason}; ${lost} line(s) lost\n`,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Write the queue now, synchronously — the process is exiting and there is
|
|
306
|
+
* no event loop left to run the pump.
|
|
307
|
+
*
|
|
308
|
+
* A chunk already handed to an asynchronous write is left to it, as pino's
|
|
309
|
+
* destination leaves it. The file is opened non-blocking when the pump had
|
|
310
|
+
* not opened it yet, so a destination nobody reads cannot hang the exit.
|
|
311
|
+
*/
|
|
312
|
+
#flushSync(): void {
|
|
313
|
+
if (this.#dropped > 0) this.#enqueueDropNotice();
|
|
314
|
+
if (this.#queue.length === 0) return;
|
|
315
|
+
const text = this.#queue.map((queued) => queued.line).join("");
|
|
316
|
+
this.#queue = [];
|
|
317
|
+
this.#pendingBytes = 0;
|
|
318
|
+
let fd = this.#fd;
|
|
319
|
+
let opened = false;
|
|
320
|
+
try {
|
|
321
|
+
if (fd === null) {
|
|
322
|
+
fs.mkdirSync(path.dirname(this.#filePath), { recursive: true });
|
|
323
|
+
fd = fs.openSync(
|
|
324
|
+
this.#filePath,
|
|
325
|
+
fs.constants.O_WRONLY |
|
|
326
|
+
fs.constants.O_APPEND |
|
|
327
|
+
fs.constants.O_CREAT |
|
|
328
|
+
(this.#truncate ? fs.constants.O_TRUNC : 0) |
|
|
329
|
+
(fs.constants.O_NONBLOCK ?? 0),
|
|
330
|
+
0o666,
|
|
331
|
+
);
|
|
332
|
+
opened = true;
|
|
333
|
+
}
|
|
334
|
+
const buffer = Buffer.from(text, "utf8");
|
|
335
|
+
let offset = 0;
|
|
336
|
+
while (offset < buffer.length) {
|
|
337
|
+
offset += fs.writeSync(fd, buffer, offset, buffer.length - offset);
|
|
338
|
+
}
|
|
339
|
+
} catch {
|
|
340
|
+
process.stderr.write(
|
|
341
|
+
`[Spectrum] FileChannel: lines lost writing '${this.#filePath}' at exit\n`,
|
|
342
|
+
);
|
|
343
|
+
} finally {
|
|
344
|
+
if (opened && fd !== null) fs.closeSync(fd);
|
|
345
|
+
}
|
|
221
346
|
}
|
|
222
347
|
|
|
223
348
|
/**
|
|
224
|
-
* Stop writing, for good.
|
|
349
|
+
* Stop writing, for good, once everything accepted is on disk.
|
|
225
350
|
*
|
|
226
|
-
*
|
|
227
|
-
*
|
|
228
|
-
*
|
|
229
|
-
* the
|
|
351
|
+
* Every caller awaits the SAME completion — the promise itself, not a
|
|
352
|
+
* wrapper around it, which is why this is not `async`. A second `close()`
|
|
353
|
+
* that resolved while the first was still flushing let a shutdown believe
|
|
354
|
+
* the last lines were on disk when they were still queued.
|
|
230
355
|
*/
|
|
231
356
|
close(): Promise<void> {
|
|
232
|
-
// Every caller awaits the SAME completion — the promise itself, not a
|
|
233
|
-
// wrapper around it, which is why this is not `async`. Returning early on `#closed`
|
|
234
|
-
// meant a second `close()` resolved while the first was still flushing,
|
|
235
|
-
// so a shutdown that closed two channels in parallel — or simply called
|
|
236
|
-
// this twice — believed the last lines were on disk when they were still
|
|
237
|
-
// in the stream.
|
|
238
357
|
this.#closing ??= this.#close();
|
|
239
358
|
return this.#closing;
|
|
240
359
|
}
|
|
241
360
|
|
|
242
|
-
/** The single closing run, memoised by {@link close}. */
|
|
243
|
-
#closing?: Promise<void>;
|
|
244
|
-
|
|
245
361
|
async #close(): Promise<void> {
|
|
246
|
-
if (this.#closed) return;
|
|
247
|
-
// Closed FIRST, so nothing the rotation's flush triggers schedules
|
|
248
|
-
// another one, then wait for the rotation already in flight. Without
|
|
249
|
-
// this the two ran over each other and whichever finished last decided
|
|
250
|
-
// where the final lines were.
|
|
251
362
|
this.#closed = true;
|
|
252
|
-
await this.#
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
this.#stream = null;
|
|
258
|
-
// AWAIT the flush. `end()` asks the stream to finish; it does not
|
|
259
|
-
// finish it. Returning here let a shutdown run on to `process.exit`
|
|
260
|
-
// with the last lines still buffered — and the last lines are usually
|
|
261
|
-
// the ones explaining why the process is going down.
|
|
262
|
-
await new Promise<void>((resolve) => {
|
|
263
|
-
stream.end(() => resolve());
|
|
264
|
-
// A stream that errors will never emit `finish`, and a shutdown
|
|
265
|
-
// must not hang on a full disk or a revoked permission.
|
|
266
|
-
stream.once("error", () => resolve());
|
|
267
|
-
});
|
|
268
|
-
return;
|
|
363
|
+
while (this.#pump !== null) await this.#pump;
|
|
364
|
+
const fd = this.#fd;
|
|
365
|
+
this.#fd = null;
|
|
366
|
+
if (fd !== null && !this.#fdGiven) {
|
|
367
|
+
await closeFd(fd).catch(() => undefined);
|
|
269
368
|
}
|
|
270
|
-
|
|
271
|
-
// awaiting the old one's end, and it will not reopen now that #closed is
|
|
272
|
-
// set. Writing the buffer to the stream that no longer exists is how
|
|
273
|
-
// those lines used to disappear — accepted by write(), then dropped.
|
|
274
|
-
//
|
|
275
|
-
// Appended directly instead, and synchronously, because close() is: the
|
|
276
|
-
// path is the current log either way, whether the rotation has renamed
|
|
277
|
-
// it yet or not.
|
|
278
|
-
this.#appendDirectly(pending);
|
|
369
|
+
FileChannel.#untrack(this.#ref);
|
|
279
370
|
}
|
|
280
371
|
|
|
281
|
-
/**
|
|
282
|
-
#
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
372
|
+
/** Channels with lines that the `exit` hook may have to write. Weak, as pino holds its destinations. */
|
|
373
|
+
static readonly #tracked = new Set<WeakRef<FileChannel>>();
|
|
374
|
+
|
|
375
|
+
static #track(ref: WeakRef<FileChannel>): void {
|
|
376
|
+
if (FileChannel.#tracked.has(ref)) return;
|
|
377
|
+
if (FileChannel.#tracked.size === 0)
|
|
378
|
+
process.on("exit", FileChannel.#onExit);
|
|
379
|
+
FileChannel.#tracked.add(ref);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
static #untrack(ref: WeakRef<FileChannel>): void {
|
|
383
|
+
if (!FileChannel.#tracked.delete(ref)) return;
|
|
384
|
+
if (FileChannel.#tracked.size === 0) {
|
|
385
|
+
process.removeListener("exit", FileChannel.#onExit);
|
|
294
386
|
}
|
|
295
387
|
}
|
|
388
|
+
|
|
389
|
+
static readonly #onExit = (): void => {
|
|
390
|
+
for (const ref of FileChannel.#tracked) {
|
|
391
|
+
const channel = ref.deref();
|
|
392
|
+
if (channel !== undefined) channel.#flushSync();
|
|
393
|
+
}
|
|
394
|
+
};
|
|
296
395
|
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A spectrum configuration or usage error, carrying an `E_SPECTRUM_*` code an
|
|
3
|
+
* application can filter on.
|
|
4
|
+
*/
|
|
5
|
+
export class SpectrumError extends Error {
|
|
6
|
+
readonly code: string;
|
|
7
|
+
|
|
8
|
+
constructor(code: string, message: string) {
|
|
9
|
+
super(`[spectrum] ${message}`);
|
|
10
|
+
this.name = "SpectrumError";
|
|
11
|
+
this.code = code;
|
|
12
|
+
}
|
|
13
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,14 +6,24 @@
|
|
|
6
6
|
|
|
7
7
|
import "./augmentations.js";
|
|
8
8
|
|
|
9
|
-
export {
|
|
10
|
-
|
|
9
|
+
export {
|
|
10
|
+
ConsoleChannel,
|
|
11
|
+
type ConsoleChannelOptions,
|
|
12
|
+
} from "./channels/ConsoleChannel.js";
|
|
13
|
+
export { FileChannel, type FileChannelConfig } from "./channels/FileChannel.js";
|
|
11
14
|
export { defineConfig } from "./config.js";
|
|
12
15
|
export { configure } from "./configure.js";
|
|
16
|
+
export { SpectrumError } from "./errors.js";
|
|
13
17
|
export { clearLogListeners, type LogListener, onLog } from "./events.js";
|
|
18
|
+
export type { LineFormatters, TimestampOption } from "./jsonLine.js";
|
|
14
19
|
export { Logger, type LogLevel } from "./Logger.js";
|
|
15
20
|
export { LoggerManager } from "./LoggerManager.js";
|
|
16
|
-
export {
|
|
21
|
+
export {
|
|
22
|
+
createRustLogBridge,
|
|
23
|
+
parseRustLog,
|
|
24
|
+
type RustLogBridgeOptions,
|
|
25
|
+
} from "./RustLogBridge.js";
|
|
26
|
+
export { stdSerializers, stdTimeFunctions } from "./stdSerializers.js";
|
|
17
27
|
export type {
|
|
18
28
|
FileTargetOptions,
|
|
19
29
|
PrettyTargetOptions,
|
|
@@ -21,12 +31,16 @@ export type {
|
|
|
21
31
|
} from "./targets.js";
|
|
22
32
|
export { channelsFromTargets, Targets, targets } from "./targets.js";
|
|
23
33
|
export {
|
|
34
|
+
type ChildOptions,
|
|
24
35
|
isLogLevelWithSilent,
|
|
36
|
+
type LineWritable,
|
|
25
37
|
type LogChannel,
|
|
26
38
|
type LogConfig,
|
|
27
39
|
type LogEntry,
|
|
28
40
|
type LoggerManagerConfig,
|
|
29
41
|
type LogLevelWithSilent,
|
|
42
|
+
type LogMethodHook,
|
|
43
|
+
type LogMixin,
|
|
30
44
|
type LogSerializer,
|
|
31
45
|
logEntryExtras,
|
|
32
46
|
logLevel,
|