From a6f7b07a69596f704b2e4e7c70ff718561fea4fd Mon Sep 17 00:00:00 2001 From: Do Siki Date: Tue, 29 Sep 2026 12:12:55 +0200 Subject: [PATCH] fix(logger): stop graceful shutdown from writing after the logger ended The SIGTERM/SIGINT handlers were re-registered on every module evaluation, and a build worker receiving both signals logged again after logger.end(), raising ERR_STREAM_WRITE_AFTER_END during `next build`. Guard with an own flag (winston's readable-stream@3 Logger has no writableEnded) and register the handlers once per process with process.once. Closes MITHOME-126 Co-Authored-By: Claude Opus 5.5 --- proto/src/lib/logger.test.ts | 72 ++++++++++++++++++++++++++++++++++++ proto/src/lib/logger.ts | 19 +++++++++- 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/proto/src/lib/logger.test.ts b/proto/src/lib/logger.test.ts index bc61fe5..1ffbbb3 100755 --- a/proto/src/lib/logger.test.ts +++ b/proto/src/lib/logger.test.ts @@ -196,3 +196,75 @@ describe('Logger', () => { }) }) }) + +describe('Logger graceful shutdown', () => { + const SIGNALS = ['SIGTERM', 'SIGINT'] as const + const HANDLERS_KEY = Symbol.for('mozdit.logger.shutdownHandlersRegistered') + const processState = process as unknown as Record + type Signal = typeof SIGNALS[number] + let baseline: Record + + const addedListeners = (signal: Signal) => + process.listeners(signal).filter((listener) => !baseline[signal].includes(listener)) as NodeJS.SignalsListener[] + + const loadLogger = () => { + const { logger } = require('./logger') + // WHY: plain mock — winston's readable-stream@3 Logger exposes no `writableEnded` after end() + logger.end = jest.fn() + return logger + } + + beforeEach(() => { + jest.resetModules() + delete processState[HANDLERS_KEY] + baseline = { SIGTERM: process.listeners('SIGTERM'), SIGINT: process.listeners('SIGINT') } + }) + + afterEach(() => { + for (const signal of SIGNALS) { + addedListeners(signal).forEach((listener) => process.removeListener(signal, listener)) + } + delete processState[HANDLERS_KEY] + }) + + // Exploration: fails on the pre-fix code (MITHOME-126) + it('should not write the shutdown message again after the logger has ended', () => { + const logger = loadLogger() + const [onSigterm] = addedListeners('SIGTERM') + const [onSigint] = addedListeners('SIGINT') + + onSigterm('SIGTERM') + onSigint('SIGINT') + + expect(logger.info).toHaveBeenCalledTimes(1) + expect(logger.end).toHaveBeenCalledTimes(1) + }) + + it('should register the shutdown handlers only once per process', () => { + loadLogger() + jest.resetModules() + loadLogger() + + expect(addedListeners('SIGTERM')).toHaveLength(1) + expect(addedListeners('SIGINT')).toHaveLength(1) + }) + + // Preservation: passes on both the pre-fix and the fixed code + it('should register shutdown handlers for SIGTERM and SIGINT', () => { + loadLogger() + + expect(addedListeners('SIGTERM').length).toBeGreaterThanOrEqual(1) + expect(addedListeners('SIGINT').length).toBeGreaterThanOrEqual(1) + }) + + it('should log the shutdown message before ending the logger', () => { + const logger = loadLogger() + + addedListeners('SIGTERM')[0]('SIGTERM') + + expect(logger.info).toHaveBeenCalledWith('Initiating graceful shutdown...', { component: 'application' }) + expect(logger.end).toHaveBeenCalledTimes(1) + expect((logger.info as jest.Mock).mock.invocationCallOrder[0]) + .toBeLessThan((logger.end as jest.Mock).mock.invocationCallOrder[0]) + }) +}) diff --git a/proto/src/lib/logger.ts b/proto/src/lib/logger.ts index 322bbf7..6dae87d 100755 --- a/proto/src/lib/logger.ts +++ b/proto/src/lib/logger.ts @@ -155,12 +155,27 @@ export const withTiming = async ( } // Graceful shutdown +// WHY: `next build` workers (and dev HMR re-evaluations) load this module repeatedly and can +// receive both SIGTERM and SIGINT; an unguarded handler logged again after `logger.end()`, +// which threw ERR_STREAM_WRITE_AFTER_END. +// DECISION: register once per process (flag on `process`, where the listeners live), use +// `once` so our listener does not linger for repeated signals, and never write to an ended stream. +// The guard is our own flag: winston's Logger is a readable-stream@3 Transform without `writableEnded`. +const SHUTDOWN_HANDLERS_KEY = Symbol.for('mozdit.logger.shutdownHandlersRegistered') +let hasShutdownStarted = false + const gracefulShutdown = () => { + if (hasShutdownStarted) return + hasShutdownStarted = true createComponentLogger('application').info('Initiating graceful shutdown...') logger.end() } -process.on('SIGTERM', gracefulShutdown) -process.on('SIGINT', gracefulShutdown) +const processState = process as unknown as Record +if (!processState[SHUTDOWN_HANDLERS_KEY]) { + processState[SHUTDOWN_HANDLERS_KEY] = true + process.once('SIGTERM', gracefulShutdown) + process.once('SIGINT', gracefulShutdown) +} export default logger