@bymax-one/nest-realtime 1.2.17 → 1.2.19
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 +67 -1
- package/README.md +97 -8
- package/dist/internal/index.cjs +677 -110
- package/dist/internal/index.d.cts +130 -9
- package/dist/internal/index.d.ts +130 -9
- package/dist/internal/index.mjs +674 -112
- package/dist/observability/index.cjs +104 -0
- package/dist/observability/index.d.cts +47 -0
- package/dist/observability/index.d.ts +47 -0
- package/dist/observability/index.mjs +104 -0
- package/dist/websocket/index.cjs +117 -19
- package/dist/websocket/index.d.cts +14 -4
- package/dist/websocket/index.d.ts +14 -4
- package/dist/websocket/index.mjs +118 -20
- package/package.json +31 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,70 @@ Versioning is **not** strict [SemVer](https://semver.org/spec/v2.0.0.html) while
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.19] - 2026-11-20
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **Observability, all optional: metrics, a health indicator, spans and log events with stable codes.** A new subpath, `@bymax-one/nest-realtime/observability`, exports `RealtimeMetrics` and `RealtimePubSubHealthIndicator`. Registered as providers of a module of the application, `RealtimeMetrics` publishes `bymax_realtime_connections{transport}`, `bymax_realtime_connections_refused_total{reason}`, `bymax_realtime_evictions_total{reason}`, `bymax_realtime_events_emitted_total{transport}` and `bymax_realtime_slow_consumer_drops_total`, every label from a closed set, and the indicator reports `down` when the bus says it is not subscribed. With `@opentelemetry/api` installed, the library starts `realtime.handshake` and `realtime.reauthenticate` spans, and with no SDK registered they are no-ops. The root and the shared runtime import none of `@bymax-one/nest-core`, `prom-client` or `@opentelemetry/api` statically, which are optional peers, and `pnpm size` fails if one of them reaches those bundles. The README has the Metrics table, the Traces and Health notes and a Log events table.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- **Every `warn` and `error` line is an object with a stable code.** The line is `{ event: 'REALTIME_<EVENT>', message, ...fields }`, so a structured logger writes each as a JSON field and Nest's default logger prints the object instead of a sentence. The message text no longer names a user, a tenant, a room, a channel or a socket: those values were removed from the text, and the logger's own context carries identity. A connection id may be a field. A line that says the library started stays a string.
|
|
19
|
+
- **`bymax_realtime_events_emitted_total` is described as what it counts.** It counts emit calls handled on the instance, including a call with no recipient, and under `'both'` each transport counts it. The metric help text and the README say so.
|
|
20
|
+
|
|
21
|
+
#### Apply to a derived backend
|
|
22
|
+
|
|
23
|
+
An alert or a log filter that matched the text of a `warn` or `error` line now matches the `event` field instead; the codes are in the README. A host that parsed a line for a user, tenant, room or channel will not find it. Metrics start only when the application registers `RealtimeMetrics`, and spans only when it installs `@opentelemetry/api`; without them nothing changes. A class that subclasses `SseTransport`, `SseSubscriptionHandler`, `WebSocketTransport`, `RealtimeGateway` or `ReauthenticationService` and builds it by hand gains optional trailing constructor parameters and keeps working without them.
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- **Inputs were accepted, or failed as a raw `TypeError`, where a typed refusal belongs.** The `sseEndpoint` of `forRootAsync` was not covered by the check `sse.endpoint` got: a number failed as `endpoint.startsWith is not a function` and a blank one registered and served no route. A `forRoot` or `forRootAsync` called with no options, `null`, a string, a number or an array failed as "Cannot convert undefined or null to object", or as a message about `options.transport`; a factory that answered a string or a number was read the same way. A `Date` was accepted as `sse`, `websocket`, `reauthenticationPolicy` or `hooks`, because it is not an array. `new RedisOfflineQueue(undefined)` threw a raw `TypeError` and a string was accepted with no `client`. An endpoint with a space in it, `' /x '` or `'/a b'`, was registered and unreachable. Each of those is now refused with `REALTIME_INVALID_OPTIONS`, naming the option and what it received (`a built-in object` for a `Date`, a `Map` and the like). A `forRootAsync` pattern (`useFactory`, `useClass` or `useExisting`) set to `null` now reads as unset, like `undefined`: beside the pattern in use it is no longer counted as a second one, and alone it is refused at registration instead of failing at bootstrap with the container's own error.
|
|
28
|
+
- **A handshake that failed with an unexpected error counted in no metric, a `useExisting` that resolved to nothing failed with a raw `TypeError`, a proxy whose reads throw reached the application with its own error, and the cache warning was written before the logger was in place.** A 500 handshake now counts under `bymax_realtime_connections_refused_total{reason="error"}`. A `useExisting` or `useClass` provider with no `createRealtimeOptions` is refused with `REALTIME_INVALID_OPTIONS` at bootstrap. A proxy whose reads throw, given as the options or as a group, is refused as `a built-in object`. `REALTIME_REAUTH_CACHE_WEAKENS_POLICY` is written when the re-authentication service starts, through the application's logger, and no longer at registration.
|
|
29
|
+
|
|
30
|
+
#### Apply to a derived backend
|
|
31
|
+
|
|
32
|
+
A `sseEndpoint` or `sse.endpoint` that held whitespace, an options argument or factory result that was not an object, and a group that was a `Date` or another built-in now fail at registration, where they used to start or fail later: fix the value. A `RedisOfflineQueue` built without options or without a `client` now throws at construction. An instance of your own class is still read as a group by its keys, unless it sets its own `Symbol.toStringTag` to something other than `'Object'`.
|
|
33
|
+
|
|
34
|
+
A dashboard that sums `bymax_realtime_connections_refused_total` over its labels now includes `reason="error"`. A log pipeline that found `REALTIME_REAUTH_CACHE_WEAKENS_POLICY` at registration finds it at start-up, after `app.useLogger`, and only when the authenticator implements `revalidate`.
|
|
35
|
+
|
|
36
|
+
### Security
|
|
37
|
+
|
|
38
|
+
- **A log line no longer carries the text of an error raised by the application's own code.** Events such as `REALTIME_HANDSHAKE_FAILED`, `REALTIME_HOOK_FAILED`, `REALTIME_DELIVERY_FAILED`, `REALTIME_DISCONNECT_FAILED`, `REALTIME_OFFLINE_QUEUE_ACK_FAILED`, `REALTIME_PUBSUB_UNSUBSCRIBE_FAILED`, `REALTIME_REAUTH_FAILED`, `REALTIME_REVOCATION_FAILED`, `REALTIME_COMPOSITE_PARTIAL_FAILURE`, `REALTIME_PUBSUB_UNAVAILABLE` put the error's own message into `message`, so an authenticator or a hook that threw `x user=U tenant=T` reached the line. `message` now holds the library's own text only, and the error goes under `err` as the error itself, which is where a structured logger applies its serializer and its redaction. A spec reads every `logEvent` call and fails when a message reads an error.
|
|
39
|
+
|
|
40
|
+
#### Apply to a derived backend
|
|
41
|
+
|
|
42
|
+
An alert, a filter or a dashboard that matched the text of an application error in the `message` of one of those events must read the `err` field instead. A custom `LoggerService` that turns a log argument into a string prints the object, including `err`; give it the object, or serialize `err` in it.
|
|
43
|
+
|
|
44
|
+
### Documentation
|
|
45
|
+
|
|
46
|
+
- **The README names every export of every public subpath.** A spec now fails when a name in the public-surface snapshot, or one of the contract members an implementor writes, is missing from it. The README gained a Types and constants section and the Observability section.
|
|
47
|
+
- **The README says what a duplicate `socket.io` does.** Two copies in `node_modules` make TypeScript report TS2416 on `RealtimeIoAdapter` under `skipLibCheck: false`; the fix is one copy.
|
|
48
|
+
- **The README names the `./internal` exports and `ITransport.kind`, and a spec holds it.** The spec that fails when a public export is not named now covers the names `./internal` exports explicitly. The README also says that `./observability` needs its optional peers, and that without them the import fails with the runtime's own `Cannot find module` error, which names the peer.
|
|
49
|
+
|
|
50
|
+
## [1.2.18] - 2026-11-17
|
|
51
|
+
|
|
52
|
+
### Security
|
|
53
|
+
|
|
54
|
+
- **An option set to `undefined` resolved to "no bound", and a refusal echoed what it was given.** The defaults were merged with `{ ...DEFAULT_SSE, ...options.sse }`, so an own key holding `undefined` overwrote its default. Measured on 1.2.17 with `sse: { maxConnectionsPerUser: undefined, maxQueuedBytes: undefined, maxQueuedEvents: undefined, stallHeartbeats: undefined, replayBufferSize: undefined }`: the options the services receive carried `undefined` for all five, the per-user eviction returns early on `undefined` (no cap), and the three queue bounds are read with `?? 0`, which switches them off. A host that spelled an option as `cond ? value : undefined` therefore ran with the bound off instead of the default. Separately, the refusals of the numeric and enum options ended in `got <value>`, which printed whatever the host had passed: a token pasted into the wrong field, or the source text of a function. Now the keys that hold `undefined` or `null` are dropped, at the top level and in `sse`, `websocket` and `reauthenticationPolicy`, before the defaults are merged and before validation, so such an option resolves to its default and is validated as absent; a group handed over as a class instance is read through its fields and getters, as the services read it, so it is covered too. Every refusal of an option names the option and the type of what it received (`received a string`), prints a finite number, and echoes nothing else; the two `forRootAsync` endpoint refusals no longer print the paths.
|
|
55
|
+
|
|
56
|
+
- **`RedisOfflineQueue` accepted a `maxPerUser` or a `ttlSeconds` that loses or corrupts the queue.** Measured on Redis 7: a `ttlSeconds` of `0` or a negative made `EXPIRE` delete the key, so every append was dropped without an error; a `maxPerUser` of `0` made the trim remove every entry; and `NaN`, a fraction, `Infinity`, `1e300` or a value Redis rejects made the pipeline fail after `ZADD` had already run, which left the entries untrimmed or the key without an expiry, and every append rejected. A numeric string such as `'3'` concatenated in the trim (`'3' + 1` is `'31'`), keeping up to 30 events. The constructor now refuses anything that is not a safe integer from 1 to 100,000 for `maxPerUser` and from 1 to 2,147,483,647 for `ttlSeconds`, with `REALTIME_INVALID_OPTIONS` naming the option and its range and describing what it received by type (a finite number is printed). A `maxPerUser` or `ttlSeconds` of `undefined` or `null` is read as unset and takes its default.
|
|
57
|
+
|
|
58
|
+
- **A malformed pluggable piece, group or flag was accepted at start-up and failed later, or did the opposite of what it said.** Measured on 1.2.17 with `forRoot`: `pubsub: {}` and a `pubsub` without `subscribe` were accepted and the application then failed at init with a raw `this.pubsub.subscribe is not a function`; `sse.endpoint: 5` failed at registration with `endpoint.startsWith is not a function`; `offlineQueue: {}` and `presence: {}` were accepted, and with `offlineQueue: {}` an emit to an offline user rejected at run time with `REALTIME_TRANSPORT_UNAVAILABLE`; `tenantResolver: 'x'` was accepted and every handshake then threw a `TypeError` at `tenantResolver?.(auth)`; `hooks`, `sse`, `websocket` and `reauthenticationPolicy` were accepted as strings; `sse.emitConnectionEvent: 'no'` was accepted and read as true because it is truthy. `forRoot` now refuses each at registration with `REALTIME_INVALID_OPTIONS`, naming the option and describing what it received by type: a group (`sse`, `websocket`, `reauthenticationPolicy`) and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must be objects with every function of their interface, which may be on a class prototype; each lifecycle hook that is set and `tenantResolver` must be functions; the two `emitConnectionEvent` flags must be booleans; and `sse.endpoint` must be a non-blank string, with or without a leading slash.
|
|
59
|
+
|
|
60
|
+
#### Apply to a derived backend
|
|
61
|
+
|
|
62
|
+
An option that holds `null` was refused (`got null`) and is now read as unset, like `undefined`: it takes its default. An option you meant to leave unlimited with `undefined` now takes its default instead, so say `0` where `0` switches the bound off. A test that pinned the text of a refusal (`got 1000`, `(got: carrier-pigeon)`) now reads `received 1000` and `received a string`.
|
|
63
|
+
|
|
64
|
+
A queue built with `new RedisOfflineQueue({ client, maxPerUser, ttlSeconds })` now throws at construction for a value outside those ranges, where it used to start and lose events. If you passed `0` to mean unlimited, there is no such mode: pick the count you can afford to hold per user.
|
|
65
|
+
|
|
66
|
+
A test double for the bus, the offline queue or presence that implements only the functions a test calls is now refused at registration: give it every required function, as a no-op where it does nothing. A flag you passed as a string (`'false'`) is refused instead of being read as true; pass a boolean.
|
|
67
|
+
|
|
68
|
+
### Documentation
|
|
69
|
+
|
|
70
|
+
- **Details the 1.2.17 notes did not state.** A subclass of `WebSocketTransport` that replaces `joinRooms` drops, besides the user, tenant and connection rooms, the rooms an authenticator returns (`AuthenticationResult.rooms`) and the update of the `RoomRegistry`; a `static` member named `joinRooms` or `runOnConnect` compiles, because only the instance members are private; and for `emitToRoom` the change a caller can observe in 1.2.17 is that a `roomId` that is not a non-empty string is refused as a rejected promise, an outcome 1.2.16 did not have. `CONTRIBUTING.md` no longer describes a `commit-msg` hook and a `pre-commit` hook that this repository does not have.
|
|
71
|
+
|
|
72
|
+
- **A shutdown can wait six seconds for a client that stopped reading.** `app.close()` ends every stream at once, but Node's HTTP server then waits for the sockets of clients that no longer read, for `keepAliveTimeout` and a check interval: 6,004 ms measured, against 3 ms with `forceCloseConnections: true`. The README's "Shutdown" section now says so. Apply: pass `{ forceCloseConnections: true }` to `NestFactory.create`, or give the process a termination grace of at least 7 seconds.
|
|
73
|
+
|
|
10
74
|
## [1.2.17] - 2026-11-17
|
|
11
75
|
|
|
12
76
|
### Added
|
|
@@ -1139,7 +1203,9 @@ First published release.
|
|
|
1139
1203
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
1140
1204
|
asked about NestJS and never put the same question to the other ten peers.
|
|
1141
1205
|
|
|
1142
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
1206
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.19...HEAD
|
|
1207
|
+
[1.2.19]: https://github.com/bymaxone/nest-realtime/compare/v1.2.18...v1.2.19
|
|
1208
|
+
[1.2.18]: https://github.com/bymaxone/nest-realtime/compare/v1.2.17...v1.2.18
|
|
1143
1209
|
[1.2.17]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...v1.2.17
|
|
1144
1210
|
[1.2.16]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...v1.2.16
|
|
1145
1211
|
[1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
|
package/README.md
CHANGED
|
@@ -82,14 +82,15 @@ The default transport is **Server-Sent Events**: browser-native, plain HTTP, no
|
|
|
82
82
|
|
|
83
83
|
## 📦 Subpath Exports
|
|
84
84
|
|
|
85
|
-
One package,
|
|
85
|
+
One package, several entry points — import only what your app needs:
|
|
86
86
|
|
|
87
|
-
| Subpath
|
|
88
|
-
|
|
|
89
|
-
| **Server**
|
|
90
|
-
| **WebSocket**
|
|
91
|
-
| **Shared**
|
|
92
|
-
| **React**
|
|
87
|
+
| Subpath | Import | Purpose | Dependencies |
|
|
88
|
+
| ----------------- | ---------------------------------------- | ---------------------------------------------- | :---------------------------------------------------------------: |
|
|
89
|
+
| **Server** | `@bymax-one/nest-realtime` | NestJS module for SSE, services, contracts | NestJS 11, rxjs |
|
|
90
|
+
| **WebSocket** | `@bymax-one/nest-realtime/websocket` | NestJS module for `'websocket'` and `'both'` | + `@nestjs/websockets`, `@nestjs/platform-socket.io`, `socket.io` |
|
|
91
|
+
| **Shared** | `@bymax-one/nest-realtime/shared` | Types, room prefixes, event names, error codes | None |
|
|
92
|
+
| **React** | `@bymax-one/nest-realtime/react` | Hooks & `RealtimeProvider` | React 19 |
|
|
93
|
+
| **Observability** | `@bymax-one/nest-realtime/observability` | Metrics contributor, pub/sub health indicator | + `@bymax-one/nest-core`, `prom-client` (optional) |
|
|
93
94
|
|
|
94
95
|
```
|
|
95
96
|
shared (zero deps)
|
|
@@ -103,6 +104,8 @@ One package, four entry points — import only what your app needs:
|
|
|
103
104
|
|
|
104
105
|
The package also exposes `@bymax-one/nest-realtime/internal`. It is **not public API** and carries no compatibility promise — it is the shared runtime the two server subpaths import so that a service registered through one and injected through the other is the same class. Import the four above; nothing you need is only there.
|
|
105
106
|
|
|
107
|
+
These names from `./internal`, none of them API and none with a compatibility promise, are grouped below. Composition: `composeForRoot`, `composeForRootAsync`, `TransportRegistration`, `TransportWiring` and `sseWiring`. Shared services: `EventIdGenerator`, `ReauthenticationService`, `AuthenticationGate`, `AuthenticationUnavailableError`, `ConnectionAdmission`, `ConnectionLimitError`, `UNBOUNDED_TICKET`, `AdmissionTicket`, `OfflineQueueDeliveryService`, `EventReplayBuffer`, `HeartbeatService`, `SseSubscriptionHandler`, `createSseController`, `RoomRegistry`, `SseTransport` and `RealtimePubSubSubscriber`. Observability seams: `RealtimeMetricsTally`, `REFUSAL_REASONS`, `EVICTION_REASONS`, `TALLY_TRANSPORTS`, `RefusalReason`, `EvictionReason`, `TallyTransport`, `RealtimeTracing`, `RealtimeSpanName`, `RealtimeSpanAttributes`, `logEvent`, `REALTIME_LOG_EVENTS`, `RealtimeLogEvent` and `LogFields`. Utilities: `DEFAULT_HOOK_TIMEOUT_MS`, `assertIdentityIsNotBlank`, `resolveAuthTenant`, `admitRooms`, `describeError`, `quitWithin`, `QuitableClient`, `runHook`, `unavailableError`, `refuseReservedRoom`, `requireRoomName`, `realtimeError`, `CodedError`, `reportDeliveryFailure` and `parseCookieHeader`.
|
|
108
|
+
|
|
106
109
|
---
|
|
107
110
|
|
|
108
111
|
> [!TIP]
|
|
@@ -284,7 +287,7 @@ For WebSocket, scaling goes through Socket.IO's own Redis adapter instead, confi
|
|
|
284
287
|
|
|
285
288
|
### 7. Add WebSocket (optional)
|
|
286
289
|
|
|
287
|
-
WebSocket lives behind its own subpath, so an SSE application never installs the Socket.IO stack. Install its peers (see [Install](#1-install)), then do two things: register `BymaxRealtimeWebSocketModule` from `/websocket` instead of `BymaxRealtimeModule`, and install `RealtimeIoAdapter` in `main.ts`.
|
|
290
|
+
WebSocket lives behind its own subpath, so an SSE application never installs the Socket.IO stack. Install its peers (see [Install](#1-install)), then do two things: register `BymaxRealtimeWebSocketModule` from `/websocket` instead of `BymaxRealtimeModule`, and install `RealtimeIoAdapter` in `main.ts`. Two copies of `socket.io` in `node_modules` make TypeScript report TS2416 on `RealtimeIoAdapter` under `skipLibCheck: false`; dedupe to one copy.
|
|
288
291
|
|
|
289
292
|
```typescript
|
|
290
293
|
// app.module.ts
|
|
@@ -405,6 +408,10 @@ An SSE response writes one event at a time and waits for the client to read befo
|
|
|
405
408
|
> [!NOTE]
|
|
406
409
|
> `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.
|
|
407
410
|
|
|
411
|
+
An option that holds `undefined` or `null` is read as unset: it takes its default, in the module options and in `sse`, `websocket` and `reauthenticationPolicy`, so `maxConnectionsPerUser: cond ? 3 : undefined` means the default cap of `5`, never no cap. Say `0` where `0` switches a bound off. A refusal of an option names the option and the type of what it received (`received a string`), prints a finite number, and echoes nothing else, so a value pasted into the wrong field does not reach a log.
|
|
412
|
+
|
|
413
|
+
The shape of what you pass is checked at start-up too, and refused with `REALTIME_INVALID_OPTIONS`: `sse`, `websocket`, `reauthenticationPolicy` and `hooks` must be objects; `pubsub`, `offlineQueue` and `presence` must have every function of their interface (`IRealtimePubSub`, `IOfflineQueueStorage`, `IPresenceStorage`), on the object or its prototype; each hook that is set and `tenantResolver` must be a function; `sse.emitConnectionEvent` and `websocket.emitConnectionEvent` must be booleans; `sse.endpoint` must be a non-blank string, with or without a leading slash. An endpoint holds no whitespace, because no request can reach it, and the `sseEndpoint` of `forRootAsync` gets the same check. The options argument must be an object, and so must what a `forRootAsync` factory returns; an array, a `Date` or a `Map` is refused there and where a group is expected, while an instance of your own class is read by its keys. `new RedisOfflineQueue(options)` refuses options that are not an object and a `client` that is not one.
|
|
414
|
+
|
|
408
415
|
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`.
|
|
409
416
|
|
|
410
417
|
> [!IMPORTANT]
|
|
@@ -471,6 +478,65 @@ This section lists the bounds the library applies, what happens when each one is
|
|
|
471
478
|
|
|
472
479
|
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
480
|
|
|
481
|
+
### Observability
|
|
482
|
+
|
|
483
|
+
Everything here is optional. The root and the shared runtime import none of `@bymax-one/nest-core`, `prom-client` or `@opentelemetry/api` statically, so an application that publishes no metrics installs none of them.
|
|
484
|
+
|
|
485
|
+
Importing `@bymax-one/nest-realtime/observability` needs `@bymax-one/nest-core` and `prom-client`; without them the import fails with the runtime's own `Cannot find module` error, which names the missing peer.
|
|
486
|
+
|
|
487
|
+
**Metrics.** Register `RealtimeMetrics` in a module of your application; `BymaxCoreModule` discovers it and calls it once at bootstrap with the registry its scrape endpoint serves. It injects what the realtime module exports, so nothing else is wired.
|
|
488
|
+
|
|
489
|
+
```typescript
|
|
490
|
+
import { Module } from '@nestjs/common'
|
|
491
|
+
import {
|
|
492
|
+
RealtimeMetrics,
|
|
493
|
+
RealtimePubSubHealthIndicator,
|
|
494
|
+
} from '@bymax-one/nest-realtime/observability'
|
|
495
|
+
|
|
496
|
+
@Module({ providers: [RealtimeMetrics, RealtimePubSubHealthIndicator] })
|
|
497
|
+
export class ObservabilityModule {}
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
| Metric | Type | Labels | Meaning |
|
|
501
|
+
| ------------------------------------------ | ------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
|
502
|
+
| `bymax_realtime_connections` | gauge | `transport` = `sse`, `websocket` | Connections open on this instance now. |
|
|
503
|
+
| `bymax_realtime_connections_refused_total` | counter | `reason` = `limit`, `unauthorized`, `unavailable`, `error` | Handshakes refused since start; `error` is one that failed with an unexpected error (a 500). |
|
|
504
|
+
| `bymax_realtime_evictions_total` | counter | `reason` = `per_user_cap`, `slow_consumer`, `revoked` | Connections closed by the library or by a revocation. |
|
|
505
|
+
| `bymax_realtime_events_emitted_total` | counter | `transport` = `sse`, `websocket` | Emit calls handled on this instance, not deliveries: a call with no recipient counts, and under `'both'` each transport counts it. |
|
|
506
|
+
| `bymax_realtime_slow_consumer_drops_total` | counter | none | Connections cut for not reading what they were sent. |
|
|
507
|
+
|
|
508
|
+
A label is one of the values listed and never an id, a tenant or a user. A revocation is counted on the instance that was asked to make it, once it has closed the connection or handed the request to the bus.
|
|
509
|
+
|
|
510
|
+
**Health.** `RealtimePubSubHealthIndicator` (name `realtime-pubsub`) reports `down` when the bus says it is not subscribed, so what other instances publish no longer reaches this one. It reads the bus's own state, sends nothing and returns no detail. A bus that does not report its state, such as the in-memory one, counts as up.
|
|
511
|
+
|
|
512
|
+
**Traces.** With `@opentelemetry/api` installed the library starts `realtime.handshake` around the admission and authentication of each connection (attribute `bymax.realtime.transport`, `sse` or `websocket`) and `realtime.reauthenticate` around each re-authentication cycle. A refused handshake ends its span with status ERROR and the library error code, never the message. With no SDK registered the API is a no-op, and without the package nothing is started.
|
|
513
|
+
|
|
514
|
+
**Log events.** Every `warn` and `error` line the library writes is an object, `{ event, message, ...fields }`, with the error that caused a failure, when there is one, under `err` as the error itself and never as text in `message`; so a structured logger writes each as a JSON field and Nest's default logger prints the object. The fields are counts, sizes, configured limits, transport names and a library-made connection id; a user id, a tenant id or a room is never in a message or a field, because the logger's own context carries identity. Lines that report that the library started stay plain strings.
|
|
515
|
+
|
|
516
|
+
| Event | Level | When | Fields |
|
|
517
|
+
| -------------------------------------- | ----------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
|
518
|
+
| `REALTIME_REAUTH_CACHE_WEAKENS_POLICY` | warn | At start-up, `reauthenticationPolicy.cacheTtlMs` is longer than the interval. | `cacheTtlMs`, `intervalMs` |
|
|
519
|
+
| `REALTIME_HANDSHAKE_FAILED` | error | A handshake failed with an error that is not a refusal. | `socketId` (WebSocket) |
|
|
520
|
+
| `REALTIME_HOOK_FAILED` | warn, error | A lifecycle hook threw or did not settle within `hookTimeoutMs`. | `hook` where known |
|
|
521
|
+
| `REALTIME_DELIVERY_FAILED` | warn | A delivery failed without failing its call. | `connectionId` or `code`, `op` |
|
|
522
|
+
| `REALTIME_SLOW_CONSUMER` | warn | A connection was cut for not reading what it was sent. | `connectionId`, `queuedEvents`, `queuedBytes`, `heldBytes` |
|
|
523
|
+
| `REALTIME_DISCONNECT_FAILED` | warn | Closing a connection failed. | `connectionId` |
|
|
524
|
+
| `REALTIME_RECONNECTS_GIVEN_UP` | warn | Reconnects were given up on because the offline queue did not answer (windowed). | `count`, `timeoutMs`, `maxPending` |
|
|
525
|
+
| `REALTIME_OFFLINE_QUEUE_LIMIT` | warn | A read of the offline queue reached its event limit. | `limit` |
|
|
526
|
+
| `REALTIME_OFFLINE_QUEUE_ACK_FAILED` | warn | Acknowledging the offline queue failed. | none |
|
|
527
|
+
| `REALTIME_PUBSUB_NOT_PROVIDED` | warn | In production, no `IRealtimePubSub` was provided: single instance only. | none |
|
|
528
|
+
| `REALTIME_PUBSUB_UNSUBSCRIBE_FAILED` | warn | Unsubscribing from the bus failed at shutdown. | none |
|
|
529
|
+
| `REALTIME_PUBSUB_DROPPED` | warn | The bus dropped messages it could not act on (windowed). | `count`, `last` |
|
|
530
|
+
| `REALTIME_PUBSUB_UNAVAILABLE` | warn | The bus refused or lost the subscription; remote events do not reach this instance. | none |
|
|
531
|
+
| `REALTIME_CONNECTIONS_REFUSED` | warn | Connections were refused at `maxConnections` (windowed). | `count`, `maxConnections` |
|
|
532
|
+
| `REALTIME_HANDSHAKES_REFUSED` | warn | Handshakes were refused because the authenticator was saturated or slow (windowed). | `saturated`, `timedOut`, `maxPendingHandshakes`, `authenticateTimeoutMs` |
|
|
533
|
+
| `REALTIME_REAUTH_FAILED` | warn | A re-authentication cycle, a check or its notification failed. | `connectionId` where known |
|
|
534
|
+
| `REALTIME_REVOCATION_FAILED` | warn | A revocation failed and is retried on the next cycle. | `connectionId` |
|
|
535
|
+
| `REALTIME_ADAPTER_MISSING` | error | `RealtimeIoAdapter` is not the active WebSocket adapter. | none |
|
|
536
|
+
| `REALTIME_ADAPTER_COMMAND_FAILED` | warn | A command of the Redis adapter's subscriber failed (once for each connection). | none |
|
|
537
|
+
| `REALTIME_COMPOSITE_PARTIAL_FAILURE` | warn | One of the two transports failed an emit under `transport: 'both'`. | `op` |
|
|
538
|
+
| `REALTIME_SERVER_NOT_ATTACHED` | warn | An emit was made before the WebSocket server was attached (once). | `op` |
|
|
539
|
+
|
|
474
540
|
### Before you deploy
|
|
475
541
|
|
|
476
542
|
- File-descriptor limit against `maxConnections`: [How many connections one instance holds](#how-many-connections-one-instance-holds).
|
|
@@ -703,6 +769,8 @@ Read-side view of live connections — useful for admin endpoints and metrics. T
|
|
|
703
769
|
|
|
704
770
|
Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
|
|
705
771
|
|
|
772
|
+
`RedisOfflineQueue` takes `maxPerUser` (default 500) and `ttlSeconds` (default 3600), each an integer: `maxPerUser` from 1 to 100,000 and `ttlSeconds` from 1 to 2,147,483,647. A value outside that is refused when the queue is constructed, with `REALTIME_INVALID_OPTIONS`, because Redis would otherwise turn it into a silent loss: see the changelog entry for what each value did.
|
|
773
|
+
|
|
706
774
|
#### Identity must be present or absent, never blank
|
|
707
775
|
|
|
708
776
|
`userId` must be a non-empty string, and `tenantId` either absent or a non-empty string. A connection whose authenticator, or whose `tenantResolver`, yields a blank one is **refused at bootstrap** as a server fault, not a `401`: blank is not missing. Every connection carrying `''` lands under the same registry key and joins the same `user:` or `tenant:` room, and a later emit reaches all of them. Whitespace counts as blank.
|
|
@@ -923,6 +991,27 @@ Nest's default exception filter does not log an `HttpException`, so a `503` from
|
|
|
923
991
|
|
|
924
992
|
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.
|
|
925
993
|
|
|
994
|
+
A client that stopped reading holds its socket open after the library has ended its stream, and Node's HTTP server waits for it: `app.close()` took 6,004 ms with such clients and 3 ms with `forceCloseConnections: true`. Create the application with `NestFactory.create(AppModule, { forceCloseConnections: true })`, or give the process a termination grace of at least 7 seconds.
|
|
995
|
+
|
|
996
|
+
### Types and constants
|
|
997
|
+
|
|
998
|
+
Every name below is exported; the subpath says where to import it from. A type is erased at run time, a constant is a value.
|
|
999
|
+
|
|
1000
|
+
**Options.** `BymaxRealtimeModuleOptions` is the configuration of `forRoot`, and `BymaxRealtimeModuleAsyncOptions` that of `forRootAsync` (`useFactory`, `useClass`, `useExisting`, `inject`, `imports`, `sseEndpoint` and `extraProviders`, the providers to register beside the module, for instance an authenticator class that Nest manages). `SseOptions` and `WebSocketOptions` are the `sse` and `websocket` groups, `ReauthenticationPolicy` is `reauthenticationPolicy`, and `CorsConfig` is the CORS configuration both transports share. `RedisOfflineQueueOptions` and `RedisRealtimePubSubOptions` configure the two Redis implementations that ship with the package.
|
|
1001
|
+
|
|
1002
|
+
**What a hook or an authenticator receives.** `AuthenticatorCallOptions` is what `authenticate` and `revalidate` are handed besides their subject. `DeliveryFailure` is what `onDeliveryFailure` receives when a delivery path failed without failing the call that depended on it. `PublicConnectionMeta` is the public-facing metadata of one connection.
|
|
1003
|
+
|
|
1004
|
+
**Events and rooms** (from `@bymax-one/nest-realtime/shared`). `RealtimeEvent` is the shape of an event over a transport (`id`, `type` and `data`) and `ReservedEventName` the union of the names the library reserves. `ROOM_PREFIXES` is the table of canonical room prefixes and `RoomPrefix` the union of its values. `TransportMode` is `'sse' | 'websocket' | 'both'`. `REALTIME_ERROR_CODES` is the table of the stable error codes, such as `REALTIME_AUTH_FAILED`.
|
|
1005
|
+
|
|
1006
|
+
**Queues and the bus.** `OfflineQueuedEvent` is one event held in a user's offline queue, and `RealtimePubSubMessage` is one message that crosses instances.
|
|
1007
|
+
|
|
1008
|
+
**Members of the contracts you implement.**
|
|
1009
|
+
|
|
1010
|
+
- `IOfflineQueueStorage`: `append` stores an event for a user, `retrieveSince` reads the ones after an id, and `acknowledge` marks events delivered up to an id, which an implementation may purge or keep.
|
|
1011
|
+
- `IPresenceStorage`: `setOnline` and `setOffline` record a connection, `isOnline` answers for a user, `listOnlineByTenant` lists a tenant's online users and `countOnline` counts everyone.
|
|
1012
|
+
- `IRealtimePubSub`: `publish` sends to the other instances, `subscribe` receives, and the optional `isSubscribed` says whether this instance is subscribed now. A bus that cannot be unsubscribed once subscribed omits it and counts as subscribed; the health indicator reads it.
|
|
1013
|
+
- `ITransport`: `kind` names the transport, `'sse'` or `'websocket'`; the optional `onModuleInit`, `beforeApplicationShutdown` and `onApplicationShutdown` are called by Nest on bootstrap and on shutdown, the second before the HTTP server closes.
|
|
1014
|
+
|
|
926
1015
|
### DI Tokens
|
|
927
1016
|
|
|
928
1017
|
`REALTIME_OPTIONS_TOKEN` · `REALTIME_TRANSPORT_TOKEN` · `REALTIME_AUTHENTICATOR_TOKEN` · `REALTIME_PUBSUB_TOKEN` · `REALTIME_OFFLINE_QUEUE_TOKEN` · `REALTIME_PRESENCE_TOKEN` · `REALTIME_HOOKS_TOKEN` · `REALTIME_INSTANCE_ID_TOKEN`
|