@bymax-one/nest-realtime 1.2.8 → 1.2.10

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,122 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.10] - 2026-11-09
11
+
12
+ ### Fixed
13
+
14
+ - **A WebSocket handshake that arrives while the application is closing is refused.** The handshake
15
+ middleware authenticated every handshake and accepted it, however late it came, so a handshake
16
+ that arrived once shutdown had begun reached an authenticator whose store the host may already
17
+ have closed, and was accepted into a server that was about to close. From
18
+ `beforeApplicationShutdown` on, the middleware refuses it with a `connect_error` whose
19
+ `data.code` is `REALTIME_TRANSPORT_UNAVAILABLE`, before the authenticator runs and again if
20
+ shutdown began while the authenticator was running; this is the refusal SSE gives with a 503.
21
+ The code differs from `REALTIME_AUTH_FAILED`, which the same middleware uses for a refused
22
+ credential, so a client can tell the two apart.
23
+
24
+ #### Apply to a derived backend
25
+
26
+ `WebSocketTransport` gains a public `beforeApplicationShutdown()` hook and a `shuttingDown` getter,
27
+ and `RealtimeGateway` gains a private `unavailable` method. A class that extends either and already
28
+ declares a member with one of those names has to rename it or override it on purpose. A subclass
29
+ of `WebSocketTransport` that overrides `beforeApplicationShutdown` has to call
30
+ `super.beforeApplicationShutdown()`, or the gateway keeps accepting handshakes while the
31
+ application closes. A gateway that replaces `RealtimeGateway`'s handshake middleware gets no
32
+ refusal from this change; it can read `transport.shuttingDown` itself.
33
+
34
+ ## [1.2.9] - 2026-11-06
35
+
36
+ ### Changed
37
+
38
+ - **With `transport: 'both'`, an emit that fails on both transports now rejects.** `emitToUser`,
39
+ `emitToTenant`, `emitToRoom` and `broadcast` on the composite transport run on SSE and WebSocket
40
+ and logged a failure of either without ever rethrowing, so an emit that failed on both still
41
+ resolved. A failure of one transport is still logged and resolves; a failure of both now rejects
42
+ with `REALTIME_TRANSPORT_UNAVAILABLE` (`error.code`), naming the operation and carrying both
43
+ reasons in `cause`, the way `joinRoom`, `leaveRoom` and `disconnect` already do. A rejected emit
44
+ is not proof that no client received it, so retry only where a duplicate is acceptable.
45
+
46
+ ### Added
47
+
48
+ - **Errors carry their code as a `code` property.** The `Error`s this library builds with a
49
+ `REALTIME_*` code in their message now also have that code as `error.code`, one of
50
+ `RealtimeErrorCode`. The messages are unchanged. They are plain `Error`s, so match on
51
+ `error.code`, not `instanceof`. The HTTP `UnauthorizedException` for a refused SSE connection and
52
+ the Socket.IO refusal of a WebSocket connection keep their shape; the refusal carries its code as
53
+ `data.code`.
54
+
55
+ ### Fixed
56
+
57
+ - **A refusal of the subscription is logged once.** After a start-up that found Redis unreachable,
58
+ the same refusal can answer two `SUBSCRIBE`s when the connection comes up: the one queued while
59
+ Redis was unreachable, which ioredis sends when the connection first becomes ready, and the one
60
+ the adapter sends on `ready`. The adapter logged `the server refused the subscription` once for
61
+ each, so a refusing server produced two identical warnings. It now logs a refusal once until the
62
+ instance next subscribes, and again if the reason changes. The wire may still carry two
63
+ `SUBSCRIBE`s at that first `ready`; a repeat is harmless.
64
+ - **Closing the application no longer hangs while an SSE stream is open.** Nest awaits the HTTP
65
+ server's close before it runs `onApplicationShutdown`, and the server does not finish closing
66
+ while a response is open, but the streams were ended only in that hook. One open stream therefore
67
+ kept `app.close()` pending, so a `SIGTERM` was ignored until the orchestrator's `SIGKILL` and
68
+ every `onApplicationShutdown` hook was skipped, a tracing flush included. `SseTransport` now ends
69
+ its streams and stops its heartbeats in `beforeApplicationShutdown`, which runs before the server
70
+ closes, and its `onApplicationShutdown` stays and runs the same teardown, which finds nothing
71
+ left. A stream requested once shutdown has begun is refused with a `503`, since nothing would end
72
+ 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
73
+ connection, including one opened while shutdown is under way, did not hang the close.
74
+ - **A failed re-authentication now disconnects the connection without waiting for its
75
+ notification.** With `reauthenticationPolicy.onFailure: 'event'` the service emitted
76
+ `connection:reauthentication-failed` and waited for it before disconnecting, so an emit that
77
+ rejected left the connection open until the next cycle, and one that never settled left it open
78
+ for good. The emit is now started first and not awaited: a rejection is logged
79
+ (`Reauthentication notification for <id> failed, disconnecting anyway`) and the connection is
80
+ disconnected in the same cycle. A rejected disconnect is still a failed revocation and is retried
81
+ on the next cycle.
82
+
83
+ - **A publish no longer waits behind a Redis client that is not ready, and readiness now says
84
+ whether the instance can publish.** `RedisRealtimePubSub.publish` refused a client that was
85
+ reconnecting or closed, but still handed the command to ioredis in `wait`, `connecting` and
86
+ `connect`. A client whose server accepts the connection and does not answer the handshake kept
87
+ the command pending. It now rejects with `REALTIME_PUBSUB_UNAVAILABLE` at once
88
+ unless the client can publish, and never hands the command to ioredis otherwise. A client built
89
+ with `lazyConnect` was left in `wait`, so `isPubSubReady()` reported true and the first emit was
90
+ lost; the adapter now connects it when it subscribes, and a publish made before any subscribe
91
+ connects it too (that publish is refused). `isPubSubReady()` is true
92
+ only while the subscription is confirmed and the publishing client can publish. Subscribing waits
93
+ up to 2 seconds for the publishing client to answer its first connection, so an emit from another
94
+ provider's start-up hook is not refused for the client's first milliseconds; a client that
95
+ answers nothing in that time is left unready and the application still starts.
96
+
97
+ #### Apply to a derived backend
98
+
99
+ Nothing needs to change for the shutdown fix: an application that closes with an SSE stream open
100
+ now finishes closing and runs its `onApplicationShutdown` hooks. A client that requests the SSE
101
+ route while the application is closing now gets a `503`. If you set `forceCloseConnections`
102
+ only to get past this hang, it is no longer needed for SSE streams.
103
+
104
+ If you set `reauthenticationPolicy.onFailure: 'event'`, nothing needs to change: a connection whose
105
+ credentials failed is now disconnected in the same cycle whether or not the notification can be
106
+ sent, where it used to stay open until the next cycle. The failure to send is logged as a warning.
107
+
108
+ If you use `transport: 'both'`, an emit that fails on both transports now rejects instead of
109
+ resolving. An emit you await inside a `try` is now caught; one you call without awaiting or without
110
+ a `.catch` becomes an unhandled rejection when both transports fail, so add the `.catch` or await
111
+ it. A failure of only one transport still resolves, as before.
112
+
113
+ Nothing needs to change for the `code` property: it is added to errors you already catch, and
114
+ their messages are the same. Where you match on the message text to tell a bus failure from a
115
+ transport failure, `error.code` is the stable way to do it.
116
+
117
+ If you pass `RedisRealtimePubSub` a client built with `lazyConnect: true`, the adapter now
118
+ connects it when it subscribes; connect it yourself only if you need it before then. An
119
+ emit made while the publishing client is `wait`, `connecting` or `connect` is now refused at once,
120
+ like one made while it reconnects, and a `disconnect()` of a connection held on another instance rejects with
121
+ `REALTIME_PUBSUB_UNAVAILABLE`. `isPubSubReady()` also turns false while the publishing
122
+ client cannot publish, so a readiness probe that took the instance out of rotation only on a lost
123
+ subscription now takes it out for a lost publisher as well. A client that reports no status, such
124
+ as the ioredis-mock double, is taken to be able to publish.
125
+
10
126
  ## [1.2.8] - 2026-11-06
11
127
 
12
128
  ### Changed
@@ -821,7 +937,9 @@ First published release.
821
937
  rather than by the manual sweep that raised the NestJS floors — that sweep
822
938
  asked about NestJS and never put the same question to the other ten peers.
823
939
 
824
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...HEAD
940
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.10...HEAD
941
+ [1.2.10]: https://github.com/bymaxone/nest-realtime/compare/v1.2.9...v1.2.10
942
+ [1.2.9]: https://github.com/bymaxone/nest-realtime/compare/v1.2.8...v1.2.9
825
943
  [1.2.8]: https://github.com/bymaxone/nest-realtime/compare/v1.2.7...v1.2.8
826
944
  [1.2.7]: https://github.com/bymaxone/nest-realtime/compare/v1.2.6...v1.2.7
827
945
  [1.2.6]: https://github.com/bymaxone/nest-realtime/compare/v1.2.5...v1.2.6
package/README.md CHANGED
@@ -479,7 +479,7 @@ A complete `@bymax-one/nest-auth` bridge is in [docs/examples/nest-auth-bridge.m
479
479
 
480
480
  ### Re-Authentication
481
481
 
482
- 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.
483
483
 
484
484
  ### Security Checklist
485
485
 
@@ -574,11 +574,11 @@ The unified emit API. Identical on every transport.
574
574
 
575
575
  All methods return `Promise<void>`.
576
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).
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.
578
578
 
579
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
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:
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:
582
582
 
583
583
  ```ts
584
584
  import { Injectable } from '@nestjs/common'
@@ -871,19 +871,19 @@ These names belong to the library. Do not reuse them for application events. The
871
871
 
872
872
  ### Error Codes
873
873
 
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 |
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. Also what a new SSE stream or WebSocket handshake is refused with once shutdown has begun: a 503 whose message is the code, and a connect_error whose data.code is the code |
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 |
887
887
 
888
888
  ### DI Tokens
889
889
 
@@ -8,6 +8,9 @@ var net = require('net');
8
8
 
9
9
  var __defProp = Object.defineProperty;
10
10
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __typeError = (msg) => {
12
+ throw TypeError(msg);
13
+ };
11
14
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
15
  var __decorateClass = (decorators, target, key, kind) => {
13
16
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
@@ -18,7 +21,11 @@ var __decorateClass = (decorators, target, key, kind) => {
18
21
  return result;
19
22
  };
20
23
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
21
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
24
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
25
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
26
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
27
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
28
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
22
29
 
23
30
  // src/shared/constants/error-codes.constants.ts
24
31
  var REALTIME_ERROR_CODES = {
@@ -63,22 +70,36 @@ var DEFAULT_HEARTBEAT_MS = 3e4;
63
70
  var HEARTBEAT_MIN_MS = 5e3;
64
71
  var HEARTBEAT_MAX_MS = 9e4;
65
72
 
73
+ // src/server/utils/realtime-error.ts
74
+ function realtimeError(code, detail, options = {}) {
75
+ const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
76
+ const message = `${lead}: ${detail}`;
77
+ const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
78
+ return Object.assign(error, { code });
79
+ }
80
+
66
81
  // src/server/config/validate-options.ts
67
82
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
68
83
  function validateOptions(options) {
69
84
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
70
- throw new Error(
71
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`
85
+ throw realtimeError(
86
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
87
+ `options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`,
88
+ { who: "BymaxRealtimeModule" }
72
89
  );
73
90
  }
74
91
  if (!options.authenticator) {
75
- throw new Error(
76
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator is required \u2014 the library never ships a default authenticator`
92
+ throw realtimeError(
93
+ REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
94
+ `options.authenticator is required \u2014 the library never ships a default authenticator`,
95
+ { who: "BymaxRealtimeModule" }
77
96
  );
78
97
  }
79
98
  if (typeof options.authenticator.authenticate !== "function") {
80
- throw new Error(
81
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator must implement IConnectionAuthenticator.authenticate(context)`
99
+ throw realtimeError(
100
+ REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
101
+ `options.authenticator must implement IConnectionAuthenticator.authenticate(context)`,
102
+ { who: "BymaxRealtimeModule" }
82
103
  );
83
104
  }
84
105
  validateSseOptions(options);
@@ -97,18 +118,24 @@ function validateSseOptions(options) {
97
118
  const sse = options.sse;
98
119
  const heartbeatMs = sse?.heartbeatMs;
99
120
  if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
100
- throw new Error(
101
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`
121
+ throw realtimeError(
122
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
123
+ `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`,
124
+ { who: "BymaxRealtimeModule" }
102
125
  );
103
126
  }
104
127
  if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
105
- throw new Error(
106
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.replayBufferSize must be >= 0`
128
+ throw realtimeError(
129
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
130
+ `options.sse.replayBufferSize must be >= 0`,
131
+ { who: "BymaxRealtimeModule" }
107
132
  );
108
133
  }
109
134
  if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
110
- throw new Error(
111
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`
135
+ throw realtimeError(
136
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
137
+ `options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
138
+ { who: "BymaxRealtimeModule" }
112
139
  );
113
140
  }
114
141
  }
@@ -212,13 +239,15 @@ function resolveAuthTenant(options, auth) {
212
239
  }
213
240
  function assertIdentityIsNotBlank(auth) {
214
241
  if (isBlank(auth.userId)) {
215
- throw new Error(
216
- `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
242
+ throw realtimeError(
243
+ REALTIME_ERROR_CODES.AUTH_FAILED,
244
+ `the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
217
245
  );
218
246
  }
219
247
  if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
220
- throw new Error(
221
- `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
248
+ throw realtimeError(
249
+ REALTIME_ERROR_CODES.AUTH_FAILED,
250
+ `the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
222
251
  );
223
252
  }
224
253
  }
@@ -403,7 +432,7 @@ function composeRoomId(prefix, ...parts) {
403
432
 
404
433
  // src/server/utils/unavailable-error.ts
405
434
  function unavailableError(code, who, what, cause) {
406
- return new Error(`[${who}] ${code}: ${what} (${describeError(cause)})`, { cause });
435
+ return realtimeError(code, `${what} (${describeError(cause)})`, { who, cause });
407
436
  }
408
437
  exports.InMemoryPubSub = class InMemoryPubSub {
409
438
  handlers = /* @__PURE__ */ new Set();
@@ -460,8 +489,9 @@ exports.HeartbeatService = class HeartbeatService {
460
489
  timers = /* @__PURE__ */ new Map();
461
490
  start(connectionId, res, intervalMs) {
462
491
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
463
- throw new Error(
464
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
492
+ throw realtimeError(
493
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
494
+ `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
465
495
  );
466
496
  }
467
497
  this.stop(connectionId);
@@ -492,6 +522,7 @@ exports.HeartbeatService = __decorateClass([
492
522
  ], exports.HeartbeatService);
493
523
 
494
524
  // src/server/transports/sse/sse.transport.ts
525
+ var _shuttingDown;
495
526
  exports.SseTransport = class SseTransport {
496
527
  constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
497
528
  this.connections = connections;
@@ -505,6 +536,9 @@ exports.SseTransport = class SseTransport {
505
536
  this.options = options;
506
537
  this.instanceId = instanceId;
507
538
  this.offlineQueue = offlineQueue;
539
+ __publicField(this, "kind", "sse");
540
+ __publicField(this, "logger", new common.Logger(exports.SseTransport.name));
541
+ __privateAdd(this, _shuttingDown, false);
508
542
  }
509
543
  connections;
510
544
  rooms;
@@ -517,14 +551,19 @@ exports.SseTransport = class SseTransport {
517
551
  options;
518
552
  instanceId;
519
553
  offlineQueue;
520
- kind = "sse";
521
- logger = new common.Logger(exports.SseTransport.name);
522
- async onApplicationShutdown() {
554
+ async beforeApplicationShutdown() {
555
+ __privateSet(this, _shuttingDown, true);
523
556
  this.heartbeat.stopAll();
524
557
  for (const conn of this.connections.allByTransport("sse")) {
525
558
  await this.disconnectLocal(conn.connectionId);
526
559
  }
527
560
  }
561
+ async onApplicationShutdown() {
562
+ await this.beforeApplicationShutdown();
563
+ }
564
+ get shuttingDown() {
565
+ return __privateGet(this, _shuttingDown);
566
+ }
528
567
  get heartbeatMs() {
529
568
  return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
530
569
  }
@@ -745,6 +784,7 @@ exports.SseTransport = class SseTransport {
745
784
  }
746
785
  }
747
786
  };
787
+ _shuttingDown = new WeakMap();
748
788
  exports.SseTransport = __decorateClass([
749
789
  common.Injectable(),
750
790
  __decorateParam(0, common.Inject(exports.ConnectionRegistry)),
@@ -845,6 +885,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
845
885
  async handle(req, res) {
846
886
  res.setHeader("Cache-Control", "no-cache, no-transform");
847
887
  res.setHeader("X-Accel-Buffering", "no");
888
+ this.refuseDuringShutdown();
848
889
  const done = this.authenticated.get(req);
849
890
  this.authenticated.delete(req);
850
891
  let authenticated;
@@ -853,11 +894,19 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
853
894
  } catch (err) {
854
895
  throw this.toClientError(err, "SSE authentication failed");
855
896
  }
897
+ let stream;
856
898
  try {
857
- return await this.openStream(req, res, authenticated);
899
+ stream = await this.openStream(req, res, authenticated);
858
900
  } catch (err) {
859
901
  throw this.serverError(err, "SSE handshake failed");
860
902
  }
903
+ this.refuseDuringShutdown();
904
+ return stream;
905
+ }
906
+ refuseDuringShutdown() {
907
+ if (this.transport.shuttingDown) {
908
+ throw new common.ServiceUnavailableException(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
909
+ }
861
910
  }
862
911
  async openStream(req, res, authenticated) {
863
912
  const { context, auth: resolvedAuth } = authenticated;
@@ -905,6 +954,10 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
905
954
  }
906
955
  buildStream(p) {
907
956
  return new rxjs.Observable((subscriber) => {
957
+ if (this.transport.shuttingDown) {
958
+ subscriber.complete();
959
+ return void 0;
960
+ }
908
961
  const inner = this.subscribePipeline(p, subscriber);
909
962
  if (!subscriber.closed && p.queueEvents.length > 0) {
910
963
  void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
@@ -1134,11 +1187,7 @@ exports.ReauthenticationService = class ReauthenticationService {
1134
1187
  }
1135
1188
  async handleFailure(conn) {
1136
1189
  this.positiveCache.delete(conn.connectionId);
1137
- if (this.policy.onFailure === "event") {
1138
- await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1139
- reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1140
- });
1141
- }
1190
+ if (this.policy.onFailure === "event") this.notify(conn);
1142
1191
  void Promise.resolve(
1143
1192
  this.hooks?.onReauthenticationFailed?.({
1144
1193
  connectionId: conn.connectionId,
@@ -1156,6 +1205,20 @@ exports.ReauthenticationService = class ReauthenticationService {
1156
1205
  });
1157
1206
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1158
1207
  }
1208
+ notify(conn) {
1209
+ const failed = (err) => {
1210
+ this.logger.warn(
1211
+ `Reauthentication notification for ${conn.connectionId} failed, disconnecting anyway: ${describeError(err)}`
1212
+ );
1213
+ };
1214
+ try {
1215
+ this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1216
+ reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1217
+ }).catch(failed);
1218
+ } catch (err) {
1219
+ failed(err);
1220
+ }
1221
+ }
1159
1222
  };
1160
1223
  exports.ReauthenticationService = __decorateClass([
1161
1224
  common.Injectable(),
@@ -1194,8 +1257,10 @@ var SHARED_SERVICES = [
1194
1257
  function assertModeSupported(wiring, mode, moduleName) {
1195
1258
  if (wiring.modes.includes(mode)) return;
1196
1259
  const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
1197
- throw new Error(
1198
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
1260
+ throw realtimeError(
1261
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1262
+ `transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`,
1263
+ { who: moduleName }
1199
1264
  );
1200
1265
  }
1201
1266
  function warnIfSingleInstance(pubsub, transport, logger) {
@@ -1235,26 +1300,32 @@ function composeForRoot(moduleClass, wiring, logger, options) {
1235
1300
  }
1236
1301
  function assertSseEndpointApplies(asyncOptions, moduleName) {
1237
1302
  if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
1238
- throw new Error(
1239
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
1303
+ throw realtimeError(
1304
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1305
+ `sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
1306
+ { who: moduleName }
1240
1307
  );
1241
1308
  }
1242
1309
  function bindSseEndpoint(resolved, declared, bound, moduleName) {
1243
1310
  if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
1244
- throw new Error(
1245
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
1311
+ throw realtimeError(
1312
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1313
+ `the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
1314
+ { who: moduleName }
1246
1315
  );
1247
1316
  }
1248
1317
  return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
1249
1318
  }
1250
1319
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1251
1320
  if (!raw) {
1252
- throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1321
+ throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
1253
1322
  }
1254
1323
  validateOptions(raw);
1255
1324
  if (raw.transport !== declaredMode) {
1256
- throw new Error(
1257
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
1325
+ throw realtimeError(
1326
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1327
+ `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`,
1328
+ { who: moduleName }
1258
1329
  );
1259
1330
  }
1260
1331
  const resolved = applyDefaults(raw);
@@ -1269,8 +1340,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1269
1340
  asyncOptions.useExisting
1270
1341
  ].filter((pattern) => pattern !== void 0);
1271
1342
  if (patterns.length !== 1) {
1272
- throw new Error(
1273
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1343
+ throw realtimeError(
1344
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1345
+ `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
1346
+ { who: moduleName }
1274
1347
  );
1275
1348
  }
1276
1349
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
@@ -1453,6 +1526,16 @@ exports.BymaxRealtimeModule = __decorateClass([
1453
1526
  common.Module({})
1454
1527
  ], exports.BymaxRealtimeModule);
1455
1528
  var MALFORMED_REPORT_INTERVAL_MS = 6e4;
1529
+ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
1530
+ "wait",
1531
+ "connecting",
1532
+ "connect",
1533
+ "reconnecting",
1534
+ "close",
1535
+ "end"
1536
+ ]);
1537
+ var PUBLISHER_WAIT_MS = 2e3;
1538
+ var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
1456
1539
  function connectionReason(err) {
1457
1540
  const code = err?.code;
1458
1541
  const text = describeError(err);
@@ -1469,25 +1552,47 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1469
1552
  #subscribed = false;
1470
1553
  #outageLogged = false;
1471
1554
  #retired = /* @__PURE__ */ new WeakSet();
1555
+ #lastRefusal;
1472
1556
  constructor(options) {
1473
1557
  this.#pub = options.client;
1474
1558
  this.channel = options.channel ?? "bymax:realtime";
1475
1559
  }
1476
1560
  isSubscribed() {
1477
- return this.#subscribed;
1561
+ return this.#subscribed && !CANNOT_PUBLISH.has(this.#pub.status);
1478
1562
  }
1479
1563
  async publish(message) {
1480
1564
  const status = this.#pub.status;
1481
- if (status === "reconnecting" || status === "close" || status === "end") {
1482
- throw unavailableError(
1483
- REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1484
- _RedisRealtimePubSub.name,
1485
- `cannot publish to "${this.channel}"`,
1486
- new Error(`the Redis client is ${status}`)
1487
- );
1565
+ if (CANNOT_PUBLISH.has(status)) {
1566
+ this.connectLazyClient();
1567
+ throw this.cannotPublish(`the Redis client is ${status}`);
1488
1568
  }
1489
1569
  await this.#pub.publish(this.channel, JSON.stringify(message));
1490
1570
  }
1571
+ connectLazyClient() {
1572
+ if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
1573
+ }
1574
+ publisherSettled() {
1575
+ const pub = this.#pub;
1576
+ if (pub.status !== "connecting" && pub.status !== "connect") return Promise.resolve();
1577
+ return new Promise((resolve) => {
1578
+ const settle = () => {
1579
+ clearTimeout(deadline);
1580
+ for (const event of CONNECTION_OVER) pub.off(event, settle);
1581
+ resolve();
1582
+ };
1583
+ const deadline = setTimeout(settle, PUBLISHER_WAIT_MS);
1584
+ deadline.unref();
1585
+ for (const event of CONNECTION_OVER) pub.once(event, settle);
1586
+ });
1587
+ }
1588
+ cannotPublish(reason) {
1589
+ return unavailableError(
1590
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1591
+ _RedisRealtimePubSub.name,
1592
+ `cannot publish to "${this.channel}"`,
1593
+ new Error(reason)
1594
+ );
1595
+ }
1491
1596
  async subscribe(handler) {
1492
1597
  this.handlers.add(handler);
1493
1598
  let sub;
@@ -1498,6 +1603,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1498
1603
  this.#subInit = null;
1499
1604
  throw err;
1500
1605
  }
1606
+ await this.publisherSettled();
1501
1607
  return async () => {
1502
1608
  this.handlers.delete(handler);
1503
1609
  if (this.handlers.size === 0) {
@@ -1519,6 +1625,8 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1519
1625
  }
1520
1626
  async createSubscriber() {
1521
1627
  this.#outageLogged = false;
1628
+ this.#lastRefusal = void 0;
1629
+ this.connectLazyClient();
1522
1630
  const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
1523
1631
  let attached = false;
1524
1632
  sub.on("message", (_ch, payload) => this.dispatch(payload));
@@ -1576,14 +1684,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1576
1684
  refused(err) {
1577
1685
  if (err?.name !== "ReplyError") return;
1578
1686
  this.#subscribed = false;
1687
+ const reason = describeError(err);
1688
+ if (reason === this.#lastRefusal) return;
1689
+ this.#lastRefusal = reason;
1579
1690
  this.logger.warn(
1580
- `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${describeError(err)}`
1691
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${reason}`
1581
1692
  );
1582
1693
  }
1583
1694
  markUp() {
1584
1695
  if (this.#subscribed) return;
1585
1696
  this.#subscribed = true;
1586
1697
  this.#outageLogged = false;
1698
+ this.#lastRefusal = void 0;
1587
1699
  this.logger.log(
1588
1700
  `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
1589
1701
  );
@@ -1706,6 +1818,7 @@ exports.composeRoomId = composeRoomId;
1706
1818
  exports.createSseController = createSseController;
1707
1819
  exports.describeError = describeError;
1708
1820
  exports.parseCookieHeader = parseCookieHeader;
1821
+ exports.realtimeError = realtimeError;
1709
1822
  exports.reportDeliveryFailure = reportDeliveryFailure;
1710
1823
  exports.resolveAuthTenant = resolveAuthTenant;
1711
1824
  exports.sseWiring = sseWiring;