fix(ws): drop upgrades arriving after closeWebSocket instead of crashing
closeWebSocket() nulls both WebSocketServer references but cannot unregister
the `server.on("upgrade")` listeners that initWebSocket/initPtyWebSocket
installed on the shared http.Server. An upgrade landing in that window threw
TypeError: Cannot read properties of null (reading 'handleUpgrade')
from the listener — unhandled, so it killed the process mid-SIGTERM instead of
letting it exit gracefully, and no server came back up. Observed in
runtime/server.log right after a restart, with the dashboard then showing
"Mất kết nối" and nothing else.
The previous commit's TerminalView reconnect makes this near-certain rather
than rare: every open run console re-attaches to /ws-pty every 1.5s, so a
shutdown almost always has an upgrade in flight. Both listeners now destroy
the socket when their server is gone; clients retry, which is the correct
answer during a shutdown.
Regression test uses a real http.Server and raw upgrade requests — without the
guard the process dies and the test run hangs rather than reporting a failure.
This commit is contained in:
@@ -29,6 +29,14 @@ function initWebSocket(server) {
|
||||
server.on("upgrade", (req, socket, head) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname !== "/ws") return; // not ours — `/ws-pty/*` handles its own path.
|
||||
// closeWebSocket() nulls `wss` but cannot unregister this listener, so an
|
||||
// upgrade arriving mid-shutdown would throw an unhandled TypeError and take
|
||||
// the process down instead of letting it exit gracefully. Clients retry, so
|
||||
// dropping the socket is the correct answer here.
|
||||
if (!wss) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, req);
|
||||
});
|
||||
@@ -118,6 +126,12 @@ function initPtyWebSocket(server) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
// Same shutdown race as `/ws` above — and far easier to hit here, since
|
||||
// TerminalView re-attaches every 1.5s while a run console is open.
|
||||
if (!ptyWss) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
ptyWss.handleUpgrade(req, socket, head, (ws) => {
|
||||
ptyWss.emit("connection", ws, match[1]);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user