@bymax-one/nest-realtime 1.2.6 → 1.2.8
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 +145 -1
- package/README.md +84 -52
- package/dist/internal/index.cjs +296 -436
- package/dist/internal/index.d.cts +215 -45
- package/dist/internal/index.d.ts +215 -45
- package/dist/internal/index.mjs +295 -437
- package/dist/react/index.cjs +0 -2
- package/dist/react/index.d.cts +2 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.mjs +0 -2
- 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 -1
- package/dist/shared/index.d.ts +3 -1
- package/dist/shared/index.mjs +1 -0
- package/dist/websocket/index.cjs +60 -283
- package/dist/websocket/index.d.cts +30 -11
- package/dist/websocket/index.d.ts +30 -11
- package/dist/websocket/index.mjs +61 -284
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,148 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.8] - 2026-11-06
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **Built with tsup 9; the shipped bundles no longer carry comments.** The build now strips the
|
|
15
|
+
comments from `dist/**/index.mjs` and `dist/**/index.cjs` after bundling, keeping legal comments,
|
|
16
|
+
`__PURE__` annotations and region markers, and checks that the program is unchanged. The
|
|
17
|
+
declarations keep their comments. The public surface is the same. The `internal` bundle is
|
|
18
|
+
12,293 B brotli, inside its 13,500 B budget; the other budgets were reset to the stripped size
|
|
19
|
+
plus about 11%.
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- **A host Redis client built with `enableOfflineQueue: false` no longer fails the boot of `RedisRealtimePubSub`.**
|
|
24
|
+
The subscriber connection is a copy of the host client and inherited that option, so its first
|
|
25
|
+
`SUBSCRIBE`, issued before the connection exists, was refused by ioredis at once with
|
|
26
|
+
`Stream isn't writeable and enableOfflineQueue options is false`. Since 1.2.7 that rejection was
|
|
27
|
+
treated as the server refusing the subscription and failed the boot with
|
|
28
|
+
`REALTIME_PUBSUB_UNAVAILABLE`, while Redis was healthy; before 1.2.7 the same combination logged a
|
|
29
|
+
warning and left the instance without cross-instance delivery. The subscriber connection now keeps its own offline queue on, and only an error
|
|
30
|
+
reply from the server counts as a refusal: any other rejection of the first `SUBSCRIBE` is the
|
|
31
|
+
connection failing, so the boot completes unready and recovers like any outage.
|
|
32
|
+
- **`disconnect()` no longer hangs through a Redis outage.** `RedisRealtimePubSub.publish` handed
|
|
33
|
+
the command to ioredis even while the client was reconnecting, and ioredis queued it until the
|
|
34
|
+
connection returned (still pending after 30 s with its default options), so a revocation, and
|
|
35
|
+
every emit, waited out the whole outage and was then sent late. It now rejects at once with
|
|
36
|
+
`REALTIME_PUBSUB_UNAVAILABLE` (`cannot publish to "<channel>" (the Redis client is reconnecting)`)
|
|
37
|
+
while the client is reconnecting, closed or ended, and never queues the command. `disconnect()`
|
|
38
|
+
rejects with that code so the caller can retry, and an emit no longer waits for the outage.
|
|
39
|
+
- **An `sse.heartbeatMs` outside the allowed range now stops the application at start-up.** The
|
|
40
|
+
boot check only rejected a value of zero or less, while the heartbeat service refuses anything
|
|
41
|
+
outside 5,000 to 90,000 ms each time a connection opens. A value such as `1000` or `100000`
|
|
42
|
+
therefore started the application and then answered every SSE connection with a 500.
|
|
43
|
+
`NaN`, which comes from `Number(process.env.HEARTBEAT_MS)` when the variable is unset, passed
|
|
44
|
+
both checks and made the keepalive timer fire about every millisecond on every connection.
|
|
45
|
+
`validateOptions` now applies the same range, for `forRoot` and `forRootAsync`, and the error
|
|
46
|
+
names it: `options.sse.heartbeatMs must be between 5000 and 90000 ms (got 1000)`.
|
|
47
|
+
|
|
48
|
+
#### Apply to a derived backend
|
|
49
|
+
|
|
50
|
+
A `disconnect()` made during a Redis outage now rejects immediately instead of waiting for the
|
|
51
|
+
reconnect, so the retry you already need for a rejected `disconnect()` happens sooner. An emit made
|
|
52
|
+
during an outage is no longer held and delivered late.
|
|
53
|
+
|
|
54
|
+
If your configuration sets `sse.heartbeatMs`, check it is between 5,000 and 90,000 ms. A value
|
|
55
|
+
outside it already failed every connection, except `NaN`, which flooded each connection with
|
|
56
|
+
keepalives; now every one of them fails when the application starts.
|
|
57
|
+
|
|
58
|
+
If you pass `RedisRealtimePubSub` a client created with `enableOfflineQueue: false`,
|
|
59
|
+
upgrade to this release. 1.2.7 fails the boot with `REALTIME_PUBSUB_UNAVAILABLE`
|
|
60
|
+
on such a client. Earlier versions did not fail: they logged `Failed to subscribe to pub/sub ...
|
|
61
|
+
Cross-instance fan-out disabled` once at start-up and then ran without cross-instance delivery, so
|
|
62
|
+
if you ran one of them with such a client, revocations and emits from your other instances may
|
|
63
|
+
never have reached it. Nothing needs to change in your configuration.
|
|
64
|
+
|
|
65
|
+
## [1.2.7] - 2026-11-01
|
|
66
|
+
|
|
67
|
+
### Fixed
|
|
68
|
+
|
|
69
|
+
- **A revocation that cannot reach its connection no longer answers success.** `disconnect()` on
|
|
70
|
+
`RealtimeService` resolved even when the revocation was never delivered: a failed cross-instance
|
|
71
|
+
publish was logged and swallowed, and in `transport: 'both'` a failure of either transport was
|
|
72
|
+
swallowed with no log at all, so a revoked client could stay connected while the caller was told it
|
|
73
|
+
was gone. It now rejects with `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the revocation and
|
|
74
|
+
with `REALTIME_TRANSPORT_UNAVAILABLE` when the transport that holds the connection fails or the
|
|
75
|
+
WebSocket server is not attached. It resolves when the connection was closed on this instance or the
|
|
76
|
+
revocation was handed to the bus. `joinRoom` and `leaveRoom` reject the same way when the
|
|
77
|
+
transport that holds the connection fails, in place of reporting a join or a leave that did not
|
|
78
|
+
happen, and they now change nothing for a connection the instance does not hold (they used to
|
|
79
|
+
record a room membership with no connection behind it). An emit stays at-most-once and still
|
|
80
|
+
resolves when its publish fails.
|
|
81
|
+
- **A revocation that fails during re-authentication is retried.** The cycle kept the failure to
|
|
82
|
+
itself and stopped revalidating the remaining connections; it now logs it, goes on, and revalidates
|
|
83
|
+
the connection again on the next cycle. A rejected cycle no longer leaves an unhandled rejection.
|
|
84
|
+
- **A failed publish or a failed offline-queue write is no longer silent.** An emit whose publish
|
|
85
|
+
to the other instances was refused still resolves, as before, but the failure is now logged with
|
|
86
|
+
`REALTIME_PUBSUB_UNAVAILABLE` and the operation and passed to the new `onDeliveryFailure` hook,
|
|
87
|
+
which is where to count it. `emitToUser` now waits for the offline queue instead of firing and
|
|
88
|
+
forgetting it, reports a failed write the same way, and rejects with
|
|
89
|
+
`REALTIME_TRANSPORT_UNAVAILABLE` only when the event has no delivery path left: the user is
|
|
90
|
+
offline here, the queue could not keep it, and the bus failed or cannot reach another instance
|
|
91
|
+
(the default in-memory bus). With `transport: 'both'`, a rejection from either path, or from
|
|
92
|
+
both, is logged as a warning and the call resolves; `onDeliveryFailure` is not called for that
|
|
93
|
+
rejection. A failed offline-queue read on reconnect is reported too. A remote `disconnect` that
|
|
94
|
+
fails no longer leaves an unhandled rejection, an unparsable bus payload is counted and reported
|
|
95
|
+
at most once a minute instead of vanishing, and an emit made before the WebSocket gateway attaches
|
|
96
|
+
its server says so once.
|
|
97
|
+
- **An instance that cannot hear the others no longer comes up silently deaf.** When the Redis
|
|
98
|
+
pub/sub subscription at boot was refused (a wrong password, a missing permission) the library logged a warning and started anyway, so the instance missed every
|
|
99
|
+
cross-instance revocation. A refusal now fails the boot with `REALTIME_PUBSUB_UNAVAILABLE`. When
|
|
100
|
+
Redis is merely unreachable the boot used to hang, waiting for a subscribe that ioredis keeps
|
|
101
|
+
queued (measured above 40 s on a closed port); it now completes, logs
|
|
102
|
+
`REALTIME_PUBSUB_UNAVAILABLE` once, and the instance reports itself unready until a connection
|
|
103
|
+
succeeds. The state follows the connection for the life of the process: a drop makes it unready
|
|
104
|
+
again, logged once per outage rather than once per retry, and it is ready only once the SUBSCRIBE
|
|
105
|
+
is confirmed, whether or not the client has `autoResubscribe` on.
|
|
106
|
+
The subscriber client no longer relies on ioredis replaying its subscription after a reconnect:
|
|
107
|
+
that replay had no handler for a refusal, so a re-subscribe the server refused (an ACL changed
|
|
108
|
+
while the instance ran) surfaced as an unhandled rejection that can end the Node process. The
|
|
109
|
+
library now sends its own `SUBSCRIBE` on every reconnect and reports a refusal in the log.
|
|
110
|
+
|
|
111
|
+
#### Apply to a derived backend
|
|
112
|
+
|
|
113
|
+
Await `disconnect()` and handle its rejection where you revoke a connection: a rejection means the
|
|
114
|
+
connection may still be connected, so retry or alert. A caller that ignored the returned promise now
|
|
115
|
+
risks an unhandled rejection. `joinRoom` and `leaveRoom` can reject the same way, and are local to the
|
|
116
|
+
instance that holds the connection. `REALTIME_ERROR_CODES` gains `TRANSPORT_UNAVAILABLE`.
|
|
117
|
+
|
|
118
|
+
With `transport: 'sse'`, `emitToUser` can now reject, with `REALTIME_TRANSPORT_UNAVAILABLE`, when an
|
|
119
|
+
offline queue is configured, the user is offline on this instance, the queue could not keep the event
|
|
120
|
+
and no other instance can have delivered it. Count `onDeliveryFailure` (new, optional, nothing to implement) to see
|
|
121
|
+
the publishes and queue writes that failed without failing the call.
|
|
122
|
+
|
|
123
|
+
A Redis that refuses the pub/sub subscription (a wrong password, a missing permission) now fails
|
|
124
|
+
the application's boot instead of logging and continuing, so a misconfigured credential or ACL
|
|
125
|
+
surfaces at startup. A Redis that is only unreachable no longer hangs the boot: the instance boots
|
|
126
|
+
unready and subscribes when a connection succeeds. Wire `isPubSubReady()` into the readiness probe
|
|
127
|
+
so an instance that is up but cannot hear the others (Redis unreachable, or the subscriber
|
|
128
|
+
connection dropped) is taken out of rotation; see the README. A custom `IRealtimePubSub` needs no
|
|
129
|
+
change: `isSubscribed` is optional, and a bus without it counts as subscribed.
|
|
130
|
+
|
|
131
|
+
### Added
|
|
132
|
+
|
|
133
|
+
- `IConnectionLifecycleHooks.onDeliveryFailure(failure)`, with the exported `DeliveryFailure` type
|
|
134
|
+
(`code`, `op`, `error`), called when a delivery path fails but the call that used it still
|
|
135
|
+
resolves.
|
|
136
|
+
- `RealtimeService.isPubSubReady()`, for a readiness probe: false while the instance does not hear
|
|
137
|
+
the other instances. `RedisRealtimePubSub.isSubscribed()` is the state behind it, and
|
|
138
|
+
`IRealtimePubSub.isSubscribed?()` lets a custom bus report its own.
|
|
139
|
+
|
|
140
|
+
### Internal
|
|
141
|
+
|
|
142
|
+
- The `internal` and `websocket` bundle budgets in `pnpm size` are raised to fit the revocation that
|
|
143
|
+
rejects when it cannot reach its connection, the report of a delivery path that failed and the
|
|
144
|
+
subscriber's lifecycle state, a boot that ends when the server closes the connection without an
|
|
145
|
+
error, and per-connection retirement: the `internal` budget goes from 15,900 B to 18,250 B for a
|
|
146
|
+
measured 18,232 B (15,868 B in 1.2.6) and the `websocket` budget from 7,000 B to 7,550 B for a
|
|
147
|
+
measured 7,477 B.
|
|
148
|
+
- The workflow jobs that check out the repository and then run its scripts no longer keep the job's
|
|
149
|
+
token in the git configuration: `persist-credentials: false` on the checkout wherever no later
|
|
150
|
+
step pushes or tags.
|
|
151
|
+
|
|
10
152
|
## [1.2.6] - 2026-11-01
|
|
11
153
|
|
|
12
154
|
### Fixed
|
|
@@ -679,7 +821,9 @@ First published release.
|
|
|
679
821
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
680
822
|
asked about NestJS and never put the same question to the other ten peers.
|
|
681
823
|
|
|
682
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
824
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...HEAD
|
|
825
|
+
[1.2.8]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...v1.2.8
|
|
826
|
+
[1.2.7]: https://github.com/bymaxone/nest-realtime/compare/v1.2.6...v1.2.7
|
|
683
827
|
[1.2.6]: https://github.com/bymaxone/nest-realtime/compare/v1.2.5...v1.2.6
|
|
684
828
|
[1.2.5]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...v1.2.5
|
|
685
829
|
[1.2.4]: https://github.com/bymaxone/nest-realtime/compare/v1.2.3...v1.2.4
|
package/README.md
CHANGED
|
@@ -350,18 +350,20 @@ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls
|
|
|
350
350
|
|
|
351
351
|
All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
|
|
352
352
|
|
|
353
|
-
| Group | Key Options
|
|
354
|
-
| -------------------------- |
|
|
355
|
-
| **transport** | `'sse'` \| `'websocket'` \| `'both'`
|
|
356
|
-
| **authenticator** | `IConnectionAuthenticator`
|
|
357
|
-
| **tenantResolver** | `(auth) => string \| undefined \| null` — derives `tenantId` from the auth result, on **both** transports; `undefined` and `null` mean "no opinion" and fall back
|
|
358
|
-
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget)
|
|
359
|
-
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE
|
|
360
|
-
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away
|
|
361
|
-
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it
|
|
362
|
-
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent`
|
|
363
|
-
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter`
|
|
364
|
-
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs`
|
|
353
|
+
| Group | Key Options | Default |
|
|
354
|
+
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
|
|
355
|
+
| **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
|
|
356
|
+
| **authenticator** | `IConnectionAuthenticator` | — (**required**) |
|
|
357
|
+
| **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` |
|
|
358
|
+
| **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed`, `onDeliveryFailure` (fire-and-forget) | — |
|
|
359
|
+
| **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
|
|
360
|
+
| **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
|
|
361
|
+
| **presence** | `IPresenceStorage` — contract for your own presence tracking; the library never calls it | — (disabled) |
|
|
362
|
+
| **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent` | `/realtime/sse`, `30000`, `100`, `5`, `true` |
|
|
363
|
+
| **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
|
|
364
|
+
| **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
|
|
365
|
+
|
|
366
|
+
`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`.
|
|
365
367
|
|
|
366
368
|
> [!NOTE]
|
|
367
369
|
> `websocket.maxConnectionsPerUser` is **opt-in** and unlimited unless set to a positive number, while `sse.maxConnectionsPerUser` defaults to `5`. The two transports differ here on purpose: an SSE stream holds an HTTP connection open, a Socket.IO client multiplexes.
|
|
@@ -494,16 +496,16 @@ When integrating `@bymax-one/nest-realtime` in production, verify each of the fo
|
|
|
494
496
|
|
|
495
497
|
## 🛡️ Security Table
|
|
496
498
|
|
|
497
|
-
| Layer | Implementation
|
|
498
|
-
| --------------------- |
|
|
499
|
-
| Credential validation | Delegated entirely to consumer-supplied `IConnectionAuthenticator`
|
|
500
|
-
| Auth library imports | None — enforced by a CI grep over `src/`
|
|
501
|
-
| Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result
|
|
502
|
-
| Connection revocation | `disconnect(connectionId)`, propagated cross-instance via `op: 'disconnect'
|
|
503
|
-
| Credential expiry | Interval re-authentication with `disconnect` or event on failure
|
|
504
|
-
| Connection flooding | FIFO eviction per user — oldest closed, new admitted, never a 429
|
|
505
|
-
| SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` by default
|
|
506
|
-
| WebSocket origin | Explicit `cors` config passed straight to Socket.IO
|
|
499
|
+
| Layer | Implementation |
|
|
500
|
+
| --------------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
|
501
|
+
| Credential validation | Delegated entirely to consumer-supplied `IConnectionAuthenticator` |
|
|
502
|
+
| Auth library imports | None — enforced by a CI grep over `src/` |
|
|
503
|
+
| Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
|
|
504
|
+
| Connection revocation | `disconnect(connectionId)`, propagated cross-instance via `op: 'disconnect'`; rejects when it cannot reach the connection |
|
|
505
|
+
| Credential expiry | Interval re-authentication with `disconnect` or event on failure |
|
|
506
|
+
| Connection flooding | FIFO eviction per user — oldest closed, new admitted, never a 429 |
|
|
507
|
+
| SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` by default |
|
|
508
|
+
| WebSocket origin | Explicit `cors` config passed straight to Socket.IO |
|
|
507
509
|
|
|
508
510
|
> [!IMPORTANT]
|
|
509
511
|
> This package holds **zero credential logic**. That is its central security property — and it means the strength of your realtime auth is exactly the strength of the authenticator you plug in.
|
|
@@ -572,6 +574,35 @@ The unified emit API. Identical on every transport.
|
|
|
572
574
|
|
|
573
575
|
All methods return `Promise<void>`.
|
|
574
576
|
|
|
577
|
+
**Revocation is never best-effort.** `disconnect(connectionId)` resolves when the connection was closed on this instance or when the revocation was handed to the bus (`IRealtimePubSub`). It **rejects** when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses it at once while its client is reconnecting, and does not wait for the connection to return), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. A rejection means the connection may still be connected, so retry. An emit is different: `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` stay at-most-once, and **resolve even when the publish to the other instances failed**. That failure is not silent: it is logged with `REALTIME_PUBSUB_UNAVAILABLE` and the operation, and passed to the `onDeliveryFailure` hook, which is where to count it. `emitToUser` also resolves, reporting it the same way, when the offline queue could not keep an event for a user who is offline here, because another instance may have delivered it live. It rejects only when the event has no delivery path left: the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus).
|
|
578
|
+
|
|
579
|
+
`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.
|
|
580
|
+
|
|
581
|
+
**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, and again whenever the subscriber connection drops, `isPubSubReady()` is false. Put it in your readiness probe:
|
|
582
|
+
|
|
583
|
+
```ts
|
|
584
|
+
import { Injectable } from '@nestjs/common'
|
|
585
|
+
import { HealthIndicatorService } from '@nestjs/terminus'
|
|
586
|
+
import { RealtimeService } from '@bymax-one/nest-realtime'
|
|
587
|
+
|
|
588
|
+
@Injectable()
|
|
589
|
+
export class RealtimeHealthIndicator {
|
|
590
|
+
constructor(
|
|
591
|
+
private readonly realtime: RealtimeService,
|
|
592
|
+
private readonly indicators: HealthIndicatorService,
|
|
593
|
+
) {}
|
|
594
|
+
|
|
595
|
+
check(key = 'realtime') {
|
|
596
|
+
const indicator = this.indicators.check(key)
|
|
597
|
+
return this.realtime.isPubSubReady()
|
|
598
|
+
? indicator.up()
|
|
599
|
+
: indicator.down({ reason: 'not subscribed to the realtime bus' })
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
```
|
|
603
|
+
|
|
604
|
+
`isPubSubReady()` is true for a bus that reports no state, such as the default in-memory one, and with `transport: 'websocket'`, which does not use the bus.
|
|
605
|
+
|
|
575
606
|
### ConnectionRegistry
|
|
576
607
|
|
|
577
608
|
Read-side view of live connections — useful for admin endpoints and metrics. The class also has `register` and `unregister`; those are the transports' own bookkeeping, so do not call them (a record you add has no stream or socket behind it).
|
|
@@ -586,14 +617,14 @@ Read-side view of live connections — useful for admin endpoints and metrics. T
|
|
|
586
617
|
|
|
587
618
|
### Contracts
|
|
588
619
|
|
|
589
|
-
| Interface | Required | Purpose
|
|
590
|
-
| --------------------------- | :------: |
|
|
591
|
-
| `IConnectionAuthenticator` | ✅ | Validate a connection, return `userId` / `tenantId`
|
|
592
|
-
| `IRealtimePubSub` | — | Cross-instance fan-out for SSE
|
|
593
|
-
| `IOfflineQueueStorage` | — | Hold events for disconnected users
|
|
620
|
+
| Interface | Required | Purpose |
|
|
621
|
+
| --------------------------- | :------: | --------------------------------------------------------------------------------------------------------------------- |
|
|
622
|
+
| `IConnectionAuthenticator` | ✅ | Validate a connection, return `userId` / `tenantId` |
|
|
623
|
+
| `IRealtimePubSub` | — | Cross-instance fan-out for SSE |
|
|
624
|
+
| `IOfflineQueueStorage` | — | Hold events for disconnected users |
|
|
594
625
|
| `IPresenceStorage` | — | Contract only: the library never calls it; your code stores presence and emits `presence:online` / `presence:offline` |
|
|
595
|
-
| `IConnectionLifecycleHooks` | — | Fire-and-forget connect / disconnect / error callbacks
|
|
596
|
-
| `ITransport` | — | Implemented by the library; the seam every transport shares
|
|
626
|
+
| `IConnectionLifecycleHooks` | — | Fire-and-forget connect / disconnect / error callbacks |
|
|
627
|
+
| `ITransport` | — | Implemented by the library; the seam every transport shares |
|
|
597
628
|
|
|
598
629
|
Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
|
|
599
630
|
|
|
@@ -615,7 +646,7 @@ under none and joins no tenant room, which an empty string is not. Whitespace co
|
|
|
615
646
|
Omission is the form to write, because it is the only one that compiles everywhere.
|
|
616
647
|
`AuthenticationResult` declares `tenantId?: string`; the runtime accepts an explicit `undefined`
|
|
617
648
|
or `null` too — an untyped claim spread into the result produces them routinely — but whether
|
|
618
|
-
either
|
|
649
|
+
either _type-checks_ depends on the consuming project's `tsconfig`, which the published
|
|
619
650
|
declarations do not control:
|
|
620
651
|
|
|
621
652
|
| consumer's `tsconfig` | `tenantId: undefined` | `tenantId: null` |
|
|
@@ -628,7 +659,7 @@ Omitting the key is correct in all three.
|
|
|
628
659
|
|
|
629
660
|
`tenantResolver` cannot clear a tenant, and this is the one asymmetry worth reading twice.
|
|
630
661
|
Resolution is `tenantResolver?.(auth) ?? auth.tenantId`, so a resolver returning `undefined` or
|
|
631
|
-
`null` means
|
|
662
|
+
`null` means _no opinion_ and falls back to the tenant the authenticator supplied. A resolver
|
|
632
663
|
written to place a connection in no tenant by returning `null` leaves it in `auth.tenantId`'s
|
|
633
664
|
room instead, still receiving that tenant's events. Decide the absent case in the
|
|
634
665
|
authenticator, where absence is what it looks like.
|
|
@@ -676,10 +707,10 @@ that is not an address is never returned, and `ip` is `''` when no channel carri
|
|
|
676
707
|
Without `trust proxy` it is the peer. Only `remoteAddress` can be trusted without knowing that
|
|
677
708
|
setting:
|
|
678
709
|
|
|
679
|
-
| Field | SSE | WebSocket | Forgeable by the client
|
|
680
|
-
| --------------- | ----------------------------------------------------- | ------------------- |
|
|
681
|
-
| `ip` | `req.ip`, which follows the app's `trust proxy` value | `handshake.address` | Only as far as `trust proxy` believes the header
|
|
682
|
-
| `remoteAddress` | `req.socket.remoteAddress` | `handshake.address` | No
|
|
710
|
+
| Field | SSE | WebSocket | Forgeable by the client |
|
|
711
|
+
| --------------- | ----------------------------------------------------- | ------------------- | ------------------------------------------------ |
|
|
712
|
+
| `ip` | `req.ip`, which follows the app's `trust proxy` value | `handshake.address` | Only as far as `trust proxy` believes the header |
|
|
713
|
+
| `remoteAddress` | `req.socket.remoteAddress` | `handshake.address` | No |
|
|
683
714
|
|
|
684
715
|
`remoteAddress` is the TCP peer, read from the socket and never from a header. Behind a reverse
|
|
685
716
|
proxy it is the proxy's address. Use it to decide whether a forwarded header such as
|
|
@@ -840,18 +871,19 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
840
871
|
|
|
841
872
|
### Error Codes
|
|
842
873
|
|
|
843
|
-
| Code | Status
|
|
844
|
-
| ---------------------------------- |
|
|
845
|
-
| `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option
|
|
846
|
-
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid
|
|
847
|
-
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal
|
|
848
|
-
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails
|
|
849
|
-
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed
|
|
850
|
-
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write
|
|
851
|
-
| `REALTIME_PUBSUB_UNAVAILABLE` |
|
|
852
|
-
| `
|
|
853
|
-
| `
|
|
854
|
-
| `
|
|
874
|
+
| Code | Status |
|
|
875
|
+
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
876
|
+
| `REALTIME_INVALID_OPTIONS` | Raised at bootstrap for an invalid option |
|
|
877
|
+
| `REALTIME_NO_AUTHENTICATOR` | Raised at bootstrap when the authenticator is missing or invalid |
|
|
878
|
+
| `REALTIME_AUTH_FAILED` | Raised when authentication is refused: the SSE 401 body and the WebSocket handshake refusal |
|
|
879
|
+
| `REALTIME_REAUTHENTICATION_FAILED` | Raised when a revalidation fails |
|
|
880
|
+
| `REALTIME_TOO_MANY_CONNECTIONS` | Raised as the reason an evicted connection is closed |
|
|
881
|
+
| `REALTIME_INVALID_TICKET` | Reserved, never raised today: a ticket store is yours to write |
|
|
882
|
+
| `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 |
|
|
883
|
+
| `REALTIME_TRANSPORT_UNAVAILABLE` | Raised as the rejection of a disconnect, a join or a leave when the transport that holds the connection fails or has no server attached, and of an emit to an offline user that has no delivery path left |
|
|
884
|
+
| `REALTIME_REDIS_ADAPTER_FAILED` | Raised at bootstrap when the Redis adapter is configured and cannot be installed |
|
|
885
|
+
| `REALTIME_PAYLOAD_TOO_LARGE` | Reserved, never raised today |
|
|
886
|
+
| `REALTIME_REPLAY_BUFFER_MISS` | Reserved, never raised today |
|
|
855
887
|
|
|
856
888
|
### DI Tokens
|
|
857
889
|
|
|
@@ -859,11 +891,11 @@ These names belong to the library. Do not reuse them for application events. The
|
|
|
859
891
|
|
|
860
892
|
### React Hooks
|
|
861
893
|
|
|
862
|
-
| Hook | Returns
|
|
863
|
-
| -------------------------------- |
|
|
864
|
-
| `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection
|
|
865
|
-
| `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one
|
|
866
|
-
| `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array
|
|
894
|
+
| Hook | Returns |
|
|
895
|
+
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
896
|
+
| `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection |
|
|
897
|
+
| `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one |
|
|
898
|
+
| `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array |
|
|
867
899
|
| `usePresence()` | `UsePresenceReturn`: `{ onlineUserIds, isOnline(userId), count }` — reads `presence:*` events from the provider; your server must emit them |
|
|
868
900
|
|
|
869
901
|
`RealtimeProvider` takes a single `options` prop of type `UseRealtimeOptions`:
|