@bymax-one/nest-realtime 1.2.7 → 1.2.9

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 CHANGED
@@ -7,6 +7,153 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.9] - 2026-11-06
11
+
12
+ ### Changed
13
+
14
+ - **With `transport: 'both'`, an emit that fails on both transports now rejects.** `emitToUser`,
15
+ `emitToTenant`, `emitToRoom` and `broadcast` on the composite transport run on SSE and WebSocket
16
+ and logged a failure of either without ever rethrowing, so an emit that failed on both still
17
+ resolved. A failure of one transport is still logged and resolves; a failure of both now rejects
18
+ with `REALTIME_TRANSPORT_UNAVAILABLE` (`error.code`), naming the operation and carrying both
19
+ reasons in `cause`, the way `joinRoom`, `leaveRoom` and `disconnect` already do. A rejected emit
20
+ is not proof that no client received it, so retry only where a duplicate is acceptable.
21
+
22
+ ### Added
23
+
24
+ - **Errors carry their code as a `code` property.** The `Error`s this library builds with a
25
+ `REALTIME_*` code in their message now also have that code as `error.code`, one of
26
+ `RealtimeErrorCode`. The messages are unchanged. They are plain `Error`s, so match on
27
+ `error.code`, not `instanceof`. The HTTP `UnauthorizedException` for a refused SSE connection and
28
+ the Socket.IO refusal of a WebSocket connection keep their shape; the refusal carries its code as
29
+ `data.code`.
30
+
31
+ ### Fixed
32
+
33
+ - **A refusal of the subscription is logged once.** After a start-up that found Redis unreachable,
34
+ the same refusal can answer two `SUBSCRIBE`s when the connection comes up: the one queued while
35
+ Redis was unreachable, which ioredis sends when the connection first becomes ready, and the one
36
+ the adapter sends on `ready`. The adapter logged `the server refused the subscription` once for
37
+ each, so a refusing server produced two identical warnings. It now logs a refusal once until the
38
+ instance next subscribes, and again if the reason changes. The wire may still carry two
39
+ `SUBSCRIBE`s at that first `ready`; a repeat is harmless.
40
+ - **Closing the application no longer hangs while an SSE stream is open.** Nest awaits the HTTP
41
+ server's close before it runs `onApplicationShutdown`, and the server does not finish closing
42
+ while a response is open, but the streams were ended only in that hook. One open stream therefore
43
+ kept `app.close()` pending, so a `SIGTERM` was ignored until the orchestrator's `SIGKILL` and
44
+ every `onApplicationShutdown` hook was skipped, a tracing flush included. `SseTransport` now ends
45
+ its streams and stops its heartbeats in `beforeApplicationShutdown`, which runs before the server
46
+ closes, and its `onApplicationShutdown` stays and runs the same teardown, which finds nothing
47
+ left. A stream requested once shutdown has begun is refused with a `503`, since nothing would end
48
+ it, and one that was past the handshake when shutdown began is ended as soon as it is opened. `ITransport` gains the optional `beforeApplicationShutdown` hook. An open WebSocket
49
+ connection, including one opened while shutdown is under way, did not hang the close.
50
+ - **A failed re-authentication now disconnects the connection without waiting for its
51
+ notification.** With `reauthenticationPolicy.onFailure: 'event'` the service emitted
52
+ `connection:reauthentication-failed` and waited for it before disconnecting, so an emit that
53
+ rejected left the connection open until the next cycle, and one that never settled left it open
54
+ for good. The emit is now started first and not awaited: a rejection is logged
55
+ (`Reauthentication notification for <id> failed, disconnecting anyway`) and the connection is
56
+ disconnected in the same cycle. A rejected disconnect is still a failed revocation and is retried
57
+ on the next cycle.
58
+
59
+ - **A publish no longer waits behind a Redis client that is not ready, and readiness now says
60
+ whether the instance can publish.** `RedisRealtimePubSub.publish` refused a client that was
61
+ reconnecting or closed, but still handed the command to ioredis in `wait`, `connecting` and
62
+ `connect`. A client whose server accepts the connection and does not answer the handshake kept
63
+ the command pending. It now rejects with `REALTIME_PUBSUB_UNAVAILABLE` at once
64
+ unless the client can publish, and never hands the command to ioredis otherwise. A client built
65
+ with `lazyConnect` was left in `wait`, so `isPubSubReady()` reported true and the first emit was
66
+ lost; the adapter now connects it when it subscribes, and a publish made before any subscribe
67
+ connects it too (that publish is refused). `isPubSubReady()` is true
68
+ only while the subscription is confirmed and the publishing client can publish. Subscribing waits
69
+ up to 2 seconds for the publishing client to answer its first connection, so an emit from another
70
+ provider's start-up hook is not refused for the client's first milliseconds; a client that
71
+ answers nothing in that time is left unready and the application still starts.
72
+
73
+ #### Apply to a derived backend
74
+
75
+ Nothing needs to change for the shutdown fix: an application that closes with an SSE stream open
76
+ now finishes closing and runs its `onApplicationShutdown` hooks. A client that requests the SSE
77
+ route while the application is closing now gets a `503`. If you set `forceCloseConnections`
78
+ only to get past this hang, it is no longer needed for SSE streams.
79
+
80
+ If you set `reauthenticationPolicy.onFailure: 'event'`, nothing needs to change: a connection whose
81
+ credentials failed is now disconnected in the same cycle whether or not the notification can be
82
+ sent, where it used to stay open until the next cycle. The failure to send is logged as a warning.
83
+
84
+ If you use `transport: 'both'`, an emit that fails on both transports now rejects instead of
85
+ resolving. An emit you await inside a `try` is now caught; one you call without awaiting or without
86
+ a `.catch` becomes an unhandled rejection when both transports fail, so add the `.catch` or await
87
+ it. A failure of only one transport still resolves, as before.
88
+
89
+ Nothing needs to change for the `code` property: it is added to errors you already catch, and
90
+ their messages are the same. Where you match on the message text to tell a bus failure from a
91
+ transport failure, `error.code` is the stable way to do it.
92
+
93
+ If you pass `RedisRealtimePubSub` a client built with `lazyConnect: true`, the adapter now
94
+ connects it when it subscribes; connect it yourself only if you need it before then. An
95
+ emit made while the publishing client is `wait`, `connecting` or `connect` is now refused at once,
96
+ like one made while it reconnects, and a `disconnect()` of a connection held on another instance rejects with
97
+ `REALTIME_PUBSUB_UNAVAILABLE`. `isPubSubReady()` also turns false while the publishing
98
+ client cannot publish, so a readiness probe that took the instance out of rotation only on a lost
99
+ subscription now takes it out for a lost publisher as well. A client that reports no status, such
100
+ as the ioredis-mock double, is taken to be able to publish.
101
+
102
+ ## [1.2.8] - 2026-11-06
103
+
104
+ ### Changed
105
+
106
+ - **Built with tsup 9; the shipped bundles no longer carry comments.** The build now strips the
107
+ comments from `dist/**/index.mjs` and `dist/**/index.cjs` after bundling, keeping legal comments,
108
+ `__PURE__` annotations and region markers, and checks that the program is unchanged. The
109
+ declarations keep their comments. The public surface is the same. The `internal` bundle is
110
+ 12,293 B brotli, inside its 13,500 B budget; the other budgets were reset to the stripped size
111
+ plus about 11%.
112
+
113
+ ### Fixed
114
+
115
+ - **A host Redis client built with `enableOfflineQueue: false` no longer fails the boot of `RedisRealtimePubSub`.**
116
+ The subscriber connection is a copy of the host client and inherited that option, so its first
117
+ `SUBSCRIBE`, issued before the connection exists, was refused by ioredis at once with
118
+ `Stream isn't writeable and enableOfflineQueue options is false`. Since 1.2.7 that rejection was
119
+ treated as the server refusing the subscription and failed the boot with
120
+ `REALTIME_PUBSUB_UNAVAILABLE`, while Redis was healthy; before 1.2.7 the same combination logged a
121
+ warning and left the instance without cross-instance delivery. The subscriber connection now keeps its own offline queue on, and only an error
122
+ reply from the server counts as a refusal: any other rejection of the first `SUBSCRIBE` is the
123
+ connection failing, so the boot completes unready and recovers like any outage.
124
+ - **`disconnect()` no longer hangs through a Redis outage.** `RedisRealtimePubSub.publish` handed
125
+ the command to ioredis even while the client was reconnecting, and ioredis queued it until the
126
+ connection returned (still pending after 30 s with its default options), so a revocation, and
127
+ every emit, waited out the whole outage and was then sent late. It now rejects at once with
128
+ `REALTIME_PUBSUB_UNAVAILABLE` (`cannot publish to "<channel>" (the Redis client is reconnecting)`)
129
+ while the client is reconnecting, closed or ended, and never queues the command. `disconnect()`
130
+ rejects with that code so the caller can retry, and an emit no longer waits for the outage.
131
+ - **An `sse.heartbeatMs` outside the allowed range now stops the application at start-up.** The
132
+ boot check only rejected a value of zero or less, while the heartbeat service refuses anything
133
+ outside 5,000 to 90,000 ms each time a connection opens. A value such as `1000` or `100000`
134
+ therefore started the application and then answered every SSE connection with a 500.
135
+ `NaN`, which comes from `Number(process.env.HEARTBEAT_MS)` when the variable is unset, passed
136
+ both checks and made the keepalive timer fire about every millisecond on every connection.
137
+ `validateOptions` now applies the same range, for `forRoot` and `forRootAsync`, and the error
138
+ names it: `options.sse.heartbeatMs must be between 5000 and 90000 ms (got 1000)`.
139
+
140
+ #### Apply to a derived backend
141
+
142
+ A `disconnect()` made during a Redis outage now rejects immediately instead of waiting for the
143
+ reconnect, so the retry you already need for a rejected `disconnect()` happens sooner. An emit made
144
+ during an outage is no longer held and delivered late.
145
+
146
+ If your configuration sets `sse.heartbeatMs`, check it is between 5,000 and 90,000 ms. A value
147
+ outside it already failed every connection, except `NaN`, which flooded each connection with
148
+ keepalives; now every one of them fails when the application starts.
149
+
150
+ If you pass `RedisRealtimePubSub` a client created with `enableOfflineQueue: false`,
151
+ upgrade to this release. 1.2.7 fails the boot with `REALTIME_PUBSUB_UNAVAILABLE`
152
+ on such a client. Earlier versions did not fail: they logged `Failed to subscribe to pub/sub ...
153
+ Cross-instance fan-out disabled` once at start-up and then ran without cross-instance delivery, so
154
+ if you ran one of them with such a client, revocations and emits from your other instances may
155
+ never have reached it. Nothing needs to change in your configuration.
156
+
10
157
  ## [1.2.7] - 2026-11-01
11
158
 
12
159
  ### Fixed
@@ -766,7 +913,9 @@ First published release.
766
913
  rather than by the manual sweep that raised the NestJS floors — that sweep
767
914
  asked about NestJS and never put the same question to the other ten peers.
768
915
 
769
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...HEAD
916
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...HEAD
917
+ [1.2.9]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...v1.2.9
918
+ [1.2.8]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...v1.2.8
770
919
  [1.2.7]: https://github.com/bymaxone/nest-realtime/compare/v1.2.6...v1.2.7
771
920
  [1.2.6]: https://github.com/bymaxone/nest-realtime/compare/v1.2.5...v1.2.6
772
921
  [1.2.5]: https://github.com/bymaxone/nest-realtime/compare/v1.2.4...v1.2.5
package/README.md CHANGED
@@ -363,6 +363,8 @@ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `
363
363
  | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
364
364
  | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
365
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`.
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.
368
370
 
@@ -477,7 +479,7 @@ A complete `@bymax-one/nest-auth` bridge is in [docs/examples/nest-auth-bridge.m
477
479
 
478
480
  ### Re-Authentication
479
481
 
480
- Long-lived connections outlive short-lived tokens. `reauthenticationPolicy` revalidates on an interval and either drops the connection or emits `connection:reauthentication-failed`, depending on `onFailure`. Successful checks are cached for `cacheTtlMs` so a busy connection is not revalidated on every event.
482
+ Long-lived connections outlive short-lived tokens. `reauthenticationPolicy` revalidates on an interval and either drops the connection or emits `connection:reauthentication-failed` and then drops it, depending on `onFailure`. The connection is dropped even when that event cannot be sent: the event is a notification, and the failure to send it is logged. Successful checks are cached for `cacheTtlMs` so a busy connection is not revalidated on every event.
481
483
 
482
484
  ### Security Checklist
483
485
 
@@ -572,11 +574,11 @@ The unified emit API. Identical on every transport.
572
574
 
573
575
  All methods return `Promise<void>`.
574
576
 
575
- **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, `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).
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 Redis client is anything but ready, and does not wait for the connection to return), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. The error carries that code as `error.code` (a `RealtimeErrorCode`), so branch on the property and not on the message text; it is a plain `Error`, not a class to test with `instanceof`. 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). With `transport: 'both'`, an emit that fails on one transport is logged and resolves; one that fails on both rejects with `REALTIME_TRANSPORT_UNAVAILABLE`. A rejected emit is not proof that no client received it, so retry only where a duplicate is acceptable.
576
578
 
577
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.
578
580
 
579
- **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:
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, 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:
580
582
 
581
583
  ```ts
582
584
  import { Injectable } from '@nestjs/common'