Repository navigation
fix(socket.io): keep the message stream alive when a handler throws - #17666
Conversation
c0928e9 to
f2118a1
Compare
f2118a1 to
e13b63d
Compare
micalevisk
left a comment
There was a problem hiding this comment.
Thanks for the fix and the clear write-up. Porting the ws guard makes sense, and the new test does fail without the change. A few points; the first is the one that matters.
1. The guard only catches sync throws, which gateways can't produce; the async case still kills the stream
Through the framework's wiring, callback is always an async function (WsProxy.create for static gateways, createRequestScopedHandler for request-scoped ones), and transform wraps the async pickResult (here). So callback(data, ack) can't throw synchronously in a real gateway, and the new try/catch is only reached when bindMessageHandlers is called directly, as the test does.
The failure that can happen is async. When a handler throws and an app-level exception filter rethrows (e.g. a @Catch() that only handles WsException), WsProxy.handleError throws inside the proxy's catch and the promise rejects. The inner observable errors, and mergeMap tears down that event's stream for the client. There's no error callback on subscribe, so RxJS rethrows from a setTimeout: an uncaught exception, which exits Node by default.
platform-ws has the same gap: the guard from #17635 is sync-only too (bindMessageHandlers).
Moving the guard onto the inner observable covers both cases:
// packages/platform-socket.io/adapters/io-adapter.ts
mergeMap((payload: any) => {
const { data, ack } = this.mapPayload(payload);
return defer(() => transform(callback(data, ack))).pipe(
filter((response: any) => !isNil(response)),
map((response: any) => [response, ack, isAckHandledManually]),
catchError(() => EMPTY),
);
}),// packages/platform-ws/adapters/ws-adapter.ts, in bindMessageHandlers
mergeMap(data =>
this.bindMessageHandler(data, handlersMap, transform).pipe(
filter(result => !isNil(result)),
catchError(() => EMPTY),
),
),defer also turns a sync throw into an error notification, so the let result / try block goes away. mergeMap has no concurrency limit, so defer subscribes at the same moment the direct call ran and message order doesn't change. With both changes applied locally, the spec below passes, along with the platform-socket.io, platform-ws and websockets unit specs and integration/websockets.
One behaviour question: on the reachable path this turns a process crash into a silent drop. I'd lean towards logging it rather than swallowing it, since a filter that rethrows is an app bug. Whether to log was left open in #17624, though, so that's a maintainer call.
Spec for the async case (fails at this PR's head with expected 1 to be 2)
import { EventEmitter } from 'events';
import { config, from, mergeAll } from 'rxjs';
import { WsProxy } from '../../websockets/context/ws-proxy.js';
import { WsExceptionsHandler } from '../../websockets/exceptions/ws-exceptions-handler.js';
import { WebSocketsController } from '../../websockets/web-sockets-controller.js';
import { IoAdapter } from '../adapters/io-adapter.js';
it('should not let a rejected handler tear down the message stream', async () => {
const unhandled: unknown[] = [];
config.onUnhandledError = err => unhandled.push(err);
// an app-level @Catch() filter that rethrows
const exceptionsHandler = new WsExceptionsHandler();
exceptionsHandler.setCustomFilters([
{
exceptionMetatypes: [],
func: (exception: any) => {
throw exception;
},
},
] as any);
const socket = new EventEmitter() as any;
const replies: any[] = [];
socket.on('reply', (payload: any) => replies.push(payload));
let calls = 0;
const callback = new WsProxy()
.create(
async () => {
if (++calls === 1) throw new Error('handler blew up');
return { event: 'reply', data: 'ok' };
},
exceptionsHandler,
'test-event',
)
.bind(undefined, socket);
// same transform WebSocketsController.subscribeMessages passes in
const transform = (data: any) =>
from(WebSocketsController.prototype.pickResult.call(undefined, data)).pipe(
mergeAll(),
);
new IoAdapter().bindMessageHandlers(
socket,
[
{
message: 'test-event',
methodName: 'm',
callback,
isAckHandledManually: false,
},
],
transform,
);
const flush = () => new Promise(resolve => setTimeout(resolve, 5));
socket.emit('test-event', {});
await flush();
socket.emit('test-event', {});
await flush();
config.onUnhandledError = null;
expect(calls).toBe(2);
expect(replies).toEqual(['ok']);
expect(unhandled).toEqual([]);
});2. The code comment overstates the impact for socket.io
This comment says a throw "would silence every later message for this client". In socket.io each event gets its own stream (handlers.forEach → fromEvent(socket, message)), so only that event goes silent; the PR description gets this right. The wording comes from the ws adapter, which uses one stream per client.
3. Tests
- The two
setTimeout(20)waits (L71, L73) aren't needed. Withof()the whole chain runs synchronously, and without them the test still fails when the fix is reverted. - The ack path isn't covered: a message that throws shouldn't be acked, and the next one should be.
- Adding the async case above would pin point 1.
4. Duplication
The guard now lives in both adapters. A shared helper on AbstractWsAdapter looks tempting, but both platform packages declare @nestjs/websockets: ^12.0.0 as a peer. A newer adapter installed next to an older @nestjs/websockets would then call a method that doesn't exist. Keeping it local makes sense, and with defer/catchError it's one line anyway.
5. PR description
"Issue Number: N/A" could link #17624 and #17635. It may also help to say that the repro calls the adapter directly, since gateways can't hit the sync path.
Regressions
- As-is: nothing changes for gateway users, since they can't reach the sync path. Code calling
bindMessageHandlersdirectly with a sync callback goes from crashing the process to silently dropping that message; there's no ack, as before. Other events and later messages are unaffected. - With the suggestion: the async path goes from crash to silent drop (see the logging question in point 1).
- Same pattern elsewhere:
microservices'transformToObservablebuilds a new observable per request rather than a long-lived per-socket stream, so it isn't affected. There are no custombindMessageHandlersimplementations inintegration/orsample/.
a handler that throws synchronously escapes the mergeMap in bindMessageHandlers and errors the stream, and through the framework wiring the callback is always async, so a handler whose error filter rethrows rejects the same way: the stream dies, that event goes silent for the client and rxjs reports an unhandled error the ws adapter got a sync-only guard for this in 39fbdda, the socket.io adapter had none, and neither guard covers the async case, which is the only one a real gateway can reach both adapters now defer the handler call and catchError the stream, so a sync throw and a rejected handler only drop that one message and the stream survives. a filter that rethrows is an app bug, so the failure gets logged through the adapter logger instead of being swallowed silently
e13b63d to
cbf9abd
Compare
|
thanks for the review @micalevisk, the async rethrow case was the real gap. the guard now lives on the inner observable with defer + catchError in both adapters and the rethrown filter error gets logged instead of silently dropped (the log-vs-swallow policy stays a maintainer call like in the #17624 thread). the async spec, the ack-path spec and the ws mirror are in, 14 specs green on the touched files and 128 across the three packages, and the pr description now links #17624/#17635 with the adapter-direct note |
Run prettier over the files touched by the stream guard. lint:ci only runs oxlint, so the formatting drift would otherwise land and be reformatted by the next contributor's lint-staged run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
| datasource | package | from | to | | ---------- | ------------------------ | ------ | ------ | | npm | @nestjs/common | 12.0.1 | 12.1.0 | | npm | @nestjs/core | 12.0.1 | 12.1.0 | | npm | @nestjs/platform-express | 12.0.1 | 12.1.0 | ## [v12.1.0](https://github.com/nestjs/nest/releases/tag/v12.1.0) ##### v12.1.0 (2026-09-23) ##### Bug fixes - `core` - [#17838](nestjs/nest#17838) fix(core): inherit optional ctor params when the ctor is not redeclared ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17819](nestjs/nest#17819) fix(core): name the module when metadata entries are invalid ([@thekhegay](https://github.com/thekhegay)) - `microservices` - [#17828](nestjs/nest#17828) fix(microservices): let the redis client retry after a failed connect ([@hktitof](https://github.com/hktitof)) - [#17810](nestjs/nest#17810) fix(microservices): fail every pending request when a callback throws ([@hktitof](https://github.com/hktitof)) ##### Enhancements - `core` - [#17846](nestjs/nest#17846) fix(core): do not skip subsequent middleware after a transient one ([@lehafari](https://github.com/lehafari)) - [#17840](nestjs/nest#17840) fix(core): preserve route handler names ([@Grmiade](https://github.com/Grmiade)) - `common`, `core` - [#17713](nestjs/nest#17713) feat(core): add support for array of global prefixes ([@micalevisk](https://github.com/micalevisk)) - [#17834](nestjs/nest#17834) feat(common,core): add built-in, adapter-agnostic cookies ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - `platform-fastify` - [#17824](nestjs/nest#17824) fix(fastify): honor Nest forceCloseConnections in initHttpServer ([@xia-chao](https://github.com/xia-chao)) - `common` - [#17827](nestjs/nest#17827) fix(common): apply the ParseDatePipe default to every missing value ([@xia-chao](https://github.com/xia-chao)) - `platform-fastify`, `testing` - [#17835](nestjs/nest#17835) feat(fastify): add file upload interceptors backed by [@fastify/multipart](https://github.com/fastify/multipart) ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - `common`, `core`, `platform-fastify` - [#17836](nestjs/nest#17836) feat(common,core,fastify): built-in CSRF protection and security headers ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) ##### Committers: 9 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Alejandro ([@lehafari](https://github.com/lehafari)) - Chris Z ([@haimingZZ](https://github.com/haimingZZ)) - Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - Jérémy Fauvel ([@Grmiade](https://github.com/Grmiade)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk)) - Roman Khegay ([@thekhegay](https://github.com/thekhegay)) - Xia Chao ([@xia-chao](https://github.com/xia-chao)) ## [v12.0.4](https://github.com/nestjs/nest/releases/tag/v12.0.4) ##### v12.0.4 (2026-09-21) ##### Bug fixes - `microservices` - [#17816](nestjs/nest#17816) fix(microservices): let the kafka client retry after a failed connect ([@Xch4rt](https://github.com/Xch4rt)) - [#17786](nestjs/nest#17786) fix(microservices): fail pending rmq requests on client close ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - [#17802](nestjs/nest#17802) fix(microservices): fail pending nats requests on client close ([@hktitof](https://github.com/hktitof)) - [#17803](nestjs/nest#17803) fix(microservices): handle missing grpc package namespace gracefully ([@Se3do](https://github.com/Se3do)) - [#17799](nestjs/nest#17799) fix(microservices): share the processing hook envelope across transports ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17797](nestjs/nest#17797) fix(microservices): close the kafka request-response span exactly once ([@MingLin1995](https://github.com/MingLin1995)) - [#17794](nestjs/nest#17794) fix(microservices): close the request-response span exactly once ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17785](nestjs/nest#17785) fix(microservices): route message handler rejections to handleError ([@hktitof](https://github.com/hktitof)) - `core` - [#17821](nestjs/nest#17821) fix(core): hang on sparse factory inject array ([@xia-chao](https://github.com/xia-chao)) ##### Enhancements - `platform-express` - [#17818](nestjs/nest#17818) Fix: merge multer `limits` key-by-key instead of overriding it wholesale ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy)) - `common` - [#17780](nestjs/nest#17780) fix(common): mark parse date pipe options as optional ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid)) ##### Dependencies - `common` - [#17793](nestjs/nest#17793) fix(deps): update dependency file-type to v22.1.1 ([@renovate\[bot\]](https://github.com/apps/renovate)) - `platform-fastify` - [#17791](nestjs/nest#17791) fix(deps): update dependency fastify to v5.12.5 ([@renovate\[bot\]](https://github.com/apps/renovate)) ##### Committers: 10 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Chowdhury Zaber Bin Zahid ([@Chy-Zaber-Bin-Zahid](https://github.com/Chy-Zaber-Bin-Zahid)) - Imad - Prakticode ([@prakticode](https://github.com/prakticode)) - Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - MD. Ridoy Babu ([@mdrezuanislamridoy](https://github.com/mdrezuanislamridoy)) - Ming ([@MingLin1995](https://github.com/MingLin1995)) - Mohammed Said ([@Se3do](https://github.com/Se3do)) - Pablo Gutiérrez ([@Xch4rt](https://github.com/Xch4rt)) - Xia Chao ([@xia-chao](https://github.com/xia-chao)) ## [v12.0.3](https://github.com/nestjs/nest/releases/tag/v12.0.3) ##### v12.0.3 (2026-09-15) ##### Bug fixes - `microservices` - [#17766](nestjs/nest#17766) fix(microservices): always run the kafka processing end hook ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17757](nestjs/nest#17757) fix(microservices): fail pending requests on client close ([@hktitof](https://github.com/hktitof)) - [#17746](nestjs/nest#17746) fix(microservices): bound memory held for a TCP peer ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17745](nestjs/nest#17745) fix(microservices): destroy open TCP sockets on shutdown ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - `common` - [#17738](nestjs/nest#17738) fix(common): validate uuid version and variant when no version is set ([@otnc](https://github.com/otnc)) - [#17761](nestjs/nest#17761) fix(common): invoke proto-key stripping hook via this in transform ([@koreahghg](https://github.com/koreahghg)) ##### Dependencies - `platform-express` - [#17762](nestjs/nest#17762) fix(deps): update dependency multer to v2.4.0 ([@renovate\[bot\]](https://github.com/apps/renovate)) - `common` - [#17753](nestjs/nest#17753) fix(deps): update dependency file-type to v22.1.0 ([@renovate\[bot\]](https://github.com/apps/renovate)) ##### Committers: 4 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - otoneko. ([@otnc](https://github.com/otnc)) - 한국 ([@koreahghg](https://github.com/koreahghg)) ## [v12.0.2](https://github.com/nestjs/nest/releases/tag/v12.0.2) ##### v12.0.2 (2026-09-14) ##### Bug fixes - `platform-socket.io`, `platform-ws` - [#17666](nestjs/nest#17666) fix(socket.io): keep the message stream alive when a handler throws ([@hktitof](https://github.com/hktitof)) - `microservices` - [#17728](nestjs/nest#17728) fix(microservices): detach signal listeners of connected microservices ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - [#17671](nestjs/nest#17671) fix(microservices): fail requests whose reply subscription is rejected ([@samuelmbabhazi](https://github.com/samuelmbabhazi)) - [#17670](nestjs/nest#17670) fix(microservices): do not treat foreign JSON as an RPC envelope ([@xia-chao](https://github.com/xia-chao)) - [#17644](nestjs/nest#17644) fix(microservices): don't flatten plain handler results with pre-request hooks ([@iamolegga](https://github.com/iamolegga)) - [#17641](nestjs/nest#17641) fix(microservices): run the mqtt listen callback once ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - `common` - [#17710](nestjs/nest#17710) fix(common): collapse duplicate internal slashes in `normalizePath` ([@Asadshah7950](https://github.com/Asadshah7950)) - [#17655](nestjs/nest#17655) fix(common): validate UUID v3 variant ([@gwagjiug](https://github.com/gwagjiug)) - [#17702](nestjs/nest#17702) fix(common): treat empty string as array input in ParseArrayPipe ([@xia-chao](https://github.com/xia-chao)) - `core` - [#17667](nestjs/nest#17667) fix(core): discover factory providers with discovery decorators ([@hktitof](https://github.com/hktitof)) - [#17709](nestjs/nest#17709) fix(core): avoid treating error instances with `statusCode` as http errors ([@Asadshah7950](https://github.com/Asadshah7950)) - [#17625](nestjs/nest#17625) fix(core): clean up repeated shutdown signal listeners ([@Raj4478](https://github.com/Raj4478)) - `platform-fastify` - [#17705](nestjs/nest#17705) fix(fastify): derive neutral version when accept header is absent ([@Gaurav1112](https://github.com/Gaurav1112)) - [#17699](nestjs/nest#17699) fix(fastify): send responses for exceptions thrown from middleware ([@micalevisk](https://github.com/micalevisk)) ##### Enhancements - `microservices` - [#17734](nestjs/nest#17734) feat(microservices): add maxConnectionAttempts to ServerMqtt ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) ##### Dependencies - `platform-fastify` - [#17729](nestjs/nest#17729) fix(deps): update dependency fastify to v5.12.4 ([@renovate\[bot\]](https://github.com/apps/renovate)) ##### Committers: 16 - Abdellatif Anaflous ([@hktitof](https://github.com/hktitof)) - Alexey Solovyov ([@lyohaplotinka](https://github.com/lyohaplotinka)) - Asad Ali Shah ([@Asadshah7950](https://github.com/Asadshah7950)) - Gyeonghun Park ([@Gyeonghun-Park](https://github.com/Gyeonghun-Park)) - Johnny J. Huirilef Millán ([@johnnyhuirilef](https://github.com/johnnyhuirilef)) - Kamil Mysliwiec ([@kamilmysliwiec](https://github.com/kamilmysliwiec)) - Kumar Gaurav ([@Gaurav1112](https://github.com/Gaurav1112)) - Micael Levi L. Cavalcante ([@micalevisk](https://github.com/micalevisk)) - Ming ([@MingLin1995](https://github.com/MingLin1995)) - Mohammed Said ([@Se3do](https://github.com/Se3do)) - Rajeshwar Singh ([@Raj4478](https://github.com/Raj4478)) - Xia Chao ([@xia-chao](https://github.com/xia-chao)) - [@iamolegga](https://github.com/iamolegga) - cui fliter ([@cuishuang](https://github.com/cuishuang)) - samuel mbabhazi ([@samuelmbabhazi](https://github.com/samuelmbabhazi)) - 곽지욱 ([@gwagjiug](https://github.com/gwagjiug))
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?
in IoAdapter.bindMessageHandlers the gateway callback runs inside a mergeMap projection, unguarded, so when a message handler throws synchronously the error escapes the projection, rxjs errors the whole stream and unsubscribes the socket listener, from that point the client gets no response for that event anymore and the missing error handler surfaces the throw as an uncaught exception at the process level
Issue Number: #17624, #17635
Steps to reproduce
What is the new behavior?
the transform(callback(...)) call is now wrapped in defer() with a catchError on the inner observable in both platform-socket.io and platform-ws, so a throw turns into an error notification, gets logged and returns EMPTY inside the mergeMap instead of tearing the stream down, later messages from the same socket keep working. the guard sits on the inner observable so it catches the sync throw AND the async rejection case (a @catch() filter that rethrows makes WsProxy.handleError reject inside the proxy), and defer turns a sync throw into an error notification so the try/catch shape went away. the rethrown filter error gets logged instead of silently dropped, following the lean in the review thread, the exact log-vs-swallow policy stays a maintainer call like in the #17624 thread
Does this PR introduce a breaking change?
Other information
tested with: