From db81c2dada961f40c0882b5182adf2f34bb5c178 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 14 Jan 2025 17:59:08 +0800 Subject: [PATCH] fix: ensure `server.close()` only called once (#19204) --- packages/vite/src/node/preview.ts | 15 ++++++++-- packages/vite/src/node/server/index.ts | 41 ++++++++++++++++---------- 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts index 2031538cc5c356..614c16f8aaac06 100644 --- a/packages/vite/src/node/preview.ts +++ b/packages/vite/src/node/preview.ts @@ -148,14 +148,23 @@ export async function preview( const closeHttpServer = createServerCloseFn(httpServer) + // Promise used by `server.close()` to ensure `closeServer()` is only called once + let closeServerPromise: Promise | undefined + const closeServer = async () => { + teardownSIGTERMListener(closeServerAndExit) + await closeHttpServer() + server.resolvedUrls = null + } + const server: PreviewServer = { config, middlewares: app, httpServer, async close() { - teardownSIGTERMListener(closeServerAndExit) - await closeHttpServer() - server.resolvedUrls = null + if (!closeServerPromise) { + closeServerPromise = closeServer() + } + return closeServerPromise }, resolvedUrls: null, printUrls() { diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index 32a3371cef527b..486b245d9c71de 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -523,6 +523,28 @@ export async function _createServer( const devHtmlTransformFn = createDevHtmlTransformFn(config) + // Promise used by `server.close()` to ensure `closeServer()` is only called once + let closeServerPromise: Promise | undefined + const closeServer = async () => { + if (!middlewareMode) { + teardownSIGTERMListener(closeServerAndExit) + } + + await Promise.allSettled([ + watcher.close(), + ws.close(), + Promise.allSettled( + Object.values(server.environments).map((environment) => + environment.close(), + ), + ), + closeHttpServer(), + server._ssrCompatModuleRunner?.close(), + ]) + server.resolvedUrls = null + server._ssrCompatModuleRunner = undefined + } + let server: ViteDevServer = { config, middlewares, @@ -674,23 +696,10 @@ export async function _createServer( } }, async close() { - if (!middlewareMode) { - teardownSIGTERMListener(closeServerAndExit) + if (!closeServerPromise) { + closeServerPromise = closeServer() } - - await Promise.allSettled([ - watcher.close(), - ws.close(), - Promise.allSettled( - Object.values(server.environments).map((environment) => - environment.close(), - ), - ), - closeHttpServer(), - server._ssrCompatModuleRunner?.close(), - ]) - server.resolvedUrls = null - server._ssrCompatModuleRunner = undefined + return closeServerPromise }, printUrls() { if (server.resolvedUrls) {