From e815b72507acb8af2962cc992784e905bc4368ed Mon Sep 17 00:00:00 2001 From: Charlie Ray Date: Thu, 21 Nov 2024 10:17:16 -0600 Subject: [PATCH] fix(api-server): prevent race condition in server restart process --- packages/api-server/src/serverManager.ts | 45 ++++++++++++++---------- 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/packages/api-server/src/serverManager.ts b/packages/api-server/src/serverManager.ts index 4027255bcee1..0909fd87c009 100644 --- a/packages/api-server/src/serverManager.ts +++ b/packages/api-server/src/serverManager.ts @@ -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((resolve) => { - console.log(chalk.yellow('Shutting down API server.')) - this.httpServerProcess!.on('exit', () => resolve()) - this.httpServerProcess!.kill() - }), - new Promise((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((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() + }) } }