@bymax-one/nest-realtime 1.2.13 → 1.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +101 -1
- package/README.md +88 -18
- package/dist/internal/index.cjs +800 -102
- package/dist/internal/index.d.cts +436 -51
- package/dist/internal/index.d.ts +436 -51
- package/dist/internal/index.mjs +795 -103
- package/dist/react/index.cjs +28 -5
- package/dist/react/index.mjs +28 -5
- package/dist/server/index.d.cts +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +3 -0
- package/dist/shared/index.d.ts +3 -0
- package/dist/shared/index.mjs +1 -0
- package/dist/websocket/index.cjs +150 -54
- package/dist/websocket/index.d.cts +63 -12
- package/dist/websocket/index.d.ts +63 -12
- package/dist/websocket/index.mjs +152 -56
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,104 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.15] - 2026-11-14
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **Closing the application waited for ever on a Redis that had stopped answering.** The Redis pub/sub subscriber is closed with a `QUIT`, a command on a connection, and on a connection that accepts the socket and never replies (a paused or partitioned Redis) it never settles, so `app.close()` stayed pending until the process was killed. The close now waits two seconds for the reply and then disconnects the connection. The subscriber that `RealtimeIoAdapter` opens for the Socket.IO Redis adapter with `pubClient.duplicate()` was never closed at all; it now is, in `dispose()`, once every server has closed, and on one bound for all of them. Your `pubClient` is never closed or changed.
|
|
15
|
+
- **A failing command of the Socket.IO Redis adapter's subscriber could end the process.** The adapter sends its `subscribe` and `unsubscribe` without awaiting them, so a command that failed, as every pending one does when its connection is closed, was an unhandled rejection. Each is now handled, and logged once per connection by the error's class only, never its message.
|
|
16
|
+
|
|
17
|
+
#### Apply to a derived backend
|
|
18
|
+
|
|
19
|
+
`RealtimeIoAdapter` gains a public `dispose()`, which closes the subscriber connection it opened; a class that extends it and overrides `dispose()` must call `super.dispose()`, or that connection stays open. Nothing else changes. Against a healthy Redis a shutdown is as it was; against one that does not answer it now finishes instead of never finishing, waiting a bounded time for each Redis connection it closes. The documentation said the library never opens its own Redis connection; the Socket.IO Redis adapter's subscriber is one, and `RealtimeIoAdapter` is what closes it.
|
|
20
|
+
|
|
21
|
+
## [1.2.14] - 2026-11-14
|
|
22
|
+
|
|
23
|
+
### Security
|
|
24
|
+
|
|
25
|
+
- **A reconnect could wait for a hung offline queue for ever.** The read of the offline queue that a `Last-Event-ID` reconnect makes before its stream opens had no time limit, so a store that accepts the call and never answers left every such request open, each holding a socket, a request and a place against `maxConnections`. The read is now made with the authentication, before the response is committed, and bounded by `authenticateTimeoutMs` (default 10,000 ms): a queue that has not answered in time ends the handshake with a `503` and the generic body, registers nothing and gives the place back, and the late answer is ignored. A queue that fails is unchanged: the error is reported and the client gets its live events with an empty gap. The timeouts are logged once for each ten seconds with a count. The queue is read a second time when the stream is built, for what was appended while the application's interceptors ran (an event emitted to the reconnecting user then is in the queue and in no replay ring), and what the first read came to decides what follows: when the store failed on the first read the reconnect is served without a gap, as an outage has always been served, with no second read; when the first read succeeded, a timeout of the second, its refusal because the reads waiting are all taken, or an error from the store ends the attempt before anything is delivered, so the client's cursor does not move past events that are still stored. The call to the store cannot be cancelled, so it runs on until the store gives up, and it keeps its place among the `maxPendingHandshakes` (default 1,000) offline reads waiting at once until it settles: a reconnect that finds them all taken gets the `503` at once, without a call to the store. Set `commandTimeout` on the ioredis client behind `RedisOfflineQueue`.
|
|
26
|
+
|
|
27
|
+
#### Apply to a derived backend
|
|
28
|
+
|
|
29
|
+
A reconnect whose offline queue takes longer than `authenticateTimeoutMs` now gets a `503` where it used to wait; raise `authenticateTimeoutMs` if your queue is legitimately slower. `OfflineQueueDeliveryService` takes the options as an optional last constructor argument, and `retrieve` can now reject with the new `OfflineQueueTimeoutError`.
|
|
30
|
+
|
|
31
|
+
- **Nothing limited how many connections an instance accepted.** `maxConnectionsPerUser` bounds one user, but many users, or a token minted for each request, could open connections until the process ran out of file descriptors and stopped serving, on either transport. The new `maxConnections` (default `10000`, an integer of 1 or more) bounds the instance: it counts the connections of both transports together and the handshakes admitted and not yet registered, and a handshake past it is refused before `authenticate` is called, so a flood of them costs your backend no call. SSE answers `503` with the generic body (no `Retry-After`), WebSocket the generic `connect_error`; the refusals are logged once for each ten seconds with a count. A place held for a handshake is given back when its connection is registered or when its request or socket closes, whichever comes first, and in any case after `authenticateTimeoutMs` plus 5,000 ms, so a handshake that dies half way does not use up the limit. A reconnect whose offline-queue read outlives its place takes one again before it registers, and its stream ends if the instance has filled in the meantime. The limit trades a crash for refused new connections: it cannot evict, so an attacker who fills it keeps real clients out until sockets close, and limits for each address and the proxy stay the real controls.
|
|
32
|
+
|
|
33
|
+
#### Apply to a derived backend
|
|
34
|
+
|
|
35
|
+
**An instance that holds more than 10,000 connections at once now refuses the next ones.** Set `maxConnections` to what the instance really serves, below the process's file-descriptor limit less headroom (see the README for a worked example); there is no value that switches the bound off, so a larger instance sets a larger number. `BymaxRealtimeModuleOptions` gains `maxConnections`, an integer of 1 or more, checked at start-up. `SseTransport` and `WebSocketTransport` take an optional `ConnectionAdmission` as their last constructor argument and expose `admit()`; a transport built by hand without it admits every connection, as before. `SseResponse` gains an optional `once('close', listener)` and an optional `raw`, which the handler uses to give a place back when a response ends: on the response itself (Express), on the Node response behind a reply (Fastify's `reply.raw`), or on the socket. Whatever the framework reports, a place that nothing has given back within `authenticateTimeoutMs` plus 5,000 ms is given back at the next admission, so a request that dies unseen cannot fill the instance.
|
|
36
|
+
|
|
37
|
+
- **A `revalidate` that returned nothing kept the connection.** The result was defaulted to `true` when the call returned `undefined`, so an authenticator whose `revalidate` forgot to return (a missing `return`, a branch that falls through) approved every connection at every cycle, for ever, and so did one that resolved to `null`. Only an explicit `true` keeps a connection now; `false`, `undefined`, `null` and any other value disconnect it by the same path, with the same reason and hook. An authenticator with no `revalidate` at all is unchanged: there is nothing to check.
|
|
38
|
+
|
|
39
|
+
#### Apply to a derived backend
|
|
40
|
+
|
|
41
|
+
A `revalidate` that does not return `true` on every path now disconnects the connection at its next cycle where it used to keep it. Check that each branch of yours returns a boolean.
|
|
42
|
+
|
|
43
|
+
- **The replay buffer kept the events of every user it was told about, for ever.** `emitToUser` appended to a per-user ring for any user id, whether or not that user had ever connected, and nothing removed an entry: a service that emitted to every user in its database made every instance hold up to `replayBufferSize` events for every one of them, without bound (20,000 users that never connected, 10 events each, were still held after the module closed). The buffer now keeps only the users that have a connection on the instance, or had one lately: an entry is created when a connection opens, kept for `sse.replayTtlMs` (default 300,000 ms) after the user's last connection closes, and at most `sse.replayMaxIdleUsers` (default 1,000) idle entries are kept at once, the one that closed longest ago going first. The ring of a user with a connection open is never evicted, so the most the buffer holds is (connections open + `replayMaxIdleUsers`) x `replayBufferSize` x the size of an event. Expiry is checked when the buffer is used, so there is no timer. **Behaviour change:** replay is per instance. An instance used to buffer the events of users that were not connected to it, so a client that reconnected to a different instance could be replayed events emitted before it arrived, when the ids happened to line up; ring ids are per instance, so that could skip or repeat events. It no longer happens: without sticky routing, a reconnect to another instance gets the offline queue (when configured), not replay.
|
|
44
|
+
|
|
45
|
+
#### Apply to a derived backend
|
|
46
|
+
|
|
47
|
+
`SseOptions` gains `replayTtlMs` (an integer from 1 to 2,147,483,647) and `replayMaxIdleUsers` (an integer of 1 or more), both checked at start-up. `EventReplayBuffer` gains `open(userId)` and `close(userId)`, which `SseTransport` calls when a connection registers and when it is released, and `append` drops the event of a user with no entry: a derived transport that appended directly must call `open` first.
|
|
48
|
+
|
|
49
|
+
- **One re-authentication call that never settled kept every connection after it from being revalidated or revoked.** The cycle ran serially and `revalidate` had no time limit, so a call that hung (an auth backend that accepts the request and never answers) left every later connection un-checked, and a connection whose credentials had been refused stayed connected, on every cycle after. Each call is now bounded by `reauthenticationPolicy.revalidateTimeoutMs` (default 10,000 ms), and a call that does not settle in time is treated as one that threw: the connection is revoked. The cycle runs up to `concurrency` (default 8) connections at once, and a connection with a call in flight is not asked again, so overlapping cycles no longer call `revalidate` several times at once for one connection. An auth backend that is down or slower than the timeout therefore revokes every connection due in that cycle, and the clients are refused at the handshake until it recovers: set the timeout above the backend's p99.
|
|
50
|
+
|
|
51
|
+
#### Apply to a derived backend
|
|
52
|
+
|
|
53
|
+
`ReauthenticationPolicy` gains `revalidateTimeoutMs` and `concurrency`; `IConnectionAuthenticator.revalidate` takes an optional third argument `{ signal: AbortSignal }` (new exported type `AuthenticatorCallOptions`), aborted on timeout; `ConnectionRecord` gains an optional `revalidatedAt`, which holds the time of the last confirmation instead of a map in the service. The re-authentication options are now validated when the application starts: `intervalSeconds`, `revalidateTimeoutMs` and `concurrency` must be integers of 1 or more, `cacheTtlMs` an integer of 0 or more, and `onFailure` `'disconnect'` or `'event'`. An `intervalSeconds` of 0 or a fractional one used to start a timer firing every millisecond or so, and now stops the application at start-up.
|
|
54
|
+
|
|
55
|
+
- **The memory kept for re-authentication no longer outlives the connection.** The cache of successful checks was a map that was cleared only on revocation and at shutdown, so every connection that was revalidated and then closed left an entry behind (1,000 closed connections left 1,000). It now lives on the connection's record.
|
|
56
|
+
|
|
57
|
+
- **A re-authentication failure could leave a connection connected.** When a connection's credentials were refused, a `onReauthenticationFailed` hook that threw before it returned (a plain function, which the interface allows) aborted the failure handling before the connection was disconnected, so a failing notification hook could keep a connection whose credentials had been refused until the next cycle, and the same on every cycle after. The hook's failure is now logged and the connection is disconnected as before.
|
|
58
|
+
|
|
59
|
+
- **An authenticator that never answered held every handshake for ever, and nothing limited how many could be waiting.** `authenticate` was awaited with no time limit, on SSE and on WebSocket, so a backend that accepts the request and never answers left every request or handshake pending, each holding a socket and a request, with no cap: one slow dependency, or one attacker, could exhaust the instance. A call that has not settled in the new `authenticateTimeoutMs` (default 10,000 ms) is now given up on, and the client is refused: a `503` with the generic body on SSE, the generic `connect_error` on WebSocket, and nothing about the cause reaches the client. At most `maxPendingHandshakes` (default 1,000) calls are waiting at once across both transports, and a call keeps its place until it actually settles, so an authenticator that never answers fills the limit and further handshakes are refused at once without being asked, instead of being given a new call each. A slow backend can therefore hold the limit full for as long as it stays slow, which is intended. The refusals are logged once for each ten seconds with a count, and nothing of the request is in the line.
|
|
60
|
+
|
|
61
|
+
#### Apply to a derived backend
|
|
62
|
+
|
|
63
|
+
`BymaxRealtimeModuleOptions` gains `authenticateTimeoutMs` (an integer from 1 to 2,147,483,647) and `maxPendingHandshakes` (an integer of 1 or more), both checked at start-up. `IConnectionAuthenticator.authenticate` takes an optional second argument `{ signal: AbortSignal }`, aborted on timeout; the type that `revalidate` already used is now named `AuthenticatorCallOptions` and is shared by both (it was `RevalidateOptions`, in this unreleased version). `SseTransport` takes the new `AuthenticationGate` in place of the authenticator, and `WebSocketTransport.authenticator()` is replaced by `authenticate(context)`, which goes through the same gate. An SSE handshake can now be answered `503` where it used to wait or answer `500`.
|
|
64
|
+
|
|
65
|
+
- **A WebSocket user could hold any number of connections.** `websocket.maxConnectionsPerUser` was opt-in, so with nothing configured one user (or one token) could open sockets without limit, each holding a file descriptor and its memory, while SSE already stopped at 5. The default is now `5` on both transports: the sixth connection of a user closes the user's oldest, which is sent a disconnect and gives up its slot, so a user is left with five. The new connection is registered before the oldest is closed, so for the moment between the two a user can hold six. The cap is per user only; it does not bound the sockets of an instance.
|
|
66
|
+
|
|
67
|
+
#### Apply to a derived backend
|
|
68
|
+
|
|
69
|
+
A user who legitimately holds more than five simultaneous WebSocket connections (many tabs or devices) now has the oldest closed unless `websocket.maxConnectionsPerUser` is raised. An explicit `0` keeps its meaning and switches the cap off. No option is added, and the type of the option is unchanged.
|
|
70
|
+
|
|
71
|
+
### Fixed
|
|
72
|
+
|
|
73
|
+
- **Retiring the subscription of a subscriber that had ended, or was waiting to reconnect, kept the process alive for about two seconds.** ioredis arms a timer in `disconnect()`, 2,000 ms by default, and clears it only when the socket emits `close`; a client that has ended, or is waiting to try again, has no open socket whose close is still to come, so the timer runs its whole length. `RedisRealtimePubSub` disconnected its subscriber in that state when it retired the subscription (at shutdown or when the last handler left) and when the first `SUBSCRIBE` failed, so an application that closed while Redis was unreachable was delayed by that timer. The subscriber is now created with a `disconnectTimeout` of 1 ms, so a retired subscriber has nothing to wait for; the publisher client you pass in is yours and is unchanged.
|
|
74
|
+
|
|
75
|
+
#### Apply to a derived backend
|
|
76
|
+
|
|
77
|
+
Nothing to change. An application or a test that closes while Redis is unreachable no longer waits about two seconds for the process to exit.
|
|
78
|
+
|
|
79
|
+
- **A client that opened a new `EventSource` after a refusal was never replayed what it missed, and a store that returns its events instead of a promise could fill the offline reads.** `useRealtimeSse` replaces its `EventSource` after an error (once its backoff has passed) and on a manual `reconnect()`, and a new `EventSource` has no last event id, so it sent no `Last-Event-ID`: after a `503` from the offline queue or the instance limit the gap was never read. The hook now keeps the id of the last event it saw, for the url it was opened with, and adds it to the url of the next stream it opens as the `lastEventId` query parameter (before any fragment, encoded, replacing a `lastEventId` the url already carries; nothing is added until an event has been seen). The server reads the id from the `Last-Event-ID` header or, when there is none, from `lastEventId`, at the three places it uses it (the replay ring, the guard's read of the offline queue and the second read), and the header wins when both are present. An id longer than 256 characters, from either place, and a query value that is not a single string are read as no id; the ids this library generates are 20 characters. Separately, `OfflineQueueDeliveryService` counted a call to the store before it knew the call was a promise, so a store whose `retrieveSince` returns its events directly (a JavaScript consumer, say) left the place taken for ever, and enough of them refused every reconnect with `503` until a restart; the result is now wrapped before it is counted.
|
|
80
|
+
|
|
81
|
+
#### Apply to a derived backend
|
|
82
|
+
|
|
83
|
+
Nothing to change: an older server ignores the parameter, and an older client does not send it. A server in front of which a proxy or a CDN caches or logs URLs now sees `lastEventId=<id>` on a reconnect, so treat the id as logged. If you pass your own `EventSource` url, you can add `lastEventId` yourself. A custom `IOfflineQueueStorage` whose `retrieveSince` returns a promise is unchanged.
|
|
84
|
+
|
|
85
|
+
- **A call that found no path left answered `500`.** `emitToUser` with no delivery path, a `disconnect` the bus refused and a transport with no server attached rejected with a plain `Error`, so a controller that let it escape answered `500`, which reads as a defect in the application for what is an outage of its store. The rejection is now Nest's `ServiceUnavailableException`: `503` with the generic body `{"statusCode":503,"message":"Service Unavailable"}`. The message that names the failed call, `error.code` and the `cause`, which can hold a driver's text with a host and credentials, stay on the instance for your logs and are never in the response. A WebSocket handshake refused because the authenticator is unavailable (a timeout or `maxPendingHandshakes`) or because the instance is full (`maxConnections`) now carries `data.code` `REALTIME_TRANSPORT_UNAVAILABLE`, with the message still generic, so a client can tell a retryable refusal from a refused identity; a blank identity or any other failure of `authenticate` stays generic with no code.
|
|
86
|
+
|
|
87
|
+
#### Apply to a derived backend
|
|
88
|
+
|
|
89
|
+
If you matched the rejection of `emitToUser`, `disconnect`, `joinRoom` or `leaveRoom` with `error.constructor === Error`, or answered `500` for it in a filter, it is now a `ServiceUnavailableException` (`error.getStatus()` is `503`); `error.code`, `error.message` and `error.cause` are as before, so code that branched on `error.code` is unchanged. Nest's default filter logged the plain `Error` with its stack but does not log an `HttpException`, so log these from an exception filter if you relied on that line. A WebSocket client that treated every generic `connect_error` alike can read `error.data?.code === 'REALTIME_TRANSPORT_UNAVAILABLE'` to retry.
|
|
90
|
+
|
|
91
|
+
- **The replay buffer could count a repeated close against a user's open connections, and aged its idle entries by the wall clock.** A `close` for a user with no open connection took the count below zero, so a later pair of opens and one close made an entry with a connection still open look idle, to be expired and evicted while the user was connected. A close with nothing open is now ignored. The age of an idle entry was read from `Date.now()`, so a clock stepped forward (NTP, a manual change) expired every idle entry at once and one stepped back kept them for as long as the step; it is now read from `performance.now()`, which only moves forward.
|
|
92
|
+
|
|
93
|
+
- **A consumer's disconnect hook that never settles can no longer keep a client connected, or the application from closing.** On SSE the connection was cut only after `onDisconnect` returned, so a hook that never settled left the stream open, delayed every revocation through `disconnect()`, held back the admission of a user's next connection behind the eviction of the previous one, and, because shutdown closed the connections one after another and waited for each, made `app.close()` take as many hook latencies as there were connections, or never finish at all (the HTTP server does not close while a stream is open). The connection is now removed and its stream cut first, and `onDisconnect` runs after; every connection is closed at once on shutdown. On WebSocket `registerSocket` awaited `onConnect` before the connection was announced, so a hook that never settled left the client never told it was connected. The hooks the library awaits (`onDisconnect` on both transports, WebSocket `onConnect`) are given up on after the new `hookTimeoutMs` (default 5,000 ms): the failure is logged and the connection is left as it is, so closing the application takes about one `hookTimeoutMs` however many connections there are.
|
|
94
|
+
|
|
95
|
+
#### Apply to a derived backend
|
|
96
|
+
|
|
97
|
+
`BymaxRealtimeModuleOptions` gains an optional `hookTimeoutMs`, an integer from 1 to 2,147,483,647, checked at start-up (the same ceiling now applies to `reauthenticationPolicy.revalidateTimeoutMs`, `websocket.pingIntervalMs` and `websocket.pingTimeoutMs`, and `intervalSeconds` is at most 2,147,483: Node runs a longer timer as 1 ms). In the React hook the reconnect delay is capped at the same ceiling, and a `reconnectInitialMs` or `reconnectMaxMs` that is not a positive whole number (a `NaN` from a bad parse, an infinity, 0, a negative) is replaced by its default, so neither can become a reconnect every millisecond against the server. `onDisconnect` on SSE now runs after the connection's record has been removed and its stream closed (it already ran after the record was removed), and may be abandoned after the timeout, with the late result ignored. `SseTransport.disconnectLocal` and `beforeApplicationShutdown` no longer wait for a hook for longer than the timeout.
|
|
98
|
+
|
|
99
|
+
- **A consumer's lifecycle hook that fails can no longer take the process down or touch a connection.** On WebSocket, `onDisconnect` ran in a handler Nest does not wait for and was not guarded, so a hook that rejected or threw (a presence store that is down, for one) left an unhandled rejection, which ends the process on Node 15 and later, on the next disconnect of any client; and a failing `onConnect` disconnected the client it was announcing. Both are now logged and the connection is left as it is, as on SSE. A hook that throws before it returns (a plain function, which the interface allows) also escaped the SSE `onConnect` path and ended the stream with a 500. A hook is a notification; its failure is logged and nothing else changes.
|
|
100
|
+
- **An SSE client that does not read can no longer grow the server without bound.** The response writes one event at a time and waits for the client to read, and every event behind that wait was held in memory with no limit: 100 MB sent to one connection that never read raised the server's memory by 167 MB and the connection stayed registered. Each connection is now bounded by `sse.maxQueuedBytes` (default 2 MiB) and `sse.maxQueuedEvents` (default 1000), counted as the frames Nest writes, from what has been sent and its socket has not yet taken, and a connection from which no byte has left the process for `sse.stallHeartbeats` heartbeats (default 3) while the response holds bytes is closed too. It is closed with the new reason `REALTIME_SLOW_CONSUMER` and a warning, only that connection, and the client reconnects with `Last-Event-ID`. An event that is alone in the queue is always taken, however large. `0` switches a bound off. The same 100 MB now closes the connection after 22 events with no growth in the server's memory. A bound that was not there before can close a client that had stalled; set the three options to `0` to keep the old behaviour.
|
|
101
|
+
|
|
102
|
+
#### Apply to a derived backend
|
|
103
|
+
|
|
104
|
+
`SseOptions` gains `maxQueuedBytes`, `maxQueuedEvents` and `stallHeartbeats`, `RegisterSseConnectionParams` gains an optional `outbound`, `HeartbeatService.start` an optional fourth argument, `SseResponse` the optional `socket` and `writableLength`, and `REALTIME_ERROR_CODES` the `SLOW_CONSUMER` code. A derived transport that calls `registerConnection` without `outbound` keeps its connections unbounded.
|
|
105
|
+
|
|
106
|
+
- **The rooms joined at admission are the rooms that were validated.** `AuthenticationResult.rooms` is checked when the authenticator returns, and was joined later, after an await, from the same array. An authenticator that kept the array it returned and changed it in between could join names that were never checked, including a `user:` or `tenant:` room. The array is now copied once when it is validated, and only the copy, which is frozen, is joined and stored in `originalAuth`.
|
|
107
|
+
|
|
10
108
|
## [1.2.13] - 2026-11-13
|
|
11
109
|
|
|
12
110
|
No change to the published package: `dist/` is the same as in 1.2.12.
|
|
@@ -996,7 +1094,9 @@ First published release.
|
|
|
996
1094
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
997
1095
|
asked about NestJS and never put the same question to the other ten peers.
|
|
998
1096
|
|
|
999
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
1097
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...HEAD
|
|
1098
|
+
[1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
|
|
1099
|
+
[1.2.14]: https://github.com/bymaxone/nest-realtime/compare/v1.2.13...v1.2.14
|
|
1000
1100
|
[1.2.13]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...v1.2.13
|
|
1001
1101
|
[1.2.12]: https://github.com/bymaxone/nest-realtime/compare/v1.2.11...v1.2.12
|
|
1002
1102
|
[1.2.11]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...v1.2.11
|
package/README.md
CHANGED
|
@@ -331,7 +331,7 @@ bootstrap()
|
|
|
331
331
|
RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'.
|
|
332
332
|
```
|
|
333
333
|
|
|
334
|
-
With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber
|
|
334
|
+
With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber. That connection is the library's: it is closed when the application closes, and a QUIT that Redis does not answer within two seconds is dropped, so a Redis that stopped answering cannot hold the shutdown. Your `pubClient` is never closed or changed. If it cannot be installed (the package is missing, the client has no `duplicate()`), the boot fails with `REALTIME_REDIS_ADAPTER_FAILED` instead of serving a single instance; a Redis that is merely unreachable does not fail the boot. Socket.IO's polling fallback needs sticky sessions even then — see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
|
|
335
335
|
|
|
336
336
|
---
|
|
337
337
|
|
|
@@ -339,23 +339,70 @@ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls
|
|
|
339
339
|
|
|
340
340
|
All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
|
|
341
341
|
|
|
342
|
-
| Group | Key Options
|
|
343
|
-
| -------------------------- |
|
|
344
|
-
| **transport** | `'sse'` \| `'websocket'` \| `'both'`
|
|
345
|
-
| **authenticator** | `IConnectionAuthenticator`
|
|
346
|
-
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back
|
|
347
|
-
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget)
|
|
348
|
-
| **
|
|
349
|
-
| **
|
|
350
|
-
| **
|
|
351
|
-
| **
|
|
352
|
-
| **
|
|
353
|
-
| **
|
|
354
|
-
|
|
355
|
-
|
|
342
|
+
| Group | Key Options | Default |
|
|
343
|
+
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
|
344
|
+
| **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
|
|
345
|
+
| **authenticator** | `IConnectionAuthenticator` | — (**required**) |
|
|
346
|
+
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back | `auth.tenantId` |
|
|
347
|
+
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
|
|
348
|
+
| **hookTimeoutMs** | How long the library waits for a hook it awaits (`onDisconnect` on both transports, WebSocket `onConnect`) before giving up on it; integer from 1 to 2147483647 | `5000` |
|
|
349
|
+
| **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
|
|
350
|
+
| **maxPendingHandshakes** | How many calls to `authenticate` may be waiting at once, across both transports; over it a handshake is refused at once without calling it; integer >= 1 | `1000` |
|
|
351
|
+
| **maxConnections** | How many connections one instance holds, both transports together; a handshake past it is refused before `authenticate` is called (SSE `503`, WebSocket the generic error); integer >= 1, no way to switch it off | `10000` |
|
|
352
|
+
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
|
|
353
|
+
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
|
|
354
|
+
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
|
|
355
|
+
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
|
|
356
|
+
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
|
|
357
|
+
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
|
|
358
|
+
|
|
359
|
+
`sse.heartbeatMs` must be between 5,000 and 90,000 ms. Any other value, including `NaN` and a non-number, stops the application at start-up with `REALTIME_INVALID_OPTIONS`. `websocket.pingIntervalMs` and `websocket.pingTimeoutMs` must be integers from 1 to 2147483647 (Socket.IO runs both as timers, and Node runs a longer one as 1 ms). `sse.replayTtlMs` must be an integer from 1 to 2147483647 and `sse.replayMaxIdleUsers` an integer of 1 or more. `sse.maxQueuedBytes`, `sse.maxQueuedEvents` and `sse.stallHeartbeats` must be integers of 0 or more, and `0` switches that bound off.
|
|
360
|
+
|
|
361
|
+
#### Replay is per instance, and bounded
|
|
362
|
+
|
|
363
|
+
`Last-Event-ID` replay answers a client that reconnects **to the same instance**: the ring buffer is in that process's memory, and event ids are minted per instance, so replaying "after id N" from another instance's ring could skip or repeat events. Without sticky routing, a client that reconnects to a different instance gets the offline queue (when configured), not replay. The buffer keeps the events of users that have a connection on the instance or had one lately, and nothing for anyone else: a user that never connected there is not buffered, however many events are emitted to them. When a user's last connection closes the entry is kept for `sse.replayTtlMs` (default 300,000 ms), and no more than `sse.replayMaxIdleUsers` (default 1,000) such idle entries are kept at once, the one that closed longest ago going first. The ring of a user with a connection open is never evicted, and expiry is checked when the buffer is used, so there is no timer. The most it holds is (connections open + `replayMaxIdleUsers`) x `replayBufferSize` x the size of an event: with the defaults, 2,000 connected users and 1,000 idle ones, each ring full of 1 KB events, that is (2,000 + 1,000) x 100 x 1 KB, about 300 MB. Lower `replayBufferSize` or `replayMaxIdleUsers` to hold less.
|
|
364
|
+
|
|
365
|
+
#### Authentication is bounded
|
|
366
|
+
|
|
367
|
+
`authenticate` is called for every handshake, on both transports, and it is bounded two ways. A call that has not settled in `authenticateTimeoutMs` (default 10,000 ms) is given up on: the client is refused, with a `503` and the generic body on SSE and the generic `connect_error` on WebSocket, and the `AbortSignal` in the call's second argument is aborted so that a `fetch` or a query behind it can stop. At most `maxPendingHandshakes` (default 1,000) calls are waiting at once, across both transports, and a call keeps its place until it actually settles, not until the client was refused: an authenticator that never answers fills the limit, and every further handshake is then refused at once, without calling it, so a dependency that is down is not given a new call for every handshake. A consumer that honours the signal frees its place at once. The consequence is intended: a backend that stays slow keeps the limit full for as long as it stays slow, and new clients get a `503` until it answers or its calls end. Neither refusal is logged for each request: one line for each ten seconds says how many handshakes were refused and why, with nothing of the requests in it.
|
|
368
|
+
|
|
369
|
+
#### Hooks the library waits for
|
|
370
|
+
|
|
371
|
+
A hook is a notification: its failure is logged and nothing else changes. Three hooks are awaited by the library, and each is given up on after `hookTimeoutMs` (default 5,000 ms; an integer from 1 to 2147483647, checked at start-up): `onDisconnect` on both transports and `onConnect` on WebSocket, which is awaited before the connection is announced. A hook that has not settled by then is logged as `did not settle within N ms` and abandoned, whatever it returns later. The other hooks are not waited for and have no limit. On SSE the client is cut first and `onDisconnect` runs after, so a slow hook cannot keep a connection open; on shutdown every connection is closed at once, so a hook that never settles delays closing the application by about one `hookTimeoutMs`, not by one per connection. A hook that needs longer than the timeout must hand its work off and return.
|
|
372
|
+
|
|
373
|
+
#### The offline-queue read on a reconnect
|
|
374
|
+
|
|
375
|
+
A reconnect that carries `Last-Event-ID` reads the offline queue before its stream opens, so the read is part of the handshake, made with the authentication before the response is committed (so a refusal is a status even when the application registers an interceptor), and is bounded like it: a queue that has not answered in `authenticateTimeoutMs` (default 10,000 ms) is given up on, the client gets a `503` with the generic body, nothing is registered, and its place is given back. The events stay in the queue, since a read never prunes it. A queue that **fails** is not treated the same way: the error is reported and the client gets its live events with an empty gap. The timeouts are logged once for each ten seconds with a count.
|
|
376
|
+
|
|
377
|
+
The call to your store cannot be cancelled: `IOfflineQueueStorage.retrieveSince` takes no signal, so the call runs on and its late answer is ignored. It keeps its place until it settles, not until it was given up on: at most `maxPendingHandshakes` (default 1,000) offline reads are waiting at once, and a reconnect that finds them all taken gets the same `503` at once, without a call to your store. A store that hangs therefore fills that limit, instead of collecting one more open call for every reconnect, and the `503` lasts for as long as it stays hung or until its calls end. With `RedisOfflineQueue`, set `commandTimeout` on the ioredis client (for example `new Redis({ commandTimeout: 5000 })`) so that a hung Redis rejects those calls instead of holding them for ever.
|
|
378
|
+
|
|
379
|
+
The queue is read twice for one reconnect: with the authentication, before the response is committed, and again when the stream is built, for what was appended in between (an application interceptor that emits to the user, say: the user has no connection and no replay ring on this instance, so the event is in the queue and nowhere else). The second read starts after the last event the first returned, or after `Last-Event-ID` when it returned none, and the two share the one limit on the events of a reconnect, the same deadline for each read and the one count of reads waiting. What the first read came to decides whether there is a second, and two rules follow. **If your store failed on the first read**, the error is reported, the reconnect is served without a gap as an outage of the store has always been served, and there is no second read, so an outage does not turn every reconnect into a refusal. **If the first read succeeded**, any failure of the second, a timeout, a refusal by the count of reads waiting, or an error from your store, ends the attempt **before anything is delivered**: a stream built without those events would move the client's cursor past them with the next event it receives, and an attempt that delivers nothing leaves the cursor where it was, so the events are only delayed. A first read that timed out, or was refused by the count, ends the attempt with the `503` as before. The test `sse-subscription.handler.queue-reads.spec.ts` runs every combination of the two reads. Your store's `retrieveSince` has to return the events after an id in the same order as the ids, as `RedisOfflineQueue` does, or the second read is wrong too.
|
|
380
|
+
|
|
381
|
+
What the client then does depends on how the attempt ended, and no `Retry-After` is sent, so its own reconnect policy is the only pace:
|
|
382
|
+
|
|
383
|
+
| The server answers | When | A plain browser `EventSource` | The `useRealtimeSse` hook |
|
|
384
|
+
| ----------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
385
|
+
| `503` with the generic body | the response is not committed yet | The connection fails and the browser does **not** reconnect by itself. The application has to open a new `EventSource`, which cannot send `Last-Event-ID`, so what was missed is not replayed unless it adds the id to the url as `lastEventId`. | Reconnects after its backoff with a **new** `EventSource` that carries the last id it saw as the `lastEventId` query parameter: the events are replayed from there. |
|
|
386
|
+
| `200`, then the stream ends with an error frame | an application interceptor committed the response first | Reconnects by itself and sends the last id it saw, so the events are read again. | The browser reconnects with the id. If the hook's own backoff opens a new source first, that one carries the id as `lastEventId`, so either way the events are read again. |
|
|
387
|
+
|
|
388
|
+
An application that cannot lose events has to keep its own cursor and open the stream with it. The id is read from the `Last-Event-ID` header or, when the request has none, from the `lastEventId` query parameter, which is what `useRealtimeSse` sends (replacing a `lastEventId` the url you gave it already carries, once it has seen an event; the other parameters are then written again, so a key with no value gains an equals sign (`?flag` becomes `?flag=`), an encoded space is written as `+`, an empty parameter is dropped, and an encoded `+` stays one) and what an application adds to the url of a new `EventSource`; the header wins when both are present. An id longer than 256 characters, from either place, and a query value that is not a single string (a repeated parameter, say) are read as no id. The query parameter travels in the url, so it is written to access logs and caches with the rest of it; the ids this library generates are 20 characters (`{epoch ms}-{counter}`) and are not credentials.
|
|
389
|
+
|
|
390
|
+
#### How many connections one instance holds
|
|
391
|
+
|
|
392
|
+
`maxConnectionsPerUser` bounds one user; it does not bound an instance. `maxConnections` (default `10000`, an integer of 1 or more, with no value that switches it off) bounds the whole instance, counting the connections of both transports together and the handshakes admitted and not yet registered. A handshake that arrives when the instance already holds that many is refused before `authenticate` is called, so a flood of them costs the instance no call to your backend: a `503` with the generic body on SSE (no `Retry-After` is sent), the generic `connect_error` on WebSocket. The refusals are logged once for each ten seconds with a count, and nothing of the request is in the line. A place held for a handshake is given back when its connection is registered, or when its request or socket closes, whichever comes first, and in any case after `authenticateTimeoutMs` plus 5,000 ms, at the next handshake that asks for room, so a client that leaves half way, even on a framework that reports no close, does not use up the limit. A reconnect whose offline-queue read outlives its place takes one again before it registers, and its stream ends if the instance has filled in the meantime.
|
|
393
|
+
|
|
394
|
+
The place is given back on the response's `close` as Express reports it, and on the Node response behind a Fastify reply (`reply.raw`) or on the socket when that is where a framework reports it. This is tested on Express, over real HTTP; the Fastify reply shape is handled and unit-tested, but there is no Nest-on-Fastify test in this repository.
|
|
395
|
+
|
|
396
|
+
Set it **below the process's file-descriptor limit, less headroom**. Each connection holds a descriptor, and so do the listening socket, the files the process has open, and every connection to Redis, a database or another service. A limit of 10,000 on a process allowed 1,024 descriptors (the common default of `ulimit -n`) would run out of descriptors long before it refused anyone. Worked example: with `ulimit -n 65536` and about 500 descriptors for everything that is not a client connection, set `maxConnections` to 60,000 or less; with `ulimit -n 1024`, either raise the limit or set `maxConnections` to 800 or less. Check what the process really has with `cat /proc/<pid>/limits` or `ulimit -n` inside the container, since a container or a service manager often sets a different number from your shell.
|
|
397
|
+
|
|
398
|
+
The limit has a cost, and it is not a defence by itself. It trades a process that runs out of descriptors and stops serving, for one that refuses new connections while it is full: the clients it already has are served. Because it cannot evict, anyone who fills it, with many users or with a token minted for each request, keeps real clients out until their sockets close. Limits for each address, the rate of new connections and the number of connections at the proxy or the edge stay the controls that stop that, and this option is the last bound behind them.
|
|
399
|
+
|
|
400
|
+
#### A client that does not read
|
|
401
|
+
|
|
402
|
+
An SSE response writes one event at a time and waits for the client to read before the next, so everything behind that wait is held in server memory. Each connection is bounded: when the events and bytes sent to it and not yet taken by its socket pass `sse.maxQueuedEvents` or `sse.maxQueuedBytes` (an event that is alone in the queue is always taken, however large), or no byte has left the process for `sse.stallHeartbeats` heartbeats in a row while the response holds bytes, the connection is closed with the reason `REALTIME_SLOW_CONSUMER` and a warning is logged. Only that connection is closed; the client reconnects and `Last-Event-ID` replays what it missed. A connection whose response has no socket to measure is not bounded.
|
|
356
403
|
|
|
357
404
|
> [!NOTE]
|
|
358
|
-
> `
|
|
405
|
+
> `maxConnectionsPerUser` defaults to `5` on both transports: a user's sixth connection closes their oldest, which is sent a disconnect. `0` switches the cap off. The cap is per user and does not bound the connections of an instance: many users, or a token minted per request, are bounded by your proxy or the process's file-descriptor limit, not by this option.
|
|
359
406
|
|
|
360
407
|
The options are typed per entry point: `SseRealtimeModuleOptions` and `SseRealtimeModuleAsyncOptions` fix `transport: 'sse'`, and `WebSocketRealtimeModuleOptions` and `WebSocketRealtimeModuleAsyncOptions` (from `/websocket`) fix `'websocket' | 'both'`. `forRootAsync` takes `useFactory`, `useClass` (a `BymaxRealtimeModuleOptionsFactory`) or `useExisting`.
|
|
361
408
|
|
|
@@ -456,6 +503,8 @@ A complete `@bymax-one/nest-auth` bridge is in [docs/examples/nest-auth-bridge.m
|
|
|
456
503
|
|
|
457
504
|
Long-lived connections outlive short-lived tokens. `reauthenticationPolicy` revalidates on an interval and either drops the connection or emits `connection:reauthentication-failed` and then drops it, depending on `onFailure`. The connection is dropped even when that event cannot be sent: the event is a notification, and the failure to send it is logged. Successful checks are cached for `cacheTtlMs` so a busy connection is not revalidated on every event.
|
|
458
505
|
|
|
506
|
+
`revalidate` is bounded. At most `concurrency` calls run at once, across every cycle (a revocation that does not settle in `revalidateTimeoutMs` is given up on the same way, and tried again on the next cycle), and a connection with a call in flight is not asked again until it settles, so one slow connection cannot hold up the revocation of the others. A call that has not settled in `revalidateTimeoutMs` is treated exactly as one that threw: the connection is **revoked** (the `AbortSignal` in the call's third argument is aborted so the work behind it can stop, and whatever the call returns later is ignored). The consequence is that an auth backend that is down, or slower than the timeout, revokes every connection due for revalidation in that cycle, and those clients reconnect and are refused at the handshake until the backend recovers. Set `revalidateTimeoutMs` above your backend's p99. `intervalSeconds`, `revalidateTimeoutMs` and `concurrency` must be integers of 1 or more and `cacheTtlMs` an integer of 0 or more, and the two that feed a timer have a ceiling, because Node runs any timer longer than 2,147,483,647 ms as 1 ms (`revalidateTimeoutMs` at most 2147483647, `intervalSeconds` at most 2147483); anything else stops the application at start-up with `REALTIME_INVALID_OPTIONS`.
|
|
507
|
+
|
|
459
508
|
### Security Checklist
|
|
460
509
|
|
|
461
510
|
When integrating `@bymax-one/nest-realtime` in production, verify each of the following:
|
|
@@ -464,7 +513,7 @@ When integrating `@bymax-one/nest-realtime` in production, verify each of the fo
|
|
|
464
513
|
- `tenantId` is derived from the authenticated result, never from a query parameter or request body
|
|
465
514
|
- Tickets are single-use and short-lived; `consume()` must be atomic under concurrency
|
|
466
515
|
- `websocket.cors.origin` is an explicit allowlist, not `true`, in any browser-facing deployment
|
|
467
|
-
- `maxConnectionsPerUser` is set for WebSocket if clients are untrusted — it
|
|
516
|
+
- `maxConnectionsPerUser` is left at its default of `5` (or set) for WebSocket if clients are untrusted — `0` makes it unlimited
|
|
468
517
|
- Reserved event names are not reused for application events (see the [catalog](#reserved-events))
|
|
469
518
|
|
|
470
519
|
---
|
|
@@ -546,7 +595,7 @@ The unified emit API. Identical on every transport.
|
|
|
546
595
|
|
|
547
596
|
All methods return `Promise<void>`.
|
|
548
597
|
|
|
549
|
-
**Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is
|
|
598
|
+
**Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is Nest's `ServiceUnavailableException` (HTTP `503`) with `code` set, so a controller that lets it escape answers `503` with the generic body (see "What a client is told"). A rejection means the connection may still be connected, so retry.
|
|
550
599
|
|
|
551
600
|
**Emits are at-most-once.** `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` **resolve even when the publish to the other instances failed**; that failure is logged with `REALTIME_PUBSUB_UNAVAILABLE` and passed to the `onDeliveryFailure` hook, which is where to count it. An offline queue that could not keep an event for a user who is offline here is reported the same way, since another instance may have delivered it live; a failure on one transport of `'both'` is only logged. An emit rejects only when the event has no delivery path left: for `emitToUser`, the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus); with `'both'`, a failure on both transports rejects with `REALTIME_TRANSPORT_UNAVAILABLE`. A rejected emit is not proof that no client received it, so retry only where a duplicate is acceptable.
|
|
552
601
|
|
|
@@ -789,6 +838,7 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
789
838
|
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
|
|
790
839
|
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
|
|
791
840
|
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
|
|
841
|
+
| `REALTIME_SLOW_CONSUMER` | Raised as the reason an SSE connection is closed because its client is not reading |
|
|
792
842
|
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
|
|
793
843
|
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
|
|
794
844
|
| `REALTIME_PUBSUB_UNAVAILABLE` | Raised as the rejection of a disconnect when the bus refuses the revocation; an emit's publish failure is logged and passed to the delivery-failure hook |
|
|
@@ -797,6 +847,26 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
797
847
|
| `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
|
|
798
848
|
| `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
|
|
799
849
|
|
|
850
|
+
### What a client is told
|
|
851
|
+
|
|
852
|
+
The code travels on the error you catch; what reaches a client is decided by the status below, and it carries none of the text an operator reads.
|
|
853
|
+
|
|
854
|
+
| Failure | SSE (HTTP) | WebSocket (`connect_error`) | A call you make (`emitToUser`, `disconnect`, ...) |
|
|
855
|
+
| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------- | -------------------------------------------------------------------------------- |
|
|
856
|
+
| `authenticate` returns nothing | `401`, `REALTIME_AUTH_FAILED` | message `REALTIME_AUTH_FAILED`, `data.code` the same | |
|
|
857
|
+
| `authenticate` is unavailable: it timed out, or `maxPendingHandshakes` calls are already waiting | `503`, generic body | generic message, `data.code` `REALTIME_TRANSPORT_UNAVAILABLE` | |
|
|
858
|
+
| The instance is full (`maxConnections`) | `503`, generic body | generic message, `data.code` `REALTIME_TRANSPORT_UNAVAILABLE` | |
|
|
859
|
+
| The offline queue did not answer, or its reads are all taken | `503`, generic body | not read on this transport | |
|
|
860
|
+
| Shutdown has begun | `503`, message `REALTIME_TRANSPORT_UNAVAILABLE` | message and `data.code` `REALTIME_TRANSPORT_UNAVAILABLE` | |
|
|
861
|
+
| `authenticate` throws anything else, or returns a blank identity or rooms that break the rules | `500`, generic body (an `HttpException` you throw passes as it is) | generic message, no `data.code` | |
|
|
862
|
+
| The call has no path left: an emit with no delivery path, a revocation the bus refuses, a server not attached | n/a | n/a | rejects with `ServiceUnavailableException` (`503`), `error.code` the stable code |
|
|
863
|
+
|
|
864
|
+
The rejection of a call is Nest's own `ServiceUnavailableException`, so a controller that lets it escape answers `503` with the body `{"statusCode":503,"message":"Service Unavailable"}`. The library's message, which names the failed call, and the `cause`, which can hold a driver's text with a host and credentials, are on the instance for your logs and never in the response. Branch on `error.code`, not on the message.
|
|
865
|
+
|
|
866
|
+
Nest's default exception filter does not log an `HttpException`, so a `503` from one of these calls leaves no line in your log, where a plain `Error` was logged with its stack. To keep a record, catch `ServiceUnavailableException` in an exception filter of your own and log `exception.code`, `exception.message` and `exception.cause`, as you would for any other `HttpException` you want to see.
|
|
867
|
+
|
|
868
|
+
**An authenticator that wants a `503` throws `ServiceUnavailableException`.** On SSE an `HttpException` thrown from `authenticate` is sent as it is, so `throw new ServiceUnavailableException()` answers `503`; any other error answers a generic `500`. On WebSocket the handshake carries no HTTP status: an authenticator's own exception is answered with the generic message and no `data.code`. Only the library's own unavailable refusals carry `REALTIME_TRANSPORT_UNAVAILABLE`, which a client can treat as retryable.
|
|
869
|
+
|
|
800
870
|
### Shutdown
|
|
801
871
|
|
|
802
872
|
From the `onModuleDestroy` phase on, which runs ahead of every `beforeApplicationShutdown`, a new SSE stream gets a 503 whose message is `REALTIME_TRANSPORT_UNAVAILABLE` and a new WebSocket handshake gets a `connect_error` whose `data.code` is that code. A slow `onModuleDestroy` in a module nearer the root than the realtime module still runs first, and until it returns a connection is accepted.
|