Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ import { maskIpsInText, redactSecretsInText } from "./log-mask.js";

const MAX_BYTES = 10 * 1024 * 1024; // 10 MB → rotate

// File-type bits for the open-fd directory check below (POSIX mode constants;
// Node reports them identically on Windows).
const S_IFMT = 0o170000;
const S_IFDIR = 0o040000;

export type Logger = (level: string, msg: string) => void;

// ── Request-scoped session attribution ─────────────────────────────────────
Expand Down Expand Up @@ -171,6 +176,18 @@ export function setLogCapture(fn: ((level: string, msg: string) => void) | null)
capture = fn;
}

/** Drop a freshly-opened stream whose fd failed verification (a directory on
* Win32, or fstat itself failing): clear state so the next line reopens, and
* run the one-shot degradation warn — the async-failure path getStream()'s
* try/catch cannot see (#3857 follow-up to #3858). */
function rejectOpen(s: WriteStream, err: unknown): void {
try { s.destroy(); } catch { /* best-effort */ }
stream = undefined;
streamFd = undefined;
writeProven = false;
warnReopenFailed(err);
}

function openStream(file: string): WriteStream {
mkdirSync(path.dirname(file), { recursive: true });
// Rotate if oversized.
Expand All @@ -192,11 +209,27 @@ function openStream(file: string): WriteStream {
// file doesn't exist yet — fine
}
const s = createWriteStream(file, { flags: "a" });
// 'open' only records the fd (orphan-inode detection needs it). It must NOT
// arm liveness: on win32 (observed node 22 in CI) some paths (e.g. a
// DIRECTORY) open fine and only their writes fail (#3857).
// 'open' records the fd (orphan-inode detection needs it) and verifies it
// is usable. It must NOT arm liveness — that stays with the first DELIVERED
// write (#3857): on win32 (observed node 22 in CI) open(2) can hand out an
// fd for a DIRECTORY whose writes then always fail. Rejecting it here lets
// the degradation surface immediately (one warn naming the cause, zero lost
// lines) instead of on the first lost line; character devices (/dev/null
// logFile) stay legal.
s.on("open", (fd: number) => {
if (stream === s) streamFd = fd;
if (stream !== s) return;
let st: ReturnType<typeof fstatSync>;
try {
st = fstatSync(fd);
} catch (err) {
rejectOpen(s, err);
return;
}
if ((st.mode & S_IFMT) === S_IFDIR) {
rejectOpen(s, new Error("path is a directory"));
return;
}
streamFd = fd;
});
// If the stream errors (disk full, perms), drop it so the next write
// triggers a reopen instead of piling onto a dead stream. #3857: an ASYNC
Expand Down
83 changes: 83 additions & 0 deletions tests/logger-async-open-failure.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
configureLogger,
log,
closeLogger,
setLogCapture,
isFileLoggingActive,
} from "../src/logger.ts";
import { rmrf } from "./tmp-rm.ts";

// #3857 follow-up pins (on top of #3858's delivered-write liveness design):
// regression coverage the merged silent-loss suite does not carry —
// (1) a mid-life leg death (the log path becomes a DIRECTORY while the old fd
// lives on as an orphan inode) must produce exactly ONE warn across the
// per-line reopen loop, not one warn per doomed stream;
// (2) isFileLoggingActive() must report a merely-PENDING stream (async open
// still in flight) as not live — it feeds the #2864 mute decision.

function captureStderr(): { lines: string[]; restore: () => void } {
const lines: string[] = [];
const orig = process.stderr;
Object.defineProperty(process, "stderr", {
configurable: true,
value: { write: (chunk: unknown) => { lines.push(String(chunk)); return true; } },
});
return { lines, restore: () => Object.defineProperty(process, "stderr", { configurable: true, value: orig }) };
}

async function until(fn: () => boolean, what: string, timeoutMs = 3000): Promise<void> {
const start = Date.now();
while (!fn()) {
if (Date.now() - start > timeoutMs) throw new Error(`timed out waiting for ${what}`);
await new Promise((r) => setTimeout(r, 10));
}
}

test("mid-life leg death stays one-shot across the per-line reopen loop", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-logger-asyncfail-"));
const file = path.join(dir, "bili.log");
const cap = captureStderr();
const warns: string[] = [];
setLogCapture((level, msg) => { if (level === "warn") warns.push(msg); });
configureLogger(file);
try {
// Prove the leg healthy first: a DELIVERED byte closes any earlier
// episode (the one-shot flag resets on a landed write).
log("info", "arm-line");
await until(() => fs.existsSync(file) && fs.statSync(file).size > 0, "armed write flushed");
await new Promise((r) => setTimeout(r, 50)); // settle the flush-callback reset
fs.renameSync(file, file + ".bak"); // legal on Windows even while the fd is open
fs.mkdirSync(file); // path is now a directory → every reopen fails ASYNC (EISDIR on POSIX; dir-fd reject on win32)
for (let i = 0; i < 5; i++) {
log("info", `retry-loop-${i}`);
await new Promise((r) => setTimeout(r, 60)); // let this line's doomed stream fail+clear first
}
assert.equal(warns.length, 1, "one warn per episode, not one per doomed stream");
assert.ok(cap.lines.some((l) => l.includes("[warn]")), "the single warn reached stderr");
} finally {
setLogCapture(null);
cap.restore();
closeLogger();
rmrf(dir);
}
});

test("isFileLoggingActive reports false for a pending stream (open still in flight)", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-logger-asyncfail-"));
const file = path.join(dir, "bili.log");
configureLogger(file);
try {
assert.equal(isFileLoggingActive(), false, "right after configureLogger the open is still in flight");
log("info", "seed");
await until(() => fs.existsSync(file) && fs.statSync(file).size > 0, "delivered write");
assert.equal(isFileLoggingActive(), true);
} finally {
closeLogger();
rmrf(dir);
}
});
Loading