Skip to content

Commit

Permalink
fix: ensure server.close() only called once (vitejs#19204)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Jan 14, 2025
1 parent 47039f4 commit db81c2d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 19 deletions.
15 changes: 12 additions & 3 deletions packages/vite/src/node/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> | 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() {
Expand Down
41 changes: 25 additions & 16 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> | 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,
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit db81c2d

Please sign in to comment.