Skip to content

Returning a response with a body during an upgrade crashes the Node http server on Windows #139

Open
@eltigerchino

Description

@eltigerchino

Environment

Windows 11 24H2
Node.js v18.20.5
[email protected]

Reproduction

https://github.com/eltigerchino/crossws-windows-socket-error-repro
Reproduction steps included in the repository README.md

Describe the bug

Returning/throwing a Response that has a body during the upgrade hook on a Windows machine causes the Node http server to crash.

Additional context

Related function:

async function sendResponse(socket: Duplex, res: Response) {
const head = [
`HTTP/1.1 ${res.status || 200} ${res.statusText || ""}`,
...[...res.headers.entries()].map(
([key, value]) =>
`${encodeURIComponent(key)}: ${encodeURIComponent(value)}`,
),
];
socket.write(head.join("\r\n") + "\r\n\r\n");
if (res.body) {
for await (const chunk of res.body) {
socket.write(chunk);
}
}
return new Promise<void>((resolve) => {
socket.end(resolve);
});
}

I experimented a bit and calling socket.destroy() after the upgrade seems to prevent the crash but I don't think that's the right solution?

I also tried awaiting the socket.write(chunk) operations by passing it a callback that resolves a Promise but that doesn't solve the issue either (it just ensures writes are all done before socket.end())

Logs

node:events:495
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (node:internal/stream_base_commons:217:20)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}

Node.js v18.20.5
 ELIFECYCLE  Command failed with exit code 1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions