Skip to content

Commit

Permalink
fix(api-server): prevent race condition in server restart process
Browse files Browse the repository at this point in the history
  • Loading branch information
o0charlie0o committed Nov 21, 2024
1 parent 05dca60 commit e815b72
Showing 1 changed file with 27 additions and 18 deletions.
45 changes: 27 additions & 18 deletions packages/api-server/src/serverManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,24 +94,33 @@ export class ServerManager {

// Try to gracefully close the server
// If it doesn't close within 2 seconds, forcefully close it
await Promise.race([
new Promise<void>((resolve) => {
console.log(chalk.yellow('Shutting down API server.'))
this.httpServerProcess!.on('exit', () => resolve())
this.httpServerProcess!.kill()
}),
new Promise<void>((resolve) =>
setTimeout(() => {
console.log(
chalk.yellow(
'API server did not exit within 2 seconds, forcefully closing it.',
),
)
this.httpServerProcess!.kill('SIGKILL')
resolve()
}, 2000),
),
])
await new Promise<void>((resolve) => {
console.log(chalk.yellow('Shutting down API server.'))

const cleanup = () => {
this.httpServerProcess?.removeAllListeners('exit')
clearTimeout(forceKillTimeout)
}

this.httpServerProcess!.on('exit', () => {
console.log(chalk.yellow('API server exited.'))
cleanup()
resolve()
})

const forceKillTimeout = setTimeout(() => {
console.log(
chalk.yellow(
'API server did not exit within 2 seconds, forcefully closing it.',
),
)
cleanup()
this.httpServerProcess!.kill('SIGKILL')
resolve()
}, 2000)

this.httpServerProcess!.kill()
})
}
}

Expand Down

0 comments on commit e815b72

Please sign in to comment.