Repository navigation
fix(ws): leave upgrade requests for other paths to other listeners - #18501
Conversation
kamilmysliwiec
left a comment
There was a problem hiding this comment.
Thanks, the fix is right: today the adapter destroys sockets that another upgrade listener has just claimed, so GraphQL subscriptions on the same server break whichever listener runs first.
One gap: when another listener is present, an upgrade for a path that no listener serves is now closed by nobody. @nestjs/graphql follows the same rule, so with both installed such a socket stays open until the client hangs up. The HTTP server's timeouts no longer apply after upgrade, and the gateways never see the socket.
Could you close it after a short delay when nothing has been written to it, as engine.io does for the same case? Something like:
if (!isRequestDelegated) {
socket.on(ERROR_EVENT, () => socket.destroy());
if (httpServer.listenerCount('upgrade') <= 1) {
socket.destroy();
} else {
// A listener that claims the socket answers the handshake, so a socket
// nothing has been written to by then is one that nobody claimed.
setTimeout(() => {
if (socket.writable && socket.bytesWritten <= 0) {
socket.destroy();
}
}, 1000).unref();
}
}plus a test where a second listener ignores the path and the socket gets closed (fake timers are fine).
| if (!isRequestDelegated) { | ||
| socket.destroy(); | ||
| socket.on(ERROR_EVENT, () => socket.destroy()); | ||
| if (httpServer.listenerCount('upgrade') <= 1) { |
There was a problem hiding this comment.
@kamilmysliwiec about the 1s timer you suggested above: upgrade listener that authenticates before handleUpgrade (pattern from ws README, "Client authentication") writes nothing until auth is done, so when auth takes longer than delay (cold db, remote jwks) adapter would destroy socket that other listener alredy claimed
httpServer.on('upgrade', (req, socket, head) => {
socket.on('error', onSocketError);
authenticate(req, (err, client) => { // > 1s
wss.handleUpgrade(req, socket, head, ws => wss.emit('connection', ws, req, client));
});
});engine.io has same trade-off and exposes it as destroyUpgrade / destroyUpgradeTimeout, maybe worth same knob in WsAdapterOptions so apps with slow upgrade auth can raise or turn it off
There was a problem hiding this comment.
Thank you for pointing this out. I have made the delay configurable through a new unclaimedUpgradeTimeout option in WsAdapterOptions, following the approach engine.io takes with destroyUpgradeTimeout. It defaults to 1000 ms, an application with a slow authentication step can raise it, and setting it to 0 leaves such sockets to the other listeners entirely.
When another upgrade listener is present, an upgrade for a path that no listener serves was left open until the client hung up. Close it once "unclaimedUpgradeTimeout" (1000 ms by default) has passed with nothing written to it, as engine.io does. A listener that answers the handshake late, for example after a slow authentication, can be given more time, or the timer can be turned off with 0.
|
Thank you for the review, @kamilmysliwiec. I have pushed the change you suggested: when another To address the concern raised in the review thread about listeners that authenticate before answering the handshake, the delay is configurable through a new |
kamilmysliwiec
left a comment
There was a problem hiding this comment.
Thanks, the option is fine by me: it covers the slow-authentication case @thekhegay raised, the same way engine.io does.
One problem with the check I suggested, sorry: bytesWritten counts everything written on the connection, not just the handshake. A client that sends a plain request first and then an upgrade on the same keep-alive connection arrives with bytesWritten already above 0 (124 bytes after a short response in my test), so the timer never closes its socket. Comparing against the value at upgrade time covers that:
const writtenBeforeUpgrade = (socket as Socket).bytesWritten;
setTimeout(() => {
if (socket.writable && (socket as Socket).bytesWritten <= writtenBeforeUpgrade) {
socket.destroy();
}
}, this.unclaimedUpgradeTimeout).unref();A TLS handshake doesn't count towards bytesWritten (0 on a fresh HTTPS connection), so HTTPS needs nothing else. Could you add a test for a socket that arrives with bytes already written?
bytesWritten counts everything sent on the connection, so on a keep-alive connection it already includes the responses to earlier requests and the timer never closed such a socket. Compare against the count at upgrade time instead.
|
Thank you for catching that, @kamilmysliwiec. I have pushed the change: the timer now compares |
kamilmysliwiec
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround.
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
When a
WsAdaptergateway shares the application's HTTP server, the adapter'supgradelistener destroys the socket of every upgrade request whose path does not match one of its gateways. If another listener on the same server owns that path, the connection is gone before that listener can handle it.A common case is GraphQL subscriptions next to a
WsAdaptergateway.@nestjs/graphqlroutes/graphqlupgrades from its ownupgradelistener. When theWsAdapterlistener runs first, the client getssocket hang up(ECONNRESET) and the subscription never opens.@nestjs/graphqlalready avoids this on its side: it closes an unclaimed socket only when it is the server's singleupgradelistener.Issue Number: N/A
What is the new behavior?
For a path that none of its gateways serves, the
WsAdapterlistener now:upgradelistener, so the previous behavior is unchanged for applications without other listeners;unclaimedUpgradeTimeout(1000 ms by default) has passed with nothing written to it since the upgrade. A listener that claims a socket answers the handshake, so a socket that nothing has been written to by then is one that nobody claimed. The count of bytes written covers the whole connection, so it is compared against its value at the upgrade, which on a keep-alive connection already includes the responses to earlier requests. engine.io handles the same case this way. Without this, such a socket would stay open until the client hangs up, since the HTTP server's timeouts no longer apply afterupgrade;errorlistener that destroys the socket, because Node removes its own listeners before emittingupgrade, and a connection reset on a socket nobody claims would otherwise raise an unhandlederrorevent.unclaimedUpgradeTimeoutis a newWsAdapterOptionssetting. An application whose other listener answers the handshake late, for example after a slow authentication, can raise it, or set it to0to leave such sockets to the other listeners entirely:Tests cover these cases:
/graphqlhandled by a secondWebSocketServeron the same server opens;unclaimedUpgradeTimeout, and never when it is0, while a socket that the other listener answered is kept;Does this PR introduce a breaking change?
Other information
As in
@nestjs/graphql, a socket that another listener sees but does not claim is left to that listener until the timeout. The previous behavior is kept for a gateway on its own port, since the adapter's server has no otherupgradelisteners.Results with Node.js 22: the full build,
prettierandoxlintpass, and theplatform-wsandwebsocketstest suites pass with 213 tests. The test for a socket that arrives with bytes already written fails with the previous check and passes with this one.