Skip to content

Commit

Permalink
fix: use shared sigterm callback (vitejs#19203)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Jan 14, 2025
1 parent 3bd55bc commit 47039f4
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1535,20 +1535,34 @@ export function partialEncodeURIPath(uri: string): string {
return filePath.replaceAll('%', '%25') + postfix
}

type SigtermCallback = (signal?: 'SIGTERM', exitCode?: number) => Promise<void>

// Use a shared callback when attaching sigterm listeners to avoid `MaxListenersExceededWarning`
const sigtermCallbacks = new Set<SigtermCallback>()
const parentSigtermCallback: SigtermCallback = async (signal, exitCode) => {
await Promise.all([...sigtermCallbacks].map((cb) => cb(signal, exitCode)))
}

export const setupSIGTERMListener = (
callback: (signal?: 'SIGTERM', exitCode?: number) => Promise<void>,
): void => {
process.once('SIGTERM', callback)
if (process.env.CI !== 'true') {
process.stdin.on('end', callback)
if (sigtermCallbacks.size === 0) {
process.once('SIGTERM', parentSigtermCallback)
if (process.env.CI !== 'true') {
process.stdin.on('end', parentSigtermCallback)
}
}
sigtermCallbacks.add(callback)
}

export const teardownSIGTERMListener = (
callback: Parameters<typeof setupSIGTERMListener>[0],
): void => {
process.off('SIGTERM', callback)
if (process.env.CI !== 'true') {
process.stdin.off('end', callback)
sigtermCallbacks.delete(callback)
if (sigtermCallbacks.size === 0) {
process.off('SIGTERM', parentSigtermCallback)
if (process.env.CI !== 'true') {
process.stdin.off('end', parentSigtermCallback)
}
}
}

0 comments on commit 47039f4

Please sign in to comment.