mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-31 04:12:10 +03:00
* fix(logs): stop an async EPIPE becoming an uncaughtException loop A raw process.stderr.write into a broken pipe fails asynchronously, so the try/catch around it never sees the failure. The stream emits 'error'; with no listener on process.stderr Node re-throws it as an uncaughtException; the framework's handler logs that through console.error; and the patched console writes back into the same dead stream. That closes a self-sustaining loop. Attach an 'error' listener to process.stdout and process.stderr. Node only converts a stream 'error' into an uncaughtException when the emitter has no listener, so the listener alone terminates the cycle. Measured in a spawn harness over 1.5s: 3,387 uncaught exceptions before, 0 after. Absorb EPIPE only. Attaching a listener otherwise makes every stream error on those streams non-fatal process-wide, so ENOSPC, EBADF and the rest are re-raised on a fresh stack to preserve today's crash semantics. The accompanying test asserts that in a child process, because node:test attributes any in-process uncaughtException to the running test. Add a test-only reset() to undo the patched console and the listeners: test:unit:fast runs --test-isolation=none, so leaked state would reach every subsequent test file. Refs #8181 * fix(logs): bound interceptor disk writes and self-heal a missing log dir Two write-path defects in the same file, both independent of the loop itself. writeEntry appended with no rate limit, so while the loop spun it wrote unbounded lines to disk (4.3 GB in 90 minutes in the reported incident). Apply the same policy #1006 established in structuredLogger -- 50 writes/sec, a 5s dedup window, a bounded tracking map -- but scoped to `error` entries only. That scoping is deliberate: structuredLogger applies its limiter solely to error() and fatal(), whereas writeEntry serves all five of log/info/warn/error/debug across ~800 non-error call sites. Capping those would silently drop routine logging from the Console Log Viewer's file. A test asserts non-error levels stay unlimited. ensureDir() ran once in initConsoleInterceptor and never again, so a log directory removed while the process was alive made every later append throw ENOENT into a bare catch -- console file-logging then stopped permanently with nothing surfaced anywhere. Recreate the directory and retry once, and report the failure exactly once through the unpatched stderr so it cannot recurse through the patched console or become a flood of its own. Refs #8181 * fix(logs): skip raw stderr writes to a stream already known dead error() and fatal() write with a raw process.stderr.write wrapped in try {} catch {}. The comment on that line says the raw write exists to avoid Next.js console patching "that triggers EPIPE loops" -- but on a broken pipe the write fails asynchronously, so the catch never sees it, and the resulting stream error is what ignites the loop. Skip the write when the stream is already destroyed or ended, falling through to the file sink as before. The listener added earlier is what breaks the cycle; this stops the ignition point firing into a dead stream in the first place. The existing try/catch is retained for the synchronous cases it always covered. The #1006 suppression policy and its call sites are untouched. Refs #8181 * fix(logs): install the stdio guard independently of console interception initConsoleInterceptor() returns early when APP_LOG_TO_FILE=false, and when the log directory cannot be created. The stdio 'error' listeners were installed after that return, so in those supported configurations no listener was attached at all. structuredLogger's raw stderr writes still happen there, and an ordinary broken pipe raises an async EPIPE without destroyed or writableEnded being set first, so the guard in safeStderrWrite does not cover it either. The loop this change exists to prevent was therefore still reachable with file logging turned off. Extract installStdioErrorGuard() and call it before the early return. It is idempotent and cleared by reset(). A new test asserts, in a child process, that both listeners are present when APP_LOG_TO_FILE=false. Also restore APP_LOG_TO_FILE and APP_LOG_FILE_PATH in the test's after() hook. test:unit:fast runs with --test-isolation=none, so the previous top-level mutations leaked into later test files, leaving file logging enabled against a path this file deletes. Refs #8181
108 lines
4.4 KiB
TypeScript
108 lines
4.4 KiB
TypeScript
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs";
|
|
import { spawnSync } from "node:child_process";
|
|
import { fileURLToPath } from "node:url";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
// Issue #8181: `error()` and `fatal()` write to stderr with a raw `process.stderr.write`
|
|
// wrapped in `try {} catch {}`. The comment on that line says the raw write exists to avoid
|
|
// Next.js console patching "that triggers EPIPE loops" — but on a broken pipe the write fails
|
|
// ASYNCHRONOUSLY, so the catch never sees it. The stream emits 'error', and with no listener
|
|
// attached Node re-throws it as an uncaughtException. That is the ignition point of the loop.
|
|
//
|
|
// consoleInterceptor now attaches the listener that breaks the cycle; this guard is defence in
|
|
// depth so a known-dead stream is not written to at all.
|
|
const { __structuredLoggerInternals } =
|
|
await import("../../../src/shared/utils/structuredLogger.ts");
|
|
|
|
test("isStreamWritable rejects a destroyed stream", () => {
|
|
assert.equal(__structuredLoggerInternals.isStreamWritable({ destroyed: true }), false);
|
|
});
|
|
|
|
test("isStreamWritable rejects an ended stream", () => {
|
|
assert.equal(__structuredLoggerInternals.isStreamWritable({ writableEnded: true }), false);
|
|
});
|
|
|
|
test("isStreamWritable accepts a healthy stream", () => {
|
|
assert.equal(
|
|
__structuredLoggerInternals.isStreamWritable({ destroyed: false, writableEnded: false }),
|
|
true
|
|
);
|
|
// A stream object exposing neither flag (some fakes, and older stream shims) must not be
|
|
// treated as dead — the guard is only allowed to skip writes it is certain about.
|
|
assert.equal(__structuredLoggerInternals.isStreamWritable({}), true);
|
|
});
|
|
|
|
// The behavioural half. process.stderr cannot be destroyed in-process — the test runner writes
|
|
// its own diagnostics there — so this runs in a child, which also proves the property that
|
|
// actually matters: the process survives and file logging still happens.
|
|
test("error() with a destroyed stderr does not crash, and still writes to the log file (#8181)", () => {
|
|
const loggerPath = fileURLToPath(
|
|
new URL("../../../src/shared/utils/structuredLogger.ts", import.meta.url)
|
|
);
|
|
const dir = mkdtempSync(join(tmpdir(), "omniroute-rawwrite-8181-"));
|
|
const logFile = join(dir, "logs", "application", "app.log");
|
|
const childFile = join(dir, "probe.mts");
|
|
|
|
writeFileSync(
|
|
childFile,
|
|
[
|
|
`process.env.APP_LOG_TO_FILE = "true";`,
|
|
`process.env.APP_LOG_FILE_PATH = ${JSON.stringify(logFile)};`,
|
|
`process.env.APP_LOG_LEVEL = "debug";`,
|
|
`const { createLogger } = await import(${JSON.stringify(loggerPath)});`,
|
|
`const log = createLogger("guard-probe");`,
|
|
`process.stderr.destroy();`, // the dead-stream condition
|
|
`log.error("entry after stderr destroyed");`,
|
|
`log.fatal("fatal after stderr destroyed");`,
|
|
`setTimeout(() => process.exit(0), 200);`,
|
|
].join("\n")
|
|
);
|
|
|
|
const result = spawnSync(process.execPath, ["--import", "tsx/esm", childFile], {
|
|
encoding: "utf8",
|
|
timeout: 30_000,
|
|
env: { ...process.env, DISABLE_SQLITE_AUTO_BACKUP: "true" },
|
|
});
|
|
|
|
assert.equal(
|
|
result.status,
|
|
0,
|
|
`logging to a destroyed stderr must not crash the process; got exit ${result.status}`
|
|
);
|
|
|
|
assert.ok(existsSync(logFile), "the file sink must still receive entries when stderr is dead");
|
|
const lines = readFileSync(logFile, "utf8")
|
|
.trim()
|
|
.split("\n")
|
|
.filter(Boolean)
|
|
.map((l) => JSON.parse(l));
|
|
const messages = lines.map((l: { message?: string }) => l.message);
|
|
assert.ok(
|
|
messages.includes("entry after stderr destroyed"),
|
|
"error() must still reach writeToFile after the stderr write is skipped"
|
|
);
|
|
assert.ok(
|
|
messages.includes("fatal after stderr destroyed"),
|
|
"fatal() must still reach writeToFile after the stderr write is skipped"
|
|
);
|
|
|
|
rmSync(dir, { recursive: true, force: true });
|
|
});
|
|
|
|
// Guard against collateral damage: #1006's suppression policy must be untouched by this change.
|
|
test("the #1006 dedup/rate-limit policy is unchanged", () => {
|
|
assert.equal(
|
|
__structuredLoggerInternals.MAX_TRACKED_ERRORS,
|
|
500,
|
|
"MAX_TRACKED_ERRORS is part of the accepted #1006 policy and must not drift"
|
|
);
|
|
assert.equal(
|
|
typeof __structuredLoggerInternals.pruneRecentErrors,
|
|
"function",
|
|
"pruneRecentErrors must remain exported for the existing dedup-bound test"
|
|
);
|
|
});
|