Unverified Commit 0f7251fc authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

fix(dev-server): Terminate turbopack HMR websocket connections during exit (#75344)

Without this change, an open browser tab with an HMR websocket subscription (which is very common) can prevent next.js's dev server from exiting cleanly (falls back to a SIGKILL after a 100ms timeout).

That's bad (aside from the extra 100ms delay) because it prevents

```
            await Promise.all([
              nextServer?.close().catch(console.error),
              cleanupListeners?.runAll().catch(console.error),
            ])
```

from running, which can prevent us from flushing task statistics (https://github.com/vercel/next.js/pull/67164).

You can test this with:

```
NEXT_EXIT_TIMEOUT_MS=200000 node_modules/.bin/next dev
```

or

```
NEXT_EXIT_TIMEOUT_MS=200000 node_modules/.bin/next dev --turbo
```

Prior to this PR, after hitting ctrl+c, the processes will hang if there's a connected browser window open.

After this PR, the processes exit instantly.
parent 28ac6289
...@@ -72,16 +72,11 @@ class EventStream { ...@@ -72,16 +72,11 @@ class EventStream {
this.clients = new Set() this.clients = new Set()
} }
everyClient(fn: (client: ws) => void) {
for (const client of this.clients) {
fn(client)
}
}
close() { close() {
this.everyClient((client) => { for (const wsClient of this.clients) {
client.close() // it's okay to not cleanly close these websocket connections, this is dev
}) wsClient.terminate()
}
this.clients.clear() this.clients.clear()
} }
...@@ -93,9 +88,9 @@ class EventStream { ...@@ -93,9 +88,9 @@ class EventStream {
} }
publish(payload: any) { publish(payload: any) {
this.everyClient((client) => { for (const wsClient of this.clients) {
client.send(JSON.stringify(payload)) wsClient.send(JSON.stringify(payload))
}) }
} }
} }
......
...@@ -1059,6 +1059,13 @@ export async function createHotReloaderTurbopack( ...@@ -1059,6 +1059,13 @@ export async function createHotReloaderTurbopack(
} }
}) })
}, },
close() {
for (const wsClient of clients) {
// it's okay to not cleanly close these websocket connections, this is dev
wsClient.terminate()
}
clients.clear()
},
} }
handleEntrypointsSubscription().catch((err) => { handleEntrypointsSubscription().catch((err) => {
......
...@@ -182,4 +182,5 @@ export interface NextJsHotReloaderInterface { ...@@ -182,4 +182,5 @@ export interface NextJsHotReloaderInterface {
definition: RouteDefinition | undefined definition: RouteDefinition | undefined
url?: string url?: string
}): Promise<void> }): Promise<void>
close(): void
} }
...@@ -1595,4 +1595,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1595,4 +1595,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
}) })
}) })
} }
public close() {
this.webpackHotMiddleware?.close()
}
} }
...@@ -103,4 +103,8 @@ export class DevBundlerService { ...@@ -103,4 +103,8 @@ export class DevBundlerService {
data: this.appIsrManifest, data: this.appIsrManifest,
}) })
} }
public close() {
this.bundler.hotReloader.close()
}
} }
...@@ -9,6 +9,8 @@ export type ServerInitResult = { ...@@ -9,6 +9,8 @@ export type ServerInitResult = {
requestHandler: RequestHandler requestHandler: RequestHandler
upgradeHandler: UpgradeHandler upgradeHandler: UpgradeHandler
server: NextServer server: NextServer
// Make an effort to close upgraded HTTP requests (e.g. Turbopack HMR websockets)
closeUpgraded: () => void
} }
let initializations: Record<string, Promise<ServerInitResult> | undefined> = {} let initializations: Record<string, Promise<ServerInitResult> | undefined> = {}
...@@ -109,6 +111,9 @@ async function initializeImpl(opts: { ...@@ -109,6 +111,9 @@ async function initializeImpl(opts: {
requestHandler, requestHandler,
upgradeHandler, upgradeHandler,
server, server,
closeUpgraded() {
opts.bundlerService?.close()
},
} }
} }
......
...@@ -751,5 +751,12 @@ export async function initialize(opts: { ...@@ -751,5 +751,12 @@ export async function initialize(opts: {
} }
} }
return { requestHandler, upgradeHandler, server: handlers.server } return {
requestHandler,
upgradeHandler,
server: handlers.server,
closeUpgraded() {
developmentBundler?.hotReloader?.close()
},
}
} }
...@@ -289,6 +289,7 @@ export async function startServer( ...@@ -289,6 +289,7 @@ export async function startServer(
try { try {
let cleanupStarted = false let cleanupStarted = false
let closeUpgraded: (() => void) | null = null
const cleanup = () => { const cleanup = () => {
if (cleanupStarted) { if (cleanupStarted) {
// We can get duplicate signals, e.g. when `ctrl+c` is used in an // We can get duplicate signals, e.g. when `ctrl+c` is used in an
...@@ -303,12 +304,16 @@ export async function startServer( ...@@ -303,12 +304,16 @@ export async function startServer(
// first, stop accepting new connections and finish pending requests, // first, stop accepting new connections and finish pending requests,
// because they might affect `nextServer.close()` (e.g. by scheduling an `after`) // because they might affect `nextServer.close()` (e.g. by scheduling an `after`)
await new Promise<void>((res) => await new Promise<void>((res) => {
server.close((err) => { server.close((err) => {
if (err) console.error(err) if (err) console.error(err)
res() res()
}) })
) if (isDev) {
server.closeAllConnections()
closeUpgraded?.()
}
})
// now that no new requests can come in, clean up the rest // now that no new requests can come in, clean up the rest
await Promise.all([ await Promise.all([
...@@ -360,6 +365,7 @@ export async function startServer( ...@@ -360,6 +365,7 @@ export async function startServer(
requestHandler = initResult.requestHandler requestHandler = initResult.requestHandler
upgradeHandler = initResult.upgradeHandler upgradeHandler = initResult.upgradeHandler
nextServer = initResult.server nextServer = initResult.server
closeUpgraded = initResult.closeUpgraded
const startServerProcessDuration = const startServerProcessDuration =
performance.mark('next-start-end') && performance.mark('next-start-end') &&
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment