@bymax-one/nest-realtime 1.2.15 → 1.2.17
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 +50 -3
- package/README.md +76 -24
- package/dist/internal/index.cjs +222 -105
- package/dist/internal/index.d.cts +72 -14
- package/dist/internal/index.d.ts +72 -14
- package/dist/internal/index.mjs +221 -106
- package/dist/react/index.cjs +163 -101
- package/dist/react/index.mjs +164 -102
- package/dist/websocket/index.cjs +18 -3
- package/dist/websocket/index.d.cts +4 -0
- package/dist/websocket/index.d.ts +4 -0
- package/dist/websocket/index.mjs +19 -4
- package/package.json +6 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,11 +2,56 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
-
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
|
|
6
|
-
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
|
+
Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while this API is pre-stable: breaking changes ship in minor and patch releases by explicit `@bymax-one` policy, so a version number carries no compatibility information. The **Apply to a derived backend** note, on the entries that carry one, is the compatibility contract: read it, not the number.
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.17] - 2026-11-17
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **`onConnectFailure: 'ignore' | 'close'`, a module option for what a failing `onConnect` does to its connection.** A hook that throws or rejects was only logged on both transports, so a host whose `onConnect` did work the connection depends on (a presence record, a scoped join) kept serving a connection that work had not reached. With `'close'` the failure is logged and the connection is closed. On both transports the hook has run, so `onConnect` is seen before the `onDisconnect` that follows it, and an event published while the hook runs may already have reached the client: on WebSocket the connection is closed before `connection:established` is sent, on SSE the stream is ended once the hook settles. Scope a connection in `AuthenticationResult.rooms` when no event may be missed. On WebSocket a hook that does not settle within `hookTimeoutMs` counts as a failure; on SSE the hook has no limit. The default is `'ignore'`, the behaviour of every earlier release, and any other value is refused at start-up with `REALTIME_INVALID_OPTIONS`.
|
|
15
|
+
|
|
16
|
+
#### Apply to a derived backend
|
|
17
|
+
|
|
18
|
+
Nothing changes unless you set the option. If you do, make sure your `onConnect` fails only when the connection should not stand: a hook that throws for a transient reason (a metrics client down) will then close the connection.
|
|
19
|
+
|
|
20
|
+
### Security
|
|
21
|
+
|
|
22
|
+
- **The text of a driver or a broker travelled on the 503 errors the library raises when they were stringified.** `unavailableError` set the failure underneath, a driver's message naming a host and a port, on the instance's own enumerable `message` and `cause`. A controller's 503 body was generic, but a filter, a logger or a socket acknowledgement that ran `JSON.stringify` on the instance sent them on. Both are now non-enumerable: `error.message` and `error.cause` still hold the text for whoever logs it, and the stringified instance carries the generic response and the stable `code`.
|
|
23
|
+
|
|
24
|
+
- **`joinRoom` could put a connection in another user's or tenant's room.** `AuthenticationResult.rooms` refused names that start with `user:`, `tenant:` or `connection:`, but `RealtimeService.joinRoom` and `leaveRoom` took any name. On WebSocket `emitToUser` and `emitToTenant` are delivered to the room named after the identity, so a host that forwarded a client-supplied room id to `joinRoom` let that client receive `user:<victim>` or `tenant:<other>` events by naming the room. Both calls now refuse those three prefixes with `REALTIME_AUTH_FAILED`, by the same rule admission uses; the message names the call, the field and the prefix, never the room id. `emitToRoom` does not refuse the prefixes: a name it is given only reaches that user's or tenant's own connections.
|
|
25
|
+
|
|
26
|
+
- **A room name that was not a string skipped that check.** socket.io's `join` and `leave` accept an array of names, so on WebSocket `joinRoom(id, ['user:<victim>'])`, `['tenant:<other>']`, `['connection:<id>']`, `['ok', 'user:<victim>']` and a nested array all resolved, and the connection then received what `emitToUser`, `emitToTenant` and the per-connection room delivered; `leaveRoom` took the same values. On SSE `emitToUser` and `emitToTenant` read the connection registry rather than a room, so the same names did not reach those events there; a room named that way was still joined, and `emitToRoom` with that name reached it. `joinRoom`, `leaveRoom` and `emitToRoom` now refuse a `roomId` that is not a non-empty string, before any room API sees it, with `REALTIME_AUTH_FAILED` and a message that names the call and the kind of value, never the value. The check is on `RealtimeService`, `WebSocketTransport`, `CompositeTransport` and the SSE transport, so injecting a transport directly is covered too. Measured: with real Socket.IO clients, an array, a nested array, a mixed array and a `Set` naming another identity's room are refused and the attacker's connection receives none of the events published for that identity; an object with a `toString`, a number, `null`, `undefined`, a `String` object and the empty string are refused in a unit table on the service and the SSE transport.
|
|
27
|
+
|
|
28
|
+
- **A per-user connection cap, the replay ring's size and the WebSocket payload bound could be switched off by a value that is not an integer.** The checks on `sse.maxConnectionsPerUser` and `sse.replayBufferSize` were comparisons (`< 0`), and `websocket.maxConnectionsPerUser` and `websocket.maxHttpBufferSize` had none, so `NaN`, which fails every comparison, passed and made the bounds they feed never trip. Measured: five connections of one user were all kept under `NaN` and `Infinity` on both transports; a replay ring given 1,000 events held all 1,000; and a Socket.IO server given `NaN`, `Infinity`, `-1` or `0` delivered a 2,000,000-byte payload that the default 1,000,000 bound refuses. A fraction and a numeric string were accepted too and then coerced by the comparison they fed. The four options are now validated at start-up as safe integers, `>= 0` for the counts and `>= 1` for the payload bound, each with a most, with `REALTIME_INVALID_OPTIONS`: 100,000 for either per-user cap and for `sse.replayBufferSize`, and 104,857,600 bytes (100 MiB) for `websocket.maxHttpBufferSize`. `Number.isInteger(1e300)` is true and the comparisons these options feed never trip at that size, so `1e300`, `Number.MAX_VALUE` and `2 ** 53` were a bound in name only; the integer options that had no most now refuse anything past 9,007,199,254,740,991.
|
|
29
|
+
|
|
30
|
+
#### Apply to a derived backend
|
|
31
|
+
|
|
32
|
+
Read the failure from `error.message` and `error.cause`, as before; do not rely on them appearing in `JSON.stringify(error)` or in `Object.keys(error)`.
|
|
33
|
+
|
|
34
|
+
A host that puts connections in a `user:`, `tenant:` or `connection:` room by hand now gets a rejected promise from `joinRoom` or `leaveRoom`; no call puts a connection in those rooms, because the library joins them itself from the identity it resolved. To send to one identity or tenant use `emitToUser` or `emitToTenant`; on WebSocket, to send to one connection use `emitToRoom('connection:<id>', ...)`, which is not refused. A `roomId` that is not a non-empty string, an array included, is refused the same way. Application rooms are unaffected.
|
|
35
|
+
|
|
36
|
+
At start-up a value that is not an integer is refused where it used to be accepted: `NaN`, `Infinity`, fractions and numeric strings for `sse.maxConnectionsPerUser`, `sse.replayBufferSize`, `websocket.maxConnectionsPerUser` and `websocket.maxHttpBufferSize`, plus `-1` for `websocket.maxConnectionsPerUser` (it switched the cap off, as `0` does) and `0` or a negative for `websocket.maxHttpBufferSize` (each switched the payload bound off). `0` is still how to switch off the two per-user caps, and `0` still means no replay for `sse.replayBufferSize`. If you want an unbounded value, say it with `0` where that is allowed, not with `Infinity`. A value above 100,000 for either per-user cap or `sse.replayBufferSize`, or above 104,857,600 for `websocket.maxHttpBufferSize`, is refused too.
|
|
37
|
+
|
|
38
|
+
`WebSocketTransport` gains two private members, `joinRooms` and `runOnConnect`, which `registerSocket` calls. A TypeScript subclass that declares a member with either name no longer compiles (TS2415, a private member of the base), and a JavaScript subclass that defines either replaces the joins of the user, tenant and connection rooms, or the call to `onConnect`, without any error. Do not declare members named `joinRooms` or `runOnConnect` in a subclass.
|
|
39
|
+
|
|
40
|
+
`RealtimeService.emitToRoom` is now an `async` method: it already returned `Promise<void>`, and a synchronous throw, including the refusal of a `roomId` that is not a non-empty string, now comes back as a rejected promise. `./internal` exports `requireRoomName` and `refuseReservedRoom`; `./internal` is not public API and carries no compatibility promise, so do not import them.
|
|
41
|
+
|
|
42
|
+
On SSE the `reason` that `onDisconnect` receives is set when the library closed the connection with one (`disconnect(connectionId, reason)`, the connection bounds) and is `undefined` otherwise: a connection that ended on its own, one that `onConnectFailure: 'close'` refused, or one closed at shutdown.
|
|
43
|
+
|
|
44
|
+
## [1.2.16] - 2026-11-14
|
|
45
|
+
|
|
46
|
+
### Fixed
|
|
47
|
+
|
|
48
|
+
- **A publish to a Redis that had stopped answering never settled.** `RedisRealtimePubSub.publish` awaited the `PUBLISH` with no limit once its client reported `ready`, and a paused or partitioned Redis accepts the socket and never replies, so every `emitToRoom`, `emitToTenant` and `broadcast` that waited on the bus, and every `disconnect()` of a connection held on another instance, stayed pending. A publish now gives up after two seconds and rejects with `REALTIME_PUBSUB_UNAVAILABLE`, the error it already raised when the client was not ready, so no caller changes: an emit reports the failure through `onDeliveryFailure`, and `disconnect()` rejects. The rejection means the server did not confirm the publish in time, not that it was not delivered: the command had already been written to the socket, so Redis can still process it when it answers, and an emit can arrive after it was reported failed.
|
|
49
|
+
- **A pub/sub payload that was not an object was dropped without a trace, and the messages the subscriber could not act on flooded the log.** A payload that parsed to `null` threw inside the subscriber into a catch that discarded it, with no count and no line; a message with no known op, or a known op with no `args`, wrote one warning for each message, with no limit, and carried the op or the error's message, which whoever can publish to the channel controls. A payload that is not an object is now counted by the report of malformed payloads, and everything else the subscriber cannot act on is reported once for each ten seconds, with a count and a reason that is either `unknown op` or the class of the last failure, never the op, the payload or an error's message.
|
|
50
|
+
|
|
51
|
+
#### Apply to a derived backend
|
|
52
|
+
|
|
53
|
+
Set `commandTimeout` on the ioredis client you give `RedisRealtimePubSub` (for example `new Redis({ commandTimeout: 5000 })`) if you want the command itself rejected: the library's limit stops the caller waiting, but the command stays queued in the client until the server answers or the connection drops. If you alert on the log lines `Unknown pub/sub op: …` or `Pub/sub message handling failed: …`, they no longer exist: alert on `Pub/sub dropped N message(s) it could not act on since the last report` instead. Nothing else changes.
|
|
54
|
+
|
|
10
55
|
## [1.2.15] - 2026-11-14
|
|
11
56
|
|
|
12
57
|
### Fixed
|
|
@@ -1094,7 +1139,9 @@ First published release.
|
|
|
1094
1139
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
1095
1140
|
asked about NestJS and never put the same question to the other ten peers.
|
|
1096
1141
|
|
|
1097
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
1142
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...HEAD
|
|
1143
|
+
[1.2.17]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...v1.2.17
|
|
1144
|
+
[1.2.16]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...v1.2.16
|
|
1098
1145
|
[1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
|
|
1099
1146
|
[1.2.14]: https://github.com/bymaxone/nest-realtime/compare/v1.2.13...v1.2.14
|
|
1100
1147
|
[1.2.13]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...v1.2.13
|
package/README.md
CHANGED
|
@@ -339,22 +339,23 @@ 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
|
-
| **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
|
|
349
|
-
| **
|
|
350
|
-
| **
|
|
351
|
-
| **
|
|
352
|
-
| **
|
|
353
|
-
| **
|
|
354
|
-
| **
|
|
355
|
-
| **
|
|
356
|
-
| **
|
|
357
|
-
| **
|
|
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
|
+
| **onConnectFailure** | What a failing `onConnect` does to its connection: `'ignore'` logs it and keeps the connection, `'close'` logs it and closes the connection on both transports, after the hook has run; anything else is refused at start-up | `'ignore'` |
|
|
350
|
+
| **authenticateTimeoutMs** | How long a handshake waits for `authenticate` before it is refused (SSE `503`, WebSocket the generic error); integer from 1 to 2147483647 | `10000` |
|
|
351
|
+
| **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` |
|
|
352
|
+
| **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` |
|
|
353
|
+
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
|
|
354
|
+
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
|
|
355
|
+
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
|
|
356
|
+
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `replayTtlMs`, `replayMaxIdleUsers`, `maxConnectionsPerUser`, `emitConnectionEvent`, `maxQueuedBytes`, `maxQueuedEvents`, `stallHeartbeats` | `/realtime/sse`, `30000`, `100`, `300000`, `1000`, `5`, `true`, `2097152`, `1000`, `3` |
|
|
357
|
+
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults), `5` for `maxConnectionsPerUser` |
|
|
358
|
+
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`, `revalidateTimeoutMs`, `concurrency` | `300`, `'disconnect'`, `60000`, `10000`, `8` |
|
|
358
359
|
|
|
359
360
|
`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
|
|
|
@@ -368,7 +369,7 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
|
|
|
368
369
|
|
|
369
370
|
#### Hooks the library waits for
|
|
370
371
|
|
|
371
|
-
A hook is a notification: its failure is logged and nothing else changes.
|
|
372
|
+
A hook is a notification: its failure is logged and nothing else changes. The library awaits some hooks, and gives up on each 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. A host whose `onConnect` does work the connection depends on can set `onConnectFailure: 'close'`: a failing `onConnect` then closes the connection, which on WebSocket is closed before `connection:established` is sent and on SSE is ended after the hook settles. On both transports `onConnect` is seen before the `onDisconnect` that follows it, and an event published while the hook runs may already have reached the client; scope a connection in `AuthenticationResult.rooms` when none may be missed. A connection that `'close'` refuses has also already displaced the user's oldest one when the user is at `maxConnectionsPerUser`: eviction happens at admission, before `onConnect`. On WebSocket the `reason` that `onDisconnect` receives is `CLIENT_DISCONNECT` for every connection, including one the server closed (`disconnect(connectionId, reason)` and `onConnectFailure: 'close'`), so it does not say who closed the connection; on SSE the reason is set when the library closed the connection with one (`disconnect(connectionId, reason)`, the connection bounds) and is `undefined` otherwise: a connection that ended on its own, one that `onConnectFailure: 'close'` refused, or one closed at shutdown.
|
|
372
373
|
|
|
373
374
|
#### The offline-queue read on a reconnect
|
|
374
375
|
|
|
@@ -385,7 +386,7 @@ What the client then does depends on how the attempt ended, and no `Retry-After`
|
|
|
385
386
|
| `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
387
|
| `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
|
|
|
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,
|
|
389
|
+
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, an encoded `+` stays one, and a percent-encoded byte that is not valid UTF-8 is written as the replacement character, so `%FF` becomes `%EF%BF%BD` while a valid sequence such as `%E2%82%AC` is unchanged) 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
|
|
|
390
391
|
#### How many connections one instance holds
|
|
391
392
|
|
|
@@ -402,7 +403,7 @@ The limit has a cost, and it is not a defence by itself. It trades a process tha
|
|
|
402
403
|
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.
|
|
403
404
|
|
|
404
405
|
> [!NOTE]
|
|
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.
|
|
406
|
+
> `maxConnectionsPerUser` defaults to `5` on both transports: a user's sixth connection closes their oldest, which is sent a disconnect. The oldest is closed when the new connection is admitted, before `onConnect` runs, so a connection that `onConnectFailure: 'close'` refuses has already displaced it. `0` switches the cap off. The cap, `replayBufferSize` and `websocket.maxHttpBufferSize` must be integers (`0` or more, and `1` or more for the payload bound) and have a most: 100,000 for the cap on either transport, 100,000 events for `replayBufferSize` (memory per user stream is that times the size of a frame), and 104,857,600 bytes (100 MiB) for `websocket.maxHttpBufferSize`, whose Socket.IO default is 1,000,000 bytes. `NaN`, `Infinity`, a fraction, a numeric string, a value past its most and any integer past 9,007,199,254,740,991 (`1e300`, `2 ** 53`) are refused at start-up, since a comparison with `NaN` is never true and a bound that large never trips. 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.
|
|
406
407
|
|
|
407
408
|
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`.
|
|
408
409
|
|
|
@@ -429,6 +430,57 @@ The design specification, [docs/technical_specification.md](./docs/technical_spe
|
|
|
429
430
|
|
|
430
431
|
---
|
|
431
432
|
|
|
433
|
+
## 🏭 Running in Production
|
|
434
|
+
|
|
435
|
+
This section lists the bounds the library applies, what happens when each one is reached, and what an instance does when a dependency fails. A default is the value in the code. A behaviour stated here is one that a test or a measurement pins, and the `Evidence` column of the second table says which; where nothing pins a behaviour, the row says "not measured".
|
|
436
|
+
|
|
437
|
+
### Limits
|
|
438
|
+
|
|
439
|
+
| Bound | Default | When it is reached |
|
|
440
|
+
| ---------------------------------------------------------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
441
|
+
| `maxConnections` | 10,000 | A handshake past it is refused before `authenticate` is called: SSE answers `503`, WebSocket answers the generic `connect_error`. Connections of both transports count together. See [How many connections one instance holds](#how-many-connections-one-instance-holds). |
|
|
442
|
+
| `maxPendingHandshakes` | 1,000 | A handshake that finds that many `authenticate` calls waiting is refused at once, and `authenticate` is not called. A call whose handshake was refused for taking too long keeps its place while it is still open. See [Authentication is bounded](#authentication-is-bounded). |
|
|
443
|
+
| `authenticateTimeoutMs` | 10,000 ms | A handshake whose `authenticate` has not settled by then is refused: `503` with the generic body on SSE, the generic `connect_error` on WebSocket. A read of the offline queue for a reconnect that carries `Last-Event-ID` is given up on after the same time. See [The offline-queue read on a reconnect](#the-offline-queue-read-on-a-reconnect). |
|
|
444
|
+
| `hookTimeoutMs` | 5,000 ms | A hook the library awaits that has not settled by then is given up on, and the failure is logged as `did not settle within N ms`. See [Hooks the library waits for](#hooks-the-library-waits-for). |
|
|
445
|
+
| `reauthenticationPolicy.revalidateTimeoutMs`, `reauthenticationPolicy.concurrency` | 10,000 ms; 8 | A `revalidate` call that has not settled by then is treated as one that threw, and its connection is revoked. At most `concurrency` calls run at once. |
|
|
446
|
+
| `sse.maxQueuedEvents`, `sse.maxQueuedBytes` | 1,000 events; 2,097,152 bytes | An event that would take the events queued for a connection past `sse.maxQueuedEvents` is not queued; that connection is closed with the reason `REALTIME_SLOW_CONSUMER` and the others are not affected. The queue's counter refuses an event that would take the bytes past `sse.maxQueuedBytes`, unless that event is the only one queued. With the defaults, a client that never reads is closed with the same reason. [A client that does not read](#a-client-that-does-not-read) states the cases this row does not cover. |
|
|
447
|
+
| `sse.stallHeartbeats` | 3 | A connection whose socket has taken nothing for that many heartbeats in a row, while the response holds bytes, is closed with the reason `REALTIME_SLOW_CONSUMER`. |
|
|
448
|
+
| `sse.replayBufferSize`, `sse.replayTtlMs`, `sse.replayMaxIdleUsers` | 100 events; 300,000 ms; 1,000 users | A user's ring keeps the newest `replayBufferSize` events and drops the older ones. An entry is dropped `replayTtlMs` after its user's last connection closed. At most `replayMaxIdleUsers` such entries are kept, and the one that closed longest ago goes first. See [Replay is per instance, and bounded](#replay-is-per-instance-and-bounded). |
|
|
449
|
+
| Length of a `Last-Event-ID` header or `lastEventId` query value | 256 characters | An id longer than that is treated as absent: no replay and no offline-queue read is made for it. An id of exactly 256 characters is used. A longer header with a valid query value falls back to the query value. |
|
|
450
|
+
|
|
451
|
+
### When a dependency fails
|
|
452
|
+
|
|
453
|
+
| Situation | What the instance does | Evidence |
|
|
454
|
+
| ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
455
|
+
| SSE pub/sub: the Redis server refuses the SUBSCRIBE at start (wrong password, missing permission) | `subscribe` rejects with `REALTIME_PUBSUB_UNAVAILABLE`, and the boot fails. | tested |
|
|
456
|
+
| SSE pub/sub: Redis is unreachable at start | The boot completes without waiting for Redis, the instance is not subscribed, one warning line is logged for the outage, not one for each retry, and the instance subscribes when Redis comes up. | tested |
|
|
457
|
+
| Socket.IO Redis adapter: Redis never answers at start | Creating the Socket.IO server returns and the Redis adapter is registered, without waiting for Redis. | tested with a client whose commands never settle |
|
|
458
|
+
| SSE pub/sub: the publishing client's first connection is slow | `subscribe` waits for it, 2,000 ms at most; after that the boot completes and the instance is not subscribed. | tested |
|
|
459
|
+
| SSE pub/sub, Redis lost while running: a publish | It is refused at once with `REALTIME_PUBSUB_UNAVAILABLE` and is never sent when the connection returns. | tested |
|
|
460
|
+
| SSE pub/sub, Redis connected but not answering: a publish | It rejects with `REALTIME_PUBSUB_UNAVAILABLE` after 2,000 ms. The rejection means the server did not confirm the publish in time, not that it was not delivered: the command was already written to the socket, so Redis can still process it when it answers and an emit can arrive after it was reported failed. The command stays queued in the client until the server answers or the connection drops; set `commandTimeout` on your ioredis client (for example `new Redis({ commandTimeout: 5000 })`) to reject the command itself. | tested on a controlled clock; measured on 1.2.16, against a `redis:7-alpine` container paused with `docker pause`: rejected after 2,001, 2,003 and 2,005 ms |
|
|
461
|
+
| SSE pub/sub, Redis lost while running: `disconnect` of a connection this instance does not hold | `disconnect` rejects at once with `REALTIME_PUBSUB_UNAVAILABLE`. `emitToUser` for a user with no connection on this instance, with no offline queue configured, resolves at once. | tested |
|
|
462
|
+
| SSE pub/sub, Redis lost while running: the subscriber | One warning line is logged for an outage while its reconnects fail (several attempts over 400 ms in the test), and a `Subscribed` line is logged again when Redis returns. | tested |
|
|
463
|
+
| Redis is paused when an SSE application closes | The close waits at most 2,000 ms for the subscriber's QUIT, then disconnects it. `app.close()` settled in 2,003 ms. | measured on 1.2.15, against a `redis:7-alpine` container paused with `docker pause`; the bound is also pinned on a controlled clock |
|
|
464
|
+
| Redis is paused when an application with both transports closes | The adapter's subscriber and the pub/sub subscriber are each waited for at most 2,000 ms, one after the other. `app.close()` settled in 4,007 ms. | measured on 1.2.15, against a `redis:7-alpine` container paused with `docker pause`; the two bounds are also pinned on a controlled clock |
|
|
465
|
+
| The offline queue does not answer | A reconnect that carries `Last-Event-ID` gets a `503` with the generic body after `authenticateTimeoutMs`, and nothing is registered. A queue whose first read rejects gives an empty gap instead, and the client gets its live events. At most 1,000 reads wait at once by default; the next is refused without a call to the store. | tested |
|
|
466
|
+
| The authenticator does not answer | Handshakes are refused after `authenticateTimeoutMs`; once `maxPendingHandshakes` calls wait, further handshakes are refused at once. | tested |
|
|
467
|
+
| A consumer hook never settles | The library gives up on it after `hookTimeoutMs`. On WebSocket an `onConnect` that never settles delays the announcement of the connection until then, and an `onDisconnect` that never settles still removes the connection while the other client stays connected. When an application closes, five SSE streams whose `onDisconnect` never settles are released after one hook timeout of a test clock. | tested |
|
|
468
|
+
| Memory over a long soak; behaviour at `maxConnections` on a real host | not measured | not measured |
|
|
469
|
+
|
|
470
|
+
### Shutdown order
|
|
471
|
+
|
|
472
|
+
The Socket.IO server closes first, then the adapter's `dispose()` runs, and `dispose()` closes the adapter's own Redis subscriber connection. The pub/sub subscriber is unsubscribed in the application shutdown hook. When both transports run, the two Redis subscribers are closed in two successive phases, each waited for at most 2,000 ms. [Shutdown](#shutdown) describes how a shutdown starts.
|
|
473
|
+
|
|
474
|
+
### Before you deploy
|
|
475
|
+
|
|
476
|
+
- File-descriptor limit against `maxConnections`: [How many connections one instance holds](#how-many-connections-one-instance-holds).
|
|
477
|
+
- Proxy buffering for SSE: [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
|
|
478
|
+
- Sticky sessions with the polling fallback: [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md#sticky-sessions--mandatory-for-polling-fallback).
|
|
479
|
+
- Replay is per instance: [Replay is per instance, and bounded](#replay-is-per-instance-and-bounded).
|
|
480
|
+
- HTTPS and CORS: [Security Checklist](#security-checklist).
|
|
481
|
+
|
|
482
|
+
---
|
|
483
|
+
|
|
432
484
|
## 🏗️ Architecture
|
|
433
485
|
|
|
434
486
|
The package runs **inside** your NestJS application as a dynamic module — not as a separate realtime server:
|
|
@@ -595,11 +647,11 @@ The unified emit API. Identical on every transport.
|
|
|
595
647
|
|
|
596
648
|
All methods return `Promise<void>`.
|
|
597
649
|
|
|
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.
|
|
650
|
+
**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, and after 2,000 ms when the client is ready but the server does not answer), `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"). `error.message` and `error.cause` are not enumerable, so `JSON.stringify(error)` carries the generic response and the `code` only; `error.stack` and `util.inspect(error)` still carry the text of the driver or the broker, which belongs in your server logs and nowhere a client reads. A rejection means the connection may still be connected, so retry.
|
|
599
651
|
|
|
600
652
|
**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.
|
|
601
653
|
|
|
602
|
-
`joinRoom` and `leaveRoom` act on a connection **this instance holds**; for any other id they resolve and change nothing. A failure of the transport that holds the connection rejects the call.
|
|
654
|
+
`joinRoom` and `leaveRoom` act on a connection **this instance holds**; for any other id they resolve and change nothing. A failure of the transport that holds the connection rejects the call. Both refuse a room id that starts with `user:`, `tenant:` or `connection:`, the names the library composes, and one that is not a non-empty string, with `REALTIME_AUTH_FAILED`; any other name is free-form.
|
|
603
655
|
|
|
604
656
|
**An instance must hear the others.** With `RedisRealtimePubSub`, a subscription the server refuses (a wrong password, a missing permission) **fails the boot**: retrying cannot fix it, and an instance that never hears a revocation must not look healthy. A Redis that is only unreachable does not block the boot. The instance starts, logs once that it is not subscribed, and subscribes when a connection succeeds. Until then, whenever the subscriber connection drops, and whenever the Redis client that publishes cannot publish, `isPubSubReady()` is false. A client built with `lazyConnect` is connected by the adapter. Put it in your readiness probe:
|
|
605
657
|
|
|
@@ -712,7 +764,7 @@ characters and must not start with `user:`, `tenant:` or `connection:`; at most
|
|
|
712
764
|
`ADMISSION_ROOM_LIMITS.MAX_ROOMS` entries; duplicates join once. A result that breaks a rule
|
|
713
765
|
is refused like a blank `userId` — a server fault (500 on SSE, a generic `connect_error` on
|
|
714
766
|
WebSocket), not a 401 — and nothing is registered. The two limits are bounds against abuse, not
|
|
715
|
-
measurements, and they apply to this field only: `joinRoom`
|
|
767
|
+
measurements, and they apply to this field only: `joinRoom` is not held to them.
|
|
716
768
|
|
|
717
769
|
The rooms are fixed at admission and handed back to `revalidate` in the original result. A
|
|
718
770
|
different set returned later is not re-synchronized; use `joinRoom` and `leaveRoom` for changes
|
|
@@ -757,7 +809,7 @@ composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
|
|
|
757
809
|
|
|
758
810
|
A `resource:` room is not tenant-scoped: two tenants using the same type and id share it. When ids are only unique within a tenant, pass the tenant as its own encoded part rather than gluing it to the id with a separator that ids may contain, such as `-`.
|
|
759
811
|
|
|
760
|
-
|
|
812
|
+
`joinRoom` and `leaveRoom` refuse a room id that starts with `user:`, `tenant:` or `connection:`, and all three of `joinRoom`, `leaveRoom` and `emitToRoom` refuse an id that is not a non-empty string (an array, a `Set`, an object, a number, `null`), so a client-supplied value cannot put a connection in another user's or tenant's room. Each refusal is `REALTIME_AUTH_FAILED`. `emitToRoom` does not refuse the prefixes: it can send to such a name, which only reaches that user's or tenant's own connections, so authorise who may emit before you pass it a client-supplied id.
|
|
761
813
|
|
|
762
814
|
#### Role-scoped delivery
|
|
763
815
|
|
|
@@ -863,7 +915,7 @@ The code travels on the error you catch; what reaches a client is decided by the
|
|
|
863
915
|
|
|
864
916
|
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
917
|
|
|
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.
|
|
918
|
+
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. With `@bymax-one/nest-core` 1.6.10 and an `IUnexpectedErrorSink` bound, such a `503` reaches the sink with its `cause`, once for each status and code in each `envelope.serverErrorWindowMs` window (60 s by default), so the outage is recorded there without a filter of your own; the cause can carry a host and a port, so redact it in your logger.
|
|
867
919
|
|
|
868
920
|
**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
921
|
|