@bymax-one/nest-realtime 1.2.14 → 1.2.16

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,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.16] - 2026-11-14
11
+
12
+ ### Fixed
13
+
14
+ - **A publish to a Redis that had stopped answering never settled.** `RedisRealtimePubSub.publish` awaited the `PUBLISH` with no limit once its client reported `ready`, and a paused or partitioned Redis accepts the socket and never replies, so every `emitToRoom`, `emitToTenant` and `broadcast` that waited on the bus, and every `disconnect()` of a connection held on another instance, stayed pending. A publish now gives up after two seconds and rejects with `REALTIME_PUBSUB_UNAVAILABLE`, the error it already raised when the client was not ready, so no caller changes: an emit reports the failure through `onDeliveryFailure`, and `disconnect()` rejects. The rejection means the server did not confirm the publish in time, not that it was not delivered: the command had already been written to the socket, so Redis can still process it when it answers, and an emit can arrive after it was reported failed.
15
+ - **A pub/sub payload that was not an object was dropped without a trace, and the messages the subscriber could not act on flooded the log.** A payload that parsed to `null` threw inside the subscriber into a catch that discarded it, with no count and no line; a message with no known op, or a known op with no `args`, wrote one warning for each message, with no limit, and carried the op or the error's message, which whoever can publish to the channel controls. A payload that is not an object is now counted by the report of malformed payloads, and everything else the subscriber cannot act on is reported once for each ten seconds, with a count and a reason that is either `unknown op` or the class of the last failure, never the op, the payload or an error's message.
16
+
17
+ #### Apply to a derived backend
18
+
19
+ Set `commandTimeout` on the ioredis client you give `RedisRealtimePubSub` (for example `new Redis({ commandTimeout: 5000 })`) if you want the command itself rejected: the library's limit stops the caller waiting, but the command stays queued in the client until the server answers or the connection drops. If you alert on the log lines `Unknown pub/sub op: …` or `Pub/sub message handling failed: …`, they no longer exist: alert on `Pub/sub dropped N message(s) it could not act on since the last report` instead. Nothing else changes.
20
+
21
+ ## [1.2.15] - 2026-11-14
22
+
23
+ ### Fixed
24
+
25
+ - **Closing the application waited for ever on a Redis that had stopped answering.** The Redis pub/sub subscriber is closed with a `QUIT`, a command on a connection, and on a connection that accepts the socket and never replies (a paused or partitioned Redis) it never settles, so `app.close()` stayed pending until the process was killed. The close now waits two seconds for the reply and then disconnects the connection. The subscriber that `RealtimeIoAdapter` opens for the Socket.IO Redis adapter with `pubClient.duplicate()` was never closed at all; it now is, in `dispose()`, once every server has closed, and on one bound for all of them. Your `pubClient` is never closed or changed.
26
+ - **A failing command of the Socket.IO Redis adapter's subscriber could end the process.** The adapter sends its `subscribe` and `unsubscribe` without awaiting them, so a command that failed, as every pending one does when its connection is closed, was an unhandled rejection. Each is now handled, and logged once per connection by the error's class only, never its message.
27
+
28
+ #### Apply to a derived backend
29
+
30
+ `RealtimeIoAdapter` gains a public `dispose()`, which closes the subscriber connection it opened; a class that extends it and overrides `dispose()` must call `super.dispose()`, or that connection stays open. Nothing else changes. Against a healthy Redis a shutdown is as it was; against one that does not answer it now finishes instead of never finishing, waiting a bounded time for each Redis connection it closes. The documentation said the library never opens its own Redis connection; the Socket.IO Redis adapter's subscriber is one, and `RealtimeIoAdapter` is what closes it.
31
+
10
32
  ## [1.2.14] - 2026-11-14
11
33
 
12
34
  ### Security
@@ -45,8 +67,6 @@ A `revalidate` that does not return `true` on every path now disconnects the con
45
67
 
46
68
  - **A re-authentication failure could leave a connection connected.** When a connection's credentials were refused, a `onReauthenticationFailed` hook that threw before it returned (a plain function, which the interface allows) aborted the failure handling before the connection was disconnected, so a failing notification hook could keep a connection whose credentials had been refused until the next cycle, and the same on every cycle after. The hook's failure is now logged and the connection is disconnected as before.
47
69
 
48
- ### Security
49
-
50
70
  - **An authenticator that never answered held every handshake for ever, and nothing limited how many could be waiting.** `authenticate` was awaited with no time limit, on SSE and on WebSocket, so a backend that accepts the request and never answers left every request or handshake pending, each holding a socket and a request, with no cap: one slow dependency, or one attacker, could exhaust the instance. A call that has not settled in the new `authenticateTimeoutMs` (default 10,000 ms) is now given up on, and the client is refused: a `503` with the generic body on SSE, the generic `connect_error` on WebSocket, and nothing about the cause reaches the client. At most `maxPendingHandshakes` (default 1,000) calls are waiting at once across both transports, and a call keeps its place until it actually settles, so an authenticator that never answers fills the limit and further handshakes are refused at once without being asked, instead of being given a new call each. A slow backend can therefore hold the limit full for as long as it stays slow, which is intended. The refusals are logged once for each ten seconds with a count, and nothing of the request is in the line.
51
71
 
52
72
  #### Apply to a derived backend
@@ -1085,7 +1105,9 @@ First published release.
1085
1105
  rather than by the manual sweep that raised the NestJS floors — that sweep
1086
1106
  asked about NestJS and never put the same question to the other ten peers.
1087
1107
 
1088
- [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...HEAD
1108
+ [Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.16...HEAD
1109
+ [1.2.16]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...v1.2.16
1110
+ [1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
1089
1111
  [1.2.14]: https://github.com/bymaxone/nest-realtime/compare/v1.2.13...v1.2.14
1090
1112
  [1.2.13]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...v1.2.13
1091
1113
  [1.2.12]: https://github.com/bymaxone/nest-realtime/compare/v1.2.11...v1.2.12
package/README.md CHANGED
@@ -331,7 +331,7 @@ bootstrap()
331
331
  RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'.
332
332
  ```
333
333
 
334
- With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber; the library never opens its own Redis connection. If it cannot be installed (the package is missing, the client has no `duplicate()`), the boot fails with `REALTIME_REDIS_ADAPTER_FAILED` instead of serving a single instance; a Redis that is merely unreachable does not fail the boot. Socket.IO's polling fallback needs sticky sessions even then — see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
334
+ With `redisAdapter`, the adapter registers `@socket.io/redis-adapter` and calls `pubClient.duplicate()` for the subscriber. That connection is the library's: it is closed when the application closes, and a QUIT that Redis does not answer within two seconds is dropped, so a Redis that stopped answering cannot hold the shutdown. Your `pubClient` is never closed or changed. If it cannot be installed (the package is missing, the client has no `duplicate()`), the boot fails with `REALTIME_REDIS_ADAPTER_FAILED` instead of serving a single instance; a Redis that is merely unreachable does not fail the boot. Socket.IO's polling fallback needs sticky sessions even then — see [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md). On the frontend, a `ws://` or `wss://` `url` selects WebSocket in `RealtimeProvider`. Replay through `Last-Event-ID` and the offline queue are SSE features: a WebSocket connection has neither.
335
335
 
336
336
  ---
337
337
 
@@ -385,7 +385,7 @@ What the client then does depends on how the attempt ended, and no `Retry-After`
385
385
  | `503` with the generic body | the response is not committed yet | The connection fails and the browser does **not** reconnect by itself. The application has to open a new `EventSource`, which cannot send `Last-Event-ID`, so what was missed is not replayed unless it adds the id to the url as `lastEventId`. | Reconnects after its backoff with a **new** `EventSource` that carries the last id it saw as the `lastEventId` query parameter: the events are replayed from there. |
386
386
  | `200`, then the stream ends with an error frame | an application interceptor committed the response first | Reconnects by itself and sends the last id it saw, so the events are read again. | The browser reconnects with the id. If the hook's own backoff opens a new source first, that one carries the id as `lastEventId`, so either way the events are read again. |
387
387
 
388
- An application that cannot lose events has to keep its own cursor and open the stream with it. The id is read from the `Last-Event-ID` header or, when the request has none, from the `lastEventId` query parameter, which is what `useRealtimeSse` sends (replacing a `lastEventId` the url you gave it already carries, once it has seen an event; the other parameters are then written again, so a key with no value gains an equals sign (`?flag` becomes `?flag=`), an encoded space is written as `+`, an empty parameter is dropped, and an encoded `+` stays one) and what an application adds to the url of a new `EventSource`; the header wins when both are present. An id longer than 256 characters, from either place, and a query value that is not a single string (a repeated parameter, say) are read as no id. The query parameter travels in the url, so it is written to access logs and caches with the rest of it; the ids this library generates are 20 characters (`{epoch ms}-{counter}`) and are not credentials.
388
+ An application that cannot lose events has to keep its own cursor and open the stream with it. The id is read from the `Last-Event-ID` header or, when the request has none, from the `lastEventId` query parameter, which is what `useRealtimeSse` sends (replacing a `lastEventId` the url you gave it already carries, once it has seen an event; the other parameters are then written again, so a key with no value gains an equals sign (`?flag` becomes `?flag=`), an encoded space is written as `+`, an empty parameter is dropped, an encoded `+` stays one, and a percent-encoded byte that is not valid UTF-8 is written as the replacement character, so `%FF` becomes `%EF%BF%BD` while a valid sequence such as `%E2%82%AC` is unchanged) and what an application adds to the url of a new `EventSource`; the header wins when both are present. An id longer than 256 characters, from either place, and a query value that is not a single string (a repeated parameter, say) are read as no id. The query parameter travels in the url, so it is written to access logs and caches with the rest of it; the ids this library generates are 20 characters (`{epoch ms}-{counter}`) and are not credentials.
389
389
 
390
390
  #### How many connections one instance holds
391
391
 
@@ -429,6 +429,57 @@ The design specification, [docs/technical_specification.md](./docs/technical_spe
429
429
 
430
430
  ---
431
431
 
432
+ ## 🏭 Running in Production
433
+
434
+ This section lists the bounds the library applies, what happens when each one is reached, and what an instance does when a dependency fails. A default is the value in the code. A behaviour stated here is one that a test or a measurement pins, and the `Evidence` column of the second table says which; where nothing pins a behaviour, the row says "not measured".
435
+
436
+ ### Limits
437
+
438
+ | Bound | Default | When it is reached |
439
+ | ---------------------------------------------------------------------------------- | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
440
+ | `maxConnections` | 10,000 | A handshake past it is refused before `authenticate` is called: SSE answers `503`, WebSocket answers the generic `connect_error`. Connections of both transports count together. See [How many connections one instance holds](#how-many-connections-one-instance-holds). |
441
+ | `maxPendingHandshakes` | 1,000 | A handshake that finds that many `authenticate` calls waiting is refused at once, and `authenticate` is not called. A call whose handshake was refused for taking too long keeps its place while it is still open. See [Authentication is bounded](#authentication-is-bounded). |
442
+ | `authenticateTimeoutMs` | 10,000 ms | A handshake whose `authenticate` has not settled by then is refused: `503` with the generic body on SSE, the generic `connect_error` on WebSocket. A read of the offline queue for a reconnect that carries `Last-Event-ID` is given up on after the same time. See [The offline-queue read on a reconnect](#the-offline-queue-read-on-a-reconnect). |
443
+ | `hookTimeoutMs` | 5,000 ms | A hook the library awaits that has not settled by then is given up on, and the failure is logged as `did not settle within N ms`. See [Hooks the library waits for](#hooks-the-library-waits-for). |
444
+ | `reauthenticationPolicy.revalidateTimeoutMs`, `reauthenticationPolicy.concurrency` | 10,000 ms; 8 | A `revalidate` call that has not settled by then is treated as one that threw, and its connection is revoked. At most `concurrency` calls run at once. |
445
+ | `sse.maxQueuedEvents`, `sse.maxQueuedBytes` | 1,000 events; 2,097,152 bytes | An event that would take the events queued for a connection past `sse.maxQueuedEvents` is not queued; that connection is closed with the reason `REALTIME_SLOW_CONSUMER` and the others are not affected. The queue's counter refuses an event that would take the bytes past `sse.maxQueuedBytes`, unless that event is the only one queued. With the defaults, a client that never reads is closed with the same reason. [A client that does not read](#a-client-that-does-not-read) states the cases this row does not cover. |
446
+ | `sse.stallHeartbeats` | 3 | A connection whose socket has taken nothing for that many heartbeats in a row, while the response holds bytes, is closed with the reason `REALTIME_SLOW_CONSUMER`. |
447
+ | `sse.replayBufferSize`, `sse.replayTtlMs`, `sse.replayMaxIdleUsers` | 100 events; 300,000 ms; 1,000 users | A user's ring keeps the newest `replayBufferSize` events and drops the older ones. An entry is dropped `replayTtlMs` after its user's last connection closed. At most `replayMaxIdleUsers` such entries are kept, and the one that closed longest ago goes first. See [Replay is per instance, and bounded](#replay-is-per-instance-and-bounded). |
448
+ | Length of a `Last-Event-ID` header or `lastEventId` query value | 256 characters | An id longer than that is treated as absent: no replay and no offline-queue read is made for it. An id of exactly 256 characters is used. A longer header with a valid query value falls back to the query value. |
449
+
450
+ ### When a dependency fails
451
+
452
+ | Situation | What the instance does | Evidence |
453
+ | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
454
+ | SSE pub/sub: the Redis server refuses the SUBSCRIBE at start (wrong password, missing permission) | `subscribe` rejects with `REALTIME_PUBSUB_UNAVAILABLE`, and the boot fails. | tested |
455
+ | SSE pub/sub: Redis is unreachable at start | The boot completes without waiting for Redis, the instance is not subscribed, one warning line is logged for the outage, not one for each retry, and the instance subscribes when Redis comes up. | tested |
456
+ | Socket.IO Redis adapter: Redis never answers at start | Creating the Socket.IO server returns and the Redis adapter is registered, without waiting for Redis. | tested with a client whose commands never settle |
457
+ | SSE pub/sub: the publishing client's first connection is slow | `subscribe` waits for it, 2,000 ms at most; after that the boot completes and the instance is not subscribed. | tested |
458
+ | SSE pub/sub, Redis lost while running: a publish | It is refused at once with `REALTIME_PUBSUB_UNAVAILABLE` and is never sent when the connection returns. | tested |
459
+ | SSE pub/sub, Redis connected but not answering: a publish | It rejects with `REALTIME_PUBSUB_UNAVAILABLE` after 2,000 ms. The rejection means the server did not confirm the publish in time, not that it was not delivered: the command was already written to the socket, so Redis can still process it when it answers and an emit can arrive after it was reported failed. The command stays queued in the client until the server answers or the connection drops; set `commandTimeout` on your ioredis client (for example `new Redis({ commandTimeout: 5000 })`) to reject the command itself. | tested on a controlled clock; measured on 1.2.16, against a `redis:7-alpine` container paused with `docker pause`: rejected after 2,001, 2,003 and 2,005 ms |
460
+ | SSE pub/sub, Redis lost while running: `disconnect` of a connection this instance does not hold | `disconnect` rejects at once with `REALTIME_PUBSUB_UNAVAILABLE`. `emitToUser` for a user with no connection on this instance, with no offline queue configured, resolves at once. | tested |
461
+ | SSE pub/sub, Redis lost while running: the subscriber | One warning line is logged for an outage while its reconnects fail (several attempts over 400 ms in the test), and a `Subscribed` line is logged again when Redis returns. | tested |
462
+ | Redis is paused when an SSE application closes | The close waits at most 2,000 ms for the subscriber's QUIT, then disconnects it. `app.close()` settled in 2,003 ms. | measured on 1.2.15, against a `redis:7-alpine` container paused with `docker pause`; the bound is also pinned on a controlled clock |
463
+ | Redis is paused when an application with both transports closes | The adapter's subscriber and the pub/sub subscriber are each waited for at most 2,000 ms, one after the other. `app.close()` settled in 4,007 ms. | measured on 1.2.15, against a `redis:7-alpine` container paused with `docker pause`; the two bounds are also pinned on a controlled clock |
464
+ | The offline queue does not answer | A reconnect that carries `Last-Event-ID` gets a `503` with the generic body after `authenticateTimeoutMs`, and nothing is registered. A queue whose first read rejects gives an empty gap instead, and the client gets its live events. At most 1,000 reads wait at once by default; the next is refused without a call to the store. | tested |
465
+ | The authenticator does not answer | Handshakes are refused after `authenticateTimeoutMs`; once `maxPendingHandshakes` calls wait, further handshakes are refused at once. | tested |
466
+ | A consumer hook never settles | The library gives up on it after `hookTimeoutMs`. On WebSocket an `onConnect` that never settles delays the announcement of the connection until then, and an `onDisconnect` that never settles still removes the connection while the other client stays connected. When an application closes, five SSE streams whose `onDisconnect` never settles are released after one hook timeout of a test clock. | tested |
467
+ | Memory over a long soak; behaviour at `maxConnections` on a real host | not measured | not measured |
468
+
469
+ ### Shutdown order
470
+
471
+ The Socket.IO server closes first, then the adapter's `dispose()` runs, and `dispose()` closes the adapter's own Redis subscriber connection. The pub/sub subscriber is unsubscribed in the application shutdown hook. When both transports run, the two Redis subscribers are closed in two successive phases, each waited for at most 2,000 ms. [Shutdown](#shutdown) describes how a shutdown starts.
472
+
473
+ ### Before you deploy
474
+
475
+ - File-descriptor limit against `maxConnections`: [How many connections one instance holds](#how-many-connections-one-instance-holds).
476
+ - Proxy buffering for SSE: [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
477
+ - Sticky sessions with the polling fallback: [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md#sticky-sessions--mandatory-for-polling-fallback).
478
+ - Replay is per instance: [Replay is per instance, and bounded](#replay-is-per-instance-and-bounded).
479
+ - HTTPS and CORS: [Security Checklist](#security-checklist).
480
+
481
+ ---
482
+
432
483
  ## 🏗️ Architecture
433
484
 
434
485
  The package runs **inside** your NestJS application as a dynamic module — not as a separate realtime server:
@@ -595,7 +646,7 @@ The unified emit API. Identical on every transport.
595
646
 
596
647
  All methods return `Promise<void>`.
597
648
 
598
- **Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is Nest's `ServiceUnavailableException` (HTTP `503`) with `code` set, so a controller that lets it escape answers `503` with the generic body (see "What a client is told"). A rejection means the connection may still be connected, so retry.
649
+ **Revocation is never best-effort.** `disconnect(connectionId)` resolves once the connection was closed on this instance or the revocation was handed to the bus (`IRealtimePubSub`). It **rejects**, with `error.code` set to a `RealtimeErrorCode`, when it could not: `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the publish (`RedisRealtimePubSub` refuses at once while its Redis client is not ready, and after 2,000 ms when the client is ready but the server does not answer), `REALTIME_TRANSPORT_UNAVAILABLE` when the WebSocket server is not attached or its fan-out throws. Branch on the code, not the message; the error is Nest's `ServiceUnavailableException` (HTTP `503`) with `code` set, so a controller that lets it escape answers `503` with the generic body (see "What a client is told"). A rejection means the connection may still be connected, so retry.
599
650
 
600
651
  **Emits are at-most-once.** `emitToUser`, `emitToTenant`, `emitToRoom` and `broadcast` **resolve even when the publish to the other instances failed**; that failure is logged with `REALTIME_PUBSUB_UNAVAILABLE` and passed to the `onDeliveryFailure` hook, which is where to count it. An offline queue that could not keep an event for a user who is offline here is reported the same way, since another instance may have delivered it live; a failure on one transport of `'both'` is only logged. An emit rejects only when the event has no delivery path left: for `emitToUser`, the user is offline here, the queue failed, and the bus failed or cannot reach another instance (the default in-memory bus); with `'both'`, a failure on both transports rejects with `REALTIME_TRANSPORT_UNAVAILABLE`. A rejected emit is not proof that no client received it, so retry only where a duplicate is acceptable.
601
652
 
@@ -863,7 +914,7 @@ The code travels on the error you catch; what reaches a client is decided by the
863
914
 
864
915
  The rejection of a call is Nest's own `ServiceUnavailableException`, so a controller that lets it escape answers `503` with the body `{"statusCode":503,"message":"Service Unavailable"}`. The library's message, which names the failed call, and the `cause`, which can hold a driver's text with a host and credentials, are on the instance for your logs and never in the response. Branch on `error.code`, not on the message.
865
916
 
866
- Nest's default exception filter does not log an `HttpException`, so a `503` from one of these calls leaves no line in your log, where a plain `Error` was logged with its stack. To keep a record, catch `ServiceUnavailableException` in an exception filter of your own and log `exception.code`, `exception.message` and `exception.cause`, as you would for any other `HttpException` you want to see.
917
+ Nest's default exception filter does not log an `HttpException`, so a `503` from one of these calls leaves no line in your log, where a plain `Error` was logged with its stack. To keep a record, catch `ServiceUnavailableException` in an exception filter of your own and log `exception.code`, `exception.message` and `exception.cause`, as you would for any other `HttpException` you want to see. With `@bymax-one/nest-core` 1.6.10 and an `IUnexpectedErrorSink` bound, such a `503` reaches the sink with its `cause`, once for each status and code in each `envelope.serverErrorWindowMs` window (60 s by default), so the outage is recorded there without a filter of your own; the cause can carry a host and a port, so redact it in your logger.
867
918
 
868
919
  **An authenticator that wants a `503` throws `ServiceUnavailableException`.** On SSE an `HttpException` thrown from `authenticate` is sent as it is, so `throw new ServiceUnavailableException()` answers `503`; any other error answers a generic `500`. On WebSocket the handshake carries no HTTP status: an authenticator's own exception is answered with the generic message and no `data.code`. Only the library's own unavailable refusals carry `REALTIME_TRANSPORT_UNAVAILABLE`, which a client can treat as retryable.
869
920
 
@@ -218,11 +218,26 @@ function reportDeliveryFailure(logger, hooks, failure, what) {
218
218
  });
219
219
  }
220
220
 
221
+ // src/server/utils/windowed-report.ts
222
+ var REPORT_WINDOW_MS = 1e4;
223
+ function windowedReport(fresh, emit) {
224
+ let startedAt = Number.NEGATIVE_INFINITY;
225
+ let pending = fresh();
226
+ return (add) => {
227
+ pending = add(pending);
228
+ const now = performance.now();
229
+ if (now - startedAt < REPORT_WINDOW_MS) return;
230
+ startedAt = now;
231
+ const accumulated = pending;
232
+ pending = fresh();
233
+ emit(accumulated);
234
+ };
235
+ }
236
+
221
237
  // src/server/offline-queue/offline-queue-delivery.service.ts
222
238
  var RETRIEVE_LIMIT = 200;
223
239
  var DEFAULT_TIMEOUT_MS = 1e4;
224
240
  var DEFAULT_MAX_PENDING = 1e3;
225
- var REPORT_WINDOW_MS = 1e4;
226
241
  var OfflineQueueTimeoutError = class extends Error {
227
242
  constructor() {
228
243
  super("the offline queue did not answer in time");
@@ -241,8 +256,14 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
241
256
  timeoutMs;
242
257
  maxPending;
243
258
  pending = 0;
244
- windowStartedAt = Number.NEGATIVE_INFINITY;
245
- timedOut = 0;
259
+ timeouts = windowedReport(
260
+ () => 0,
261
+ (count) => {
262
+ this.logger.warn(
263
+ `reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
264
+ );
265
+ }
266
+ );
246
267
  async retrieve(userId, lastEventId, ringBufferIds) {
247
268
  const { events } = await this.retrieveGap(userId, lastEventId);
248
269
  return events.filter((e) => !ringBufferIds.has(e.id));
@@ -318,15 +339,7 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
318
339
  }
319
340
  }
320
341
  countTimeout() {
321
- this.timedOut += 1;
322
- const now = performance.now();
323
- if (now - this.windowStartedAt < REPORT_WINDOW_MS) return;
324
- this.windowStartedAt = now;
325
- const count = this.timedOut;
326
- this.timedOut = 0;
327
- this.logger.warn(
328
- `reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
329
- );
342
+ this.timeouts((count) => count + 1);
330
343
  }
331
344
  };
332
345
  exports.OfflineQueueDeliveryService = __decorateClass([
@@ -459,7 +472,6 @@ function resolveClientAddress(request) {
459
472
  }
460
473
  return peerAddress(request.socket?.remoteAddress);
461
474
  }
462
- var REPORT_WINDOW_MS2 = 1e4;
463
475
  var AuthenticationUnavailableError = class extends Error {
464
476
  constructor(reason) {
465
477
  super(
@@ -480,8 +492,14 @@ exports.AuthenticationGate = class AuthenticationGate {
480
492
  maxPending;
481
493
  timeoutMs;
482
494
  pending = 0;
483
- windowStartedAt = Number.NEGATIVE_INFINITY;
484
- refused = { saturated: 0, timeout: 0 };
495
+ refusals = windowedReport(
496
+ () => ({ saturated: 0, timeout: 0 }),
497
+ ({ saturated, timeout }) => {
498
+ this.logger.warn(
499
+ `handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
500
+ );
501
+ }
502
+ );
485
503
  async authenticate(context) {
486
504
  if (this.pending >= this.maxPending) {
487
505
  this.refuse("saturated");
@@ -510,15 +528,7 @@ exports.AuthenticationGate = class AuthenticationGate {
510
528
  }
511
529
  }
512
530
  refuse(reason) {
513
- this.refused[reason] += 1;
514
- const now = performance.now();
515
- if (now - this.windowStartedAt < REPORT_WINDOW_MS2) return;
516
- this.windowStartedAt = now;
517
- const { saturated, timeout } = this.refused;
518
- this.refused = { saturated: 0, timeout: 0 };
519
- this.logger.warn(
520
- `handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
521
- );
531
+ this.refusals((refused) => ({ ...refused, [reason]: refused[reason] + 1 }));
522
532
  }
523
533
  };
524
534
  exports.AuthenticationGate = __decorateClass([
@@ -596,7 +606,6 @@ exports.ConnectionRegistry = __decorateClass([
596
606
  var DEFAULT_AUTHENTICATE_TIMEOUT_MS = 1e4;
597
607
  var DEFAULT_MAX_CONNECTIONS = 1e4;
598
608
  var HOLD_MARGIN_MS = 5e3;
599
- var REPORT_WINDOW_MS3 = 1e4;
600
609
  var ConnectionLimitError = class extends Error {
601
610
  constructor(limit) {
602
611
  super(`the instance already holds ${limit} connections`);
@@ -619,8 +628,14 @@ exports.ConnectionAdmission = class ConnectionAdmission {
619
628
  max;
620
629
  holdMs;
621
630
  held = /* @__PURE__ */ new Map();
622
- windowStartedAt = Number.NEGATIVE_INFINITY;
623
- refused = 0;
631
+ refusals = windowedReport(
632
+ () => 0,
633
+ (count) => {
634
+ this.logger.warn(
635
+ `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
636
+ );
637
+ }
638
+ );
624
639
  admit() {
625
640
  const place = /* @__PURE__ */ Symbol("place");
626
641
  this.take(place);
@@ -652,15 +667,7 @@ exports.ConnectionAdmission = class ConnectionAdmission {
652
667
  }
653
668
  }
654
669
  refuse() {
655
- this.refused += 1;
656
- const now = performance.now();
657
- if (now - this.windowStartedAt < REPORT_WINDOW_MS3) return;
658
- this.windowStartedAt = now;
659
- const count = this.refused;
660
- this.refused = 0;
661
- this.logger.warn(
662
- `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
663
- );
670
+ this.refusals((count) => count + 1);
664
671
  }
665
672
  };
666
673
  exports.ConnectionAdmission = __decorateClass([
@@ -2135,9 +2142,17 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
2135
2142
  this.unsubscribe = null;
2136
2143
  }
2137
2144
  }
2145
+ dropped = windowedReport(
2146
+ () => ({ count: 0, last: "none" }),
2147
+ ({ count, last }) => {
2148
+ this.logger.warn(
2149
+ `Pub/sub dropped ${count} message(s) it could not act on since the last report (last: ${last})`
2150
+ );
2151
+ }
2152
+ );
2138
2153
  handle(msg) {
2139
- if (msg.origin === this.instanceId) return;
2140
2154
  try {
2155
+ if (msg.origin === this.instanceId) return;
2141
2156
  switch (msg.op) {
2142
2157
  case "emitToUser": {
2143
2158
  const a = msg.args;
@@ -2171,14 +2186,17 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
2171
2186
  break;
2172
2187
  }
2173
2188
  default: {
2174
- const exhaustive = msg.op;
2175
- this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
2189
+ msg.op;
2190
+ this.drop("unknown op");
2176
2191
  }
2177
2192
  }
2178
2193
  } catch (err) {
2179
- this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
2194
+ this.drop(String(Object(err).constructor?.name ?? "Error"));
2180
2195
  }
2181
2196
  }
2197
+ drop(last) {
2198
+ this.dropped(({ count }) => ({ count: count + 1, last }));
2199
+ }
2182
2200
  };
2183
2201
  exports.RealtimePubSubSubscriber = __decorateClass([
2184
2202
  common.Injectable(),
@@ -2232,6 +2250,31 @@ exports.BymaxRealtimeModule = __decorateClass([
2232
2250
  common.Global(),
2233
2251
  common.Module({})
2234
2252
  ], exports.BymaxRealtimeModule);
2253
+
2254
+ // src/server/utils/quit-within.ts
2255
+ var QUIT_WAIT_MS = 2e3;
2256
+ async function quitWithin(client, ms = QUIT_WAIT_MS) {
2257
+ let timer;
2258
+ const bound = new Promise((resolve) => {
2259
+ timer = setTimeout(resolve, ms);
2260
+ timer.unref();
2261
+ });
2262
+ let answered = false;
2263
+ const quit = client.quit().then(
2264
+ () => {
2265
+ answered = true;
2266
+ },
2267
+ () => void 0
2268
+ );
2269
+ try {
2270
+ await Promise.race([quit, bound]);
2271
+ if (!answered) client.disconnect();
2272
+ } finally {
2273
+ clearTimeout(timer);
2274
+ }
2275
+ }
2276
+
2277
+ // src/server/pubsub/redis-realtime-pubsub.ts
2235
2278
  var MALFORMED_REPORT_INTERVAL_MS = 6e4;
2236
2279
  var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
2237
2280
  "wait",
@@ -2242,6 +2285,7 @@ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
2242
2285
  "end"
2243
2286
  ]);
2244
2287
  var PUBLISHER_WAIT_MS = 2e3;
2288
+ var PUBLISH_WAIT_MS = 2e3;
2245
2289
  var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
2246
2290
  function connectionReason(err) {
2247
2291
  const code = err?.code;
@@ -2273,7 +2317,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2273
2317
  this.connectLazyClient();
2274
2318
  throw this.cannotPublish(`the Redis client is ${status}`);
2275
2319
  }
2276
- await this.#pub.publish(this.channel, JSON.stringify(message));
2320
+ const sent = this.#pub.publish(this.channel, JSON.stringify(message));
2321
+ let timer;
2322
+ const expired = new Promise((_resolve, reject) => {
2323
+ timer = setTimeout(
2324
+ () => reject(this.cannotPublish(`the server did not answer within ${PUBLISH_WAIT_MS} ms`)),
2325
+ PUBLISH_WAIT_MS
2326
+ );
2327
+ timer.unref();
2328
+ });
2329
+ try {
2330
+ await Promise.race([sent, expired]);
2331
+ } finally {
2332
+ clearTimeout(timer);
2333
+ }
2277
2334
  }
2278
2335
  connectLazyClient() {
2279
2336
  if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
@@ -2319,7 +2376,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2319
2376
  const connected = this.#subscribed;
2320
2377
  this.#subscribed = false;
2321
2378
  try {
2322
- if (connected) await sub.quit();
2379
+ if (connected) await quitWithin(sub);
2323
2380
  else sub.disconnect();
2324
2381
  } catch {
2325
2382
  }
@@ -2432,7 +2489,12 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2432
2489
  dispatch(payload) {
2433
2490
  let msg;
2434
2491
  try {
2435
- msg = JSON.parse(payload);
2492
+ const parsed = JSON.parse(payload);
2493
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2494
+ this.reportMalformed();
2495
+ return;
2496
+ }
2497
+ msg = parsed;
2436
2498
  } catch {
2437
2499
  this.reportMalformed();
2438
2500
  return;
@@ -2535,6 +2597,7 @@ exports.composeRoomId = composeRoomId;
2535
2597
  exports.createSseController = createSseController;
2536
2598
  exports.describeError = describeError;
2537
2599
  exports.parseCookieHeader = parseCookieHeader;
2600
+ exports.quitWithin = quitWithin;
2538
2601
  exports.realtimeError = realtimeError;
2539
2602
  exports.reportDeliveryFailure = reportDeliveryFailure;
2540
2603
  exports.resolveAuthTenant = resolveAuthTenant;
@@ -1058,6 +1058,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
1058
1058
  private notify;
1059
1059
  }
1060
1060
 
1061
+ /** How long a window of refusals is summarised in one log line. */
1061
1062
  /**
1062
1063
  * A handshake was refused because the authenticator could not be asked or did not answer in time:
1063
1064
  * a fault of the system, not of the credentials, and carrying nothing about either.
@@ -1081,8 +1082,7 @@ declare class AuthenticationGate {
1081
1082
  private readonly maxPending;
1082
1083
  private readonly timeoutMs;
1083
1084
  private pending;
1084
- private windowStartedAt;
1085
- private refused;
1085
+ private readonly refusals;
1086
1086
  constructor(options: BymaxRealtimeModuleOptions, authenticator: IConnectionAuthenticator);
1087
1087
  /**
1088
1088
  * Ask the authenticator about one handshake.
@@ -1095,6 +1095,7 @@ declare class AuthenticationGate {
1095
1095
  private refuse;
1096
1096
  }
1097
1097
 
1098
+ /** How long a window of refusals is summarised in one log line. */
1098
1099
  /** A handshake was refused because the instance already holds `maxConnections` connections. */
1099
1100
  declare class ConnectionLimitError extends Error {
1100
1101
  readonly limit: number;
@@ -1134,8 +1135,7 @@ declare class ConnectionAdmission {
1134
1135
  private readonly holdMs;
1135
1136
  /** The places held, oldest first, each with the time it is given back at whatever happens. */
1136
1137
  private readonly held;
1137
- private windowStartedAt;
1138
- private refused;
1138
+ private readonly refusals;
1139
1139
  constructor(options: BymaxRealtimeModuleOptions, registry: ConnectionRegistry);
1140
1140
  /**
1141
1141
  * Take a place for one connection.
@@ -1175,6 +1175,7 @@ declare class RoomRegistry {
1175
1175
  countRooms(): number;
1176
1176
  }
1177
1177
 
1178
+ /** How long a window of timeouts is summarised in one log line. */
1178
1179
  /** What the first read of a reconnect's gap came to. */
1179
1180
  interface OfflineQueueRead {
1180
1181
  /** The gap events, in queue order. */
@@ -1204,8 +1205,7 @@ declare class OfflineQueueDeliveryService {
1204
1205
  private readonly timeoutMs;
1205
1206
  private readonly maxPending;
1206
1207
  private pending;
1207
- private windowStartedAt;
1208
- private timedOut;
1208
+ private readonly timeouts;
1209
1209
  constructor(storage?: IOfflineQueueStorage | undefined, hooks?: IConnectionLifecycleHooks | undefined, options?: BymaxRealtimeModuleOptions);
1210
1210
  /**
1211
1211
  * Return events for `userId` that arrived after `lastEventId` and are NOT
@@ -1870,7 +1870,15 @@ declare class RealtimePubSubSubscriber implements OnModuleInit, OnApplicationShu
1870
1870
  constructor(pubsub: IRealtimePubSub, instanceId: string, sse: SseTransport);
1871
1871
  onModuleInit(): Promise<void>;
1872
1872
  onApplicationShutdown(): Promise<void>;
1873
+ /**
1874
+ * Messages the subscriber cannot act on, counted and reported once for each window. The line
1875
+ * carries the count and the reason in a fixed vocabulary: an unknown op, or the class of the last
1876
+ * failure. The op and the failure's message can echo what whoever publishes to the channel
1877
+ * wrote, so neither is ever written.
1878
+ */
1879
+ private readonly dropped;
1873
1880
  private handle;
1881
+ private drop;
1874
1882
  }
1875
1883
 
1876
1884
  /** Options for RedisRealtimePubSub. */
@@ -1927,6 +1935,14 @@ declare class RedisRealtimePubSub implements IRealtimePubSub {
1927
1935
  * returns, and never gives up on one waiting behind a peer that does not answer, so a revocation
1928
1936
  * would wait out the whole outage and then be sent after its caller was told it failed. It is
1929
1937
  * refused at once instead, and never handed to the client.
1938
+ *
1939
+ * A client that can publish but whose server stops answering is given {@link PUBLISH_WAIT_MS}:
1940
+ * after it the publish rejects the same way. That rejection means the server did not confirm the
1941
+ * publish in time, not that it was not delivered: the command was already written to the socket
1942
+ * and Redis can still process it when it answers, so a message can arrive after its caller was
1943
+ * told it failed. The command also stays queued in the client until the server answers or the
1944
+ * connection drops; `commandTimeout` on the host's ioredis client is what rejects the command
1945
+ * itself.
1930
1946
  */
1931
1947
  publish(message: RealtimePubSubMessage): Promise<void>;
1932
1948
  /**
@@ -2157,6 +2173,30 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
2157
2173
  /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
2158
2174
  declare function describeError(reason: unknown): string;
2159
2175
 
2176
+ /**
2177
+ * @fileoverview Closing a Redis connection without waiting on a server that has stopped answering.
2178
+ * @layer infrastructure
2179
+ */
2180
+ /** The part of an ioredis client that closing a connection uses. */
2181
+ interface QuitableClient {
2182
+ quit(): Promise<unknown>;
2183
+ disconnect(): void;
2184
+ }
2185
+ /**
2186
+ * Quits `client`, waiting at most `ms` for the server to answer, and disconnects it when it did
2187
+ * not. QUIT is a command on the connection, so on a connection that no longer answers it never
2188
+ * settles and nothing in ioredis bounds it. A client whose QUIT was answered is already closed and
2189
+ * is left alone: disconnecting it again would arm ioredis's close timer on a socket that has no
2190
+ * close left to clear it.
2191
+ *
2192
+ * Never rejects: an error from QUIT (a connection that is already closed) is the same outcome as a
2193
+ * server that did not answer, and the connection is disconnected.
2194
+ *
2195
+ * @param client - The connection to close.
2196
+ * @param ms - How long to wait for the QUIT to be answered.
2197
+ */
2198
+ declare function quitWithin(client: QuitableClient, ms?: number): Promise<void>;
2199
+
2160
2200
  /**
2161
2201
  * @fileoverview Runs a consumer's lifecycle hook so that its failure is a value, never an exception.
2162
2202
  * @layer utils
@@ -2369,5 +2409,5 @@ declare const RESERVED_EVENT_NAMES: {
2369
2409
  /** Union of reserved event name values. */
2370
2410
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2371
2411
 
2372
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2373
- export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
2412
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2413
+ export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -1058,6 +1058,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
1058
1058
  private notify;
1059
1059
  }
1060
1060
 
1061
+ /** How long a window of refusals is summarised in one log line. */
1061
1062
  /**
1062
1063
  * A handshake was refused because the authenticator could not be asked or did not answer in time:
1063
1064
  * a fault of the system, not of the credentials, and carrying nothing about either.
@@ -1081,8 +1082,7 @@ declare class AuthenticationGate {
1081
1082
  private readonly maxPending;
1082
1083
  private readonly timeoutMs;
1083
1084
  private pending;
1084
- private windowStartedAt;
1085
- private refused;
1085
+ private readonly refusals;
1086
1086
  constructor(options: BymaxRealtimeModuleOptions, authenticator: IConnectionAuthenticator);
1087
1087
  /**
1088
1088
  * Ask the authenticator about one handshake.
@@ -1095,6 +1095,7 @@ declare class AuthenticationGate {
1095
1095
  private refuse;
1096
1096
  }
1097
1097
 
1098
+ /** How long a window of refusals is summarised in one log line. */
1098
1099
  /** A handshake was refused because the instance already holds `maxConnections` connections. */
1099
1100
  declare class ConnectionLimitError extends Error {
1100
1101
  readonly limit: number;
@@ -1134,8 +1135,7 @@ declare class ConnectionAdmission {
1134
1135
  private readonly holdMs;
1135
1136
  /** The places held, oldest first, each with the time it is given back at whatever happens. */
1136
1137
  private readonly held;
1137
- private windowStartedAt;
1138
- private refused;
1138
+ private readonly refusals;
1139
1139
  constructor(options: BymaxRealtimeModuleOptions, registry: ConnectionRegistry);
1140
1140
  /**
1141
1141
  * Take a place for one connection.
@@ -1175,6 +1175,7 @@ declare class RoomRegistry {
1175
1175
  countRooms(): number;
1176
1176
  }
1177
1177
 
1178
+ /** How long a window of timeouts is summarised in one log line. */
1178
1179
  /** What the first read of a reconnect's gap came to. */
1179
1180
  interface OfflineQueueRead {
1180
1181
  /** The gap events, in queue order. */
@@ -1204,8 +1205,7 @@ declare class OfflineQueueDeliveryService {
1204
1205
  private readonly timeoutMs;
1205
1206
  private readonly maxPending;
1206
1207
  private pending;
1207
- private windowStartedAt;
1208
- private timedOut;
1208
+ private readonly timeouts;
1209
1209
  constructor(storage?: IOfflineQueueStorage | undefined, hooks?: IConnectionLifecycleHooks | undefined, options?: BymaxRealtimeModuleOptions);
1210
1210
  /**
1211
1211
  * Return events for `userId` that arrived after `lastEventId` and are NOT
@@ -1870,7 +1870,15 @@ declare class RealtimePubSubSubscriber implements OnModuleInit, OnApplicationShu
1870
1870
  constructor(pubsub: IRealtimePubSub, instanceId: string, sse: SseTransport);
1871
1871
  onModuleInit(): Promise<void>;
1872
1872
  onApplicationShutdown(): Promise<void>;
1873
+ /**
1874
+ * Messages the subscriber cannot act on, counted and reported once for each window. The line
1875
+ * carries the count and the reason in a fixed vocabulary: an unknown op, or the class of the last
1876
+ * failure. The op and the failure's message can echo what whoever publishes to the channel
1877
+ * wrote, so neither is ever written.
1878
+ */
1879
+ private readonly dropped;
1873
1880
  private handle;
1881
+ private drop;
1874
1882
  }
1875
1883
 
1876
1884
  /** Options for RedisRealtimePubSub. */
@@ -1927,6 +1935,14 @@ declare class RedisRealtimePubSub implements IRealtimePubSub {
1927
1935
  * returns, and never gives up on one waiting behind a peer that does not answer, so a revocation
1928
1936
  * would wait out the whole outage and then be sent after its caller was told it failed. It is
1929
1937
  * refused at once instead, and never handed to the client.
1938
+ *
1939
+ * A client that can publish but whose server stops answering is given {@link PUBLISH_WAIT_MS}:
1940
+ * after it the publish rejects the same way. That rejection means the server did not confirm the
1941
+ * publish in time, not that it was not delivered: the command was already written to the socket
1942
+ * and Redis can still process it when it answers, so a message can arrive after its caller was
1943
+ * told it failed. The command also stays queued in the client until the server answers or the
1944
+ * connection drops; `commandTimeout` on the host's ioredis client is what rejects the command
1945
+ * itself.
1930
1946
  */
1931
1947
  publish(message: RealtimePubSubMessage): Promise<void>;
1932
1948
  /**
@@ -2157,6 +2173,30 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
2157
2173
  /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
2158
2174
  declare function describeError(reason: unknown): string;
2159
2175
 
2176
+ /**
2177
+ * @fileoverview Closing a Redis connection without waiting on a server that has stopped answering.
2178
+ * @layer infrastructure
2179
+ */
2180
+ /** The part of an ioredis client that closing a connection uses. */
2181
+ interface QuitableClient {
2182
+ quit(): Promise<unknown>;
2183
+ disconnect(): void;
2184
+ }
2185
+ /**
2186
+ * Quits `client`, waiting at most `ms` for the server to answer, and disconnects it when it did
2187
+ * not. QUIT is a command on the connection, so on a connection that no longer answers it never
2188
+ * settles and nothing in ioredis bounds it. A client whose QUIT was answered is already closed and
2189
+ * is left alone: disconnecting it again would arm ioredis's close timer on a socket that has no
2190
+ * close left to clear it.
2191
+ *
2192
+ * Never rejects: an error from QUIT (a connection that is already closed) is the same outcome as a
2193
+ * server that did not answer, and the connection is disconnected.
2194
+ *
2195
+ * @param client - The connection to close.
2196
+ * @param ms - How long to wait for the QUIT to be answered.
2197
+ */
2198
+ declare function quitWithin(client: QuitableClient, ms?: number): Promise<void>;
2199
+
2160
2200
  /**
2161
2201
  * @fileoverview Runs a consumer's lifecycle hook so that its failure is a value, never an exception.
2162
2202
  * @layer utils
@@ -2369,5 +2409,5 @@ declare const RESERVED_EVENT_NAMES: {
2369
2409
  /** Union of reserved event name values. */
2370
2410
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2371
2411
 
2372
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2373
- export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
2412
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2413
+ export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -216,11 +216,26 @@ function reportDeliveryFailure(logger, hooks, failure, what) {
216
216
  });
217
217
  }
218
218
 
219
+ // src/server/utils/windowed-report.ts
220
+ var REPORT_WINDOW_MS = 1e4;
221
+ function windowedReport(fresh, emit) {
222
+ let startedAt = Number.NEGATIVE_INFINITY;
223
+ let pending = fresh();
224
+ return (add) => {
225
+ pending = add(pending);
226
+ const now = performance.now();
227
+ if (now - startedAt < REPORT_WINDOW_MS) return;
228
+ startedAt = now;
229
+ const accumulated = pending;
230
+ pending = fresh();
231
+ emit(accumulated);
232
+ };
233
+ }
234
+
219
235
  // src/server/offline-queue/offline-queue-delivery.service.ts
220
236
  var RETRIEVE_LIMIT = 200;
221
237
  var DEFAULT_TIMEOUT_MS = 1e4;
222
238
  var DEFAULT_MAX_PENDING = 1e3;
223
- var REPORT_WINDOW_MS = 1e4;
224
239
  var OfflineQueueTimeoutError = class extends Error {
225
240
  constructor() {
226
241
  super("the offline queue did not answer in time");
@@ -239,8 +254,14 @@ var OfflineQueueDeliveryService = class {
239
254
  timeoutMs;
240
255
  maxPending;
241
256
  pending = 0;
242
- windowStartedAt = Number.NEGATIVE_INFINITY;
243
- timedOut = 0;
257
+ timeouts = windowedReport(
258
+ () => 0,
259
+ (count) => {
260
+ this.logger.warn(
261
+ `reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
262
+ );
263
+ }
264
+ );
244
265
  async retrieve(userId, lastEventId, ringBufferIds) {
245
266
  const { events } = await this.retrieveGap(userId, lastEventId);
246
267
  return events.filter((e) => !ringBufferIds.has(e.id));
@@ -316,15 +337,7 @@ var OfflineQueueDeliveryService = class {
316
337
  }
317
338
  }
318
339
  countTimeout() {
319
- this.timedOut += 1;
320
- const now = performance.now();
321
- if (now - this.windowStartedAt < REPORT_WINDOW_MS) return;
322
- this.windowStartedAt = now;
323
- const count = this.timedOut;
324
- this.timedOut = 0;
325
- this.logger.warn(
326
- `reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
327
- );
340
+ this.timeouts((count) => count + 1);
328
341
  }
329
342
  };
330
343
  OfflineQueueDeliveryService = __decorateClass([
@@ -457,7 +470,6 @@ function resolveClientAddress(request) {
457
470
  }
458
471
  return peerAddress(request.socket?.remoteAddress);
459
472
  }
460
- var REPORT_WINDOW_MS2 = 1e4;
461
473
  var AuthenticationUnavailableError = class extends Error {
462
474
  constructor(reason) {
463
475
  super(
@@ -478,8 +490,14 @@ var AuthenticationGate = class {
478
490
  maxPending;
479
491
  timeoutMs;
480
492
  pending = 0;
481
- windowStartedAt = Number.NEGATIVE_INFINITY;
482
- refused = { saturated: 0, timeout: 0 };
493
+ refusals = windowedReport(
494
+ () => ({ saturated: 0, timeout: 0 }),
495
+ ({ saturated, timeout }) => {
496
+ this.logger.warn(
497
+ `handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
498
+ );
499
+ }
500
+ );
483
501
  async authenticate(context) {
484
502
  if (this.pending >= this.maxPending) {
485
503
  this.refuse("saturated");
@@ -508,15 +526,7 @@ var AuthenticationGate = class {
508
526
  }
509
527
  }
510
528
  refuse(reason) {
511
- this.refused[reason] += 1;
512
- const now = performance.now();
513
- if (now - this.windowStartedAt < REPORT_WINDOW_MS2) return;
514
- this.windowStartedAt = now;
515
- const { saturated, timeout } = this.refused;
516
- this.refused = { saturated: 0, timeout: 0 };
517
- this.logger.warn(
518
- `handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
519
- );
529
+ this.refusals((refused) => ({ ...refused, [reason]: refused[reason] + 1 }));
520
530
  }
521
531
  };
522
532
  AuthenticationGate = __decorateClass([
@@ -594,7 +604,6 @@ ConnectionRegistry = __decorateClass([
594
604
  var DEFAULT_AUTHENTICATE_TIMEOUT_MS = 1e4;
595
605
  var DEFAULT_MAX_CONNECTIONS = 1e4;
596
606
  var HOLD_MARGIN_MS = 5e3;
597
- var REPORT_WINDOW_MS3 = 1e4;
598
607
  var ConnectionLimitError = class extends Error {
599
608
  constructor(limit) {
600
609
  super(`the instance already holds ${limit} connections`);
@@ -617,8 +626,14 @@ var ConnectionAdmission = class {
617
626
  max;
618
627
  holdMs;
619
628
  held = /* @__PURE__ */ new Map();
620
- windowStartedAt = Number.NEGATIVE_INFINITY;
621
- refused = 0;
629
+ refusals = windowedReport(
630
+ () => 0,
631
+ (count) => {
632
+ this.logger.warn(
633
+ `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
634
+ );
635
+ }
636
+ );
622
637
  admit() {
623
638
  const place = /* @__PURE__ */ Symbol("place");
624
639
  this.take(place);
@@ -650,15 +665,7 @@ var ConnectionAdmission = class {
650
665
  }
651
666
  }
652
667
  refuse() {
653
- this.refused += 1;
654
- const now = performance.now();
655
- if (now - this.windowStartedAt < REPORT_WINDOW_MS3) return;
656
- this.windowStartedAt = now;
657
- const count = this.refused;
658
- this.refused = 0;
659
- this.logger.warn(
660
- `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
661
- );
668
+ this.refusals((count) => count + 1);
662
669
  }
663
670
  };
664
671
  ConnectionAdmission = __decorateClass([
@@ -2133,9 +2140,17 @@ var RealtimePubSubSubscriber = class {
2133
2140
  this.unsubscribe = null;
2134
2141
  }
2135
2142
  }
2143
+ dropped = windowedReport(
2144
+ () => ({ count: 0, last: "none" }),
2145
+ ({ count, last }) => {
2146
+ this.logger.warn(
2147
+ `Pub/sub dropped ${count} message(s) it could not act on since the last report (last: ${last})`
2148
+ );
2149
+ }
2150
+ );
2136
2151
  handle(msg) {
2137
- if (msg.origin === this.instanceId) return;
2138
2152
  try {
2153
+ if (msg.origin === this.instanceId) return;
2139
2154
  switch (msg.op) {
2140
2155
  case "emitToUser": {
2141
2156
  const a = msg.args;
@@ -2169,14 +2184,17 @@ var RealtimePubSubSubscriber = class {
2169
2184
  break;
2170
2185
  }
2171
2186
  default: {
2172
- const exhaustive = msg.op;
2173
- this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
2187
+ msg.op;
2188
+ this.drop("unknown op");
2174
2189
  }
2175
2190
  }
2176
2191
  } catch (err) {
2177
- this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
2192
+ this.drop(String(Object(err).constructor?.name ?? "Error"));
2178
2193
  }
2179
2194
  }
2195
+ drop(last) {
2196
+ this.dropped(({ count }) => ({ count: count + 1, last }));
2197
+ }
2180
2198
  };
2181
2199
  RealtimePubSubSubscriber = __decorateClass([
2182
2200
  Injectable(),
@@ -2230,6 +2248,31 @@ BymaxRealtimeModule = __decorateClass([
2230
2248
  Global(),
2231
2249
  Module({})
2232
2250
  ], BymaxRealtimeModule);
2251
+
2252
+ // src/server/utils/quit-within.ts
2253
+ var QUIT_WAIT_MS = 2e3;
2254
+ async function quitWithin(client, ms = QUIT_WAIT_MS) {
2255
+ let timer;
2256
+ const bound = new Promise((resolve) => {
2257
+ timer = setTimeout(resolve, ms);
2258
+ timer.unref();
2259
+ });
2260
+ let answered = false;
2261
+ const quit = client.quit().then(
2262
+ () => {
2263
+ answered = true;
2264
+ },
2265
+ () => void 0
2266
+ );
2267
+ try {
2268
+ await Promise.race([quit, bound]);
2269
+ if (!answered) client.disconnect();
2270
+ } finally {
2271
+ clearTimeout(timer);
2272
+ }
2273
+ }
2274
+
2275
+ // src/server/pubsub/redis-realtime-pubsub.ts
2233
2276
  var MALFORMED_REPORT_INTERVAL_MS = 6e4;
2234
2277
  var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
2235
2278
  "wait",
@@ -2240,6 +2283,7 @@ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
2240
2283
  "end"
2241
2284
  ]);
2242
2285
  var PUBLISHER_WAIT_MS = 2e3;
2286
+ var PUBLISH_WAIT_MS = 2e3;
2243
2287
  var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
2244
2288
  function connectionReason(err) {
2245
2289
  const code = err?.code;
@@ -2271,7 +2315,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2271
2315
  this.connectLazyClient();
2272
2316
  throw this.cannotPublish(`the Redis client is ${status}`);
2273
2317
  }
2274
- await this.#pub.publish(this.channel, JSON.stringify(message));
2318
+ const sent = this.#pub.publish(this.channel, JSON.stringify(message));
2319
+ let timer;
2320
+ const expired = new Promise((_resolve, reject) => {
2321
+ timer = setTimeout(
2322
+ () => reject(this.cannotPublish(`the server did not answer within ${PUBLISH_WAIT_MS} ms`)),
2323
+ PUBLISH_WAIT_MS
2324
+ );
2325
+ timer.unref();
2326
+ });
2327
+ try {
2328
+ await Promise.race([sent, expired]);
2329
+ } finally {
2330
+ clearTimeout(timer);
2331
+ }
2275
2332
  }
2276
2333
  connectLazyClient() {
2277
2334
  if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
@@ -2317,7 +2374,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2317
2374
  const connected = this.#subscribed;
2318
2375
  this.#subscribed = false;
2319
2376
  try {
2320
- if (connected) await sub.quit();
2377
+ if (connected) await quitWithin(sub);
2321
2378
  else sub.disconnect();
2322
2379
  } catch {
2323
2380
  }
@@ -2430,7 +2487,12 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2430
2487
  dispatch(payload) {
2431
2488
  let msg;
2432
2489
  try {
2433
- msg = JSON.parse(payload);
2490
+ const parsed = JSON.parse(payload);
2491
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2492
+ this.reportMalformed();
2493
+ return;
2494
+ }
2495
+ msg = parsed;
2434
2496
  } catch {
2435
2497
  this.reportMalformed();
2436
2498
  return;
@@ -2507,4 +2569,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2507
2569
  }
2508
2570
  };
2509
2571
 
2510
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
2572
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, reportDeliveryFailure, resolveAuthTenant, runHook, sseWiring, unavailableError };
@@ -313,6 +313,7 @@ exports.CompositeTransport = __decorateClass([
313
313
  __decorateParam(0, common.Inject(internal.SseTransport)),
314
314
  __decorateParam(1, common.Inject(exports.WebSocketTransport))
315
315
  ], exports.CompositeTransport);
316
+ var ADAPTER_COMMANDS = ["subscribe", "psubscribe", "unsubscribe", "punsubscribe"];
316
317
  var realtimeServers = /* @__PURE__ */ new WeakSet();
317
318
  function isRealtimeIoServer(server) {
318
319
  return typeof server === "object" && server !== null && realtimeServers.has(server);
@@ -320,6 +321,7 @@ function isRealtimeIoServer(server) {
320
321
  var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
321
322
  adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
322
323
  options;
324
+ subscribers = /* @__PURE__ */ new Set();
323
325
  constructor(app) {
324
326
  super(app);
325
327
  this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
@@ -355,13 +357,47 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
355
357
  realtimeServers.add(server);
356
358
  return server;
357
359
  }
360
+ async dispose() {
361
+ await super.dispose();
362
+ const closing = [...this.subscribers].map((sub) => internal.quitWithin(sub));
363
+ this.subscribers.clear();
364
+ await Promise.allSettled(closing);
365
+ }
366
+ guardCommands(sub) {
367
+ const commands = sub;
368
+ let reported = false;
369
+ for (const name of ADAPTER_COMMANDS) {
370
+ const original = commands[name];
371
+ if (original === void 0) continue;
372
+ commands[name] = (...args) => {
373
+ const pending = original.apply(sub, args);
374
+ Promise.resolve(pending).catch((err) => {
375
+ if (reported) return;
376
+ reported = true;
377
+ const kind = Object(err).constructor?.name ?? "Error";
378
+ this.adapterLogger.warn(`Redis adapter subscriber command failed (${kind})`);
379
+ });
380
+ return pending;
381
+ };
382
+ }
383
+ }
358
384
  installRedisAdapter(server, pubClient) {
385
+ let sub;
359
386
  try {
360
387
  const { createAdapter } = __require("@socket.io/redis-adapter");
361
388
  const pub = pubClient;
362
- const sub = pub.duplicate();
389
+ sub = pub.duplicate({ disconnectTimeout: 1 });
390
+ this.subscribers.add(sub);
391
+ this.guardCommands(sub);
363
392
  server.adapter(createAdapter(pub, sub));
364
393
  } catch (err) {
394
+ if (sub !== void 0) {
395
+ this.subscribers.delete(sub);
396
+ try {
397
+ sub.disconnect();
398
+ } catch {
399
+ }
400
+ }
365
401
  const reason = internal.describeError(err);
366
402
  throw internal.realtimeError(
367
403
  internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
@@ -367,6 +367,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
367
367
  declare class RealtimeIoAdapter extends IoAdapter {
368
368
  private readonly adapterLogger;
369
369
  private readonly options;
370
+ /** The subscriber connections this adapter opened for the Redis adapter, closed with it. */
371
+ private readonly subscribers;
370
372
  constructor(app: INestApplicationContext);
371
373
  /**
372
374
  * Bind the gateway to `websocket.namespace` when configured.
@@ -390,6 +392,25 @@ declare class RealtimeIoAdapter extends IoAdapter {
390
392
  * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
391
393
  */
392
394
  createIOServer(port: number, opts?: ServerOptions): unknown;
395
+ /**
396
+ * Closes the subscriber connections this adapter opened, after Nest has closed every server.
397
+ *
398
+ * The caller's `pubClient` is not touched: it belongs to the caller. Each connection is quit with
399
+ * a bound, and all of them at once, so a Redis that stopped answering costs one bound and not one
400
+ * per connection.
401
+ */
402
+ dispose(): Promise<void>;
403
+ /**
404
+ * Handles the rejection of the subscriber commands the Socket.IO Redis adapter sends and never
405
+ * awaits. Its `subscribe` at boot and its `unsubscribe` at close discard their promises, so a
406
+ * command that fails, as every pending one does when the connection is closed or gives up,
407
+ * would be an unhandled rejection that ends the process.
408
+ *
409
+ * Each command still returns its own promise, so anything that awaits it sees the rejection; a
410
+ * handler is attached beside it. The failure is logged once per connection, by its class only: the
411
+ * message of a connection error can carry the host or a credential.
412
+ */
413
+ private guardCommands;
393
414
  /**
394
415
  * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
395
416
  * silent single-instance server drops cross-node messages. An unreachable Redis
@@ -367,6 +367,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
367
367
  declare class RealtimeIoAdapter extends IoAdapter {
368
368
  private readonly adapterLogger;
369
369
  private readonly options;
370
+ /** The subscriber connections this adapter opened for the Redis adapter, closed with it. */
371
+ private readonly subscribers;
370
372
  constructor(app: INestApplicationContext);
371
373
  /**
372
374
  * Bind the gateway to `websocket.namespace` when configured.
@@ -390,6 +392,25 @@ declare class RealtimeIoAdapter extends IoAdapter {
390
392
  * `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
391
393
  */
392
394
  createIOServer(port: number, opts?: ServerOptions): unknown;
395
+ /**
396
+ * Closes the subscriber connections this adapter opened, after Nest has closed every server.
397
+ *
398
+ * The caller's `pubClient` is not touched: it belongs to the caller. Each connection is quit with
399
+ * a bound, and all of them at once, so a Redis that stopped answering costs one bound and not one
400
+ * per connection.
401
+ */
402
+ dispose(): Promise<void>;
403
+ /**
404
+ * Handles the rejection of the subscriber commands the Socket.IO Redis adapter sends and never
405
+ * awaits. Its `subscribe` at boot and its `unsubscribe` at close discard their promises, so a
406
+ * command that fails, as every pending one does when the connection is closed or gives up,
407
+ * would be an unhandled rejection that ends the process.
408
+ *
409
+ * Each command still returns its own promise, so anything that awaits it sees the rejection; a
410
+ * handler is attached beside it. The failure is logged once per connection, by its class only: the
411
+ * message of a connection error can carry the host or a credential.
412
+ */
413
+ private guardCommands;
393
414
  /**
394
415
  * Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
395
416
  * silent single-instance server drops cross-node messages. An unreachable Redis
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { Injectable, Inject, Optional, Logger, Global, Module } from '@nestjs/common';
3
- import { ConnectionRegistry, RoomRegistry, AuthenticationGate, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, ConnectionAdmission, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, runHook, DEFAULT_HOOK_TIMEOUT_MS, describeError, unavailableError, UNBOUNDED_TICKET, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, admitRooms, AuthenticationUnavailableError, ConnectionLimitError, parseCookieHeader, RESERVED_EVENT_NAMES, realtimeError } from '@bymax-one/nest-realtime/internal';
3
+ import { ConnectionRegistry, RoomRegistry, AuthenticationGate, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, ConnectionAdmission, SseTransport, REALTIME_ERROR_CODES, ROOM_PREFIXES, runHook, DEFAULT_HOOK_TIMEOUT_MS, describeError, unavailableError, UNBOUNDED_TICKET, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, admitRooms, AuthenticationUnavailableError, ConnectionLimitError, parseCookieHeader, RESERVED_EVENT_NAMES, quitWithin, realtimeError } from '@bymax-one/nest-realtime/internal';
4
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
5
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
6
6
 
@@ -313,6 +313,7 @@ CompositeTransport = __decorateClass([
313
313
  __decorateParam(0, Inject(SseTransport)),
314
314
  __decorateParam(1, Inject(WebSocketTransport))
315
315
  ], CompositeTransport);
316
+ var ADAPTER_COMMANDS = ["subscribe", "psubscribe", "unsubscribe", "punsubscribe"];
316
317
  var realtimeServers = /* @__PURE__ */ new WeakSet();
317
318
  function isRealtimeIoServer(server) {
318
319
  return typeof server === "object" && server !== null && realtimeServers.has(server);
@@ -320,6 +321,7 @@ function isRealtimeIoServer(server) {
320
321
  var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
321
322
  adapterLogger = new Logger(_RealtimeIoAdapter.name);
322
323
  options;
324
+ subscribers = /* @__PURE__ */ new Set();
323
325
  constructor(app) {
324
326
  super(app);
325
327
  this.options = app.get(REALTIME_OPTIONS_TOKEN);
@@ -355,13 +357,47 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
355
357
  realtimeServers.add(server);
356
358
  return server;
357
359
  }
360
+ async dispose() {
361
+ await super.dispose();
362
+ const closing = [...this.subscribers].map((sub) => quitWithin(sub));
363
+ this.subscribers.clear();
364
+ await Promise.allSettled(closing);
365
+ }
366
+ guardCommands(sub) {
367
+ const commands = sub;
368
+ let reported = false;
369
+ for (const name of ADAPTER_COMMANDS) {
370
+ const original = commands[name];
371
+ if (original === void 0) continue;
372
+ commands[name] = (...args) => {
373
+ const pending = original.apply(sub, args);
374
+ Promise.resolve(pending).catch((err) => {
375
+ if (reported) return;
376
+ reported = true;
377
+ const kind = Object(err).constructor?.name ?? "Error";
378
+ this.adapterLogger.warn(`Redis adapter subscriber command failed (${kind})`);
379
+ });
380
+ return pending;
381
+ };
382
+ }
383
+ }
358
384
  installRedisAdapter(server, pubClient) {
385
+ let sub;
359
386
  try {
360
387
  const { createAdapter } = __require("@socket.io/redis-adapter");
361
388
  const pub = pubClient;
362
- const sub = pub.duplicate();
389
+ sub = pub.duplicate({ disconnectTimeout: 1 });
390
+ this.subscribers.add(sub);
391
+ this.guardCommands(sub);
363
392
  server.adapter(createAdapter(pub, sub));
364
393
  } catch (err) {
394
+ if (sub !== void 0) {
395
+ this.subscribers.delete(sub);
396
+ try {
397
+ sub.disconnect();
398
+ } catch {
399
+ }
400
+ }
365
401
  const reason = describeError(err);
366
402
  throw realtimeError(
367
403
  REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.14",
3
+ "version": "1.2.16",
4
4
  "description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -97,18 +97,20 @@
97
97
  "check:exports": "attw --pack . --profile strict",
98
98
  "check:mutants": "node scripts/check-mutation-directives.mjs",
99
99
  "check:file-length": "node scripts/check-file-length.mjs",
100
+ "check:spec-headers": "node scripts/check-spec-headers.mjs",
101
+ "check:suppressions": "node scripts/check-suppressions-baseline.mjs",
100
102
  "check:api": "node scripts/check-api-surface.mjs",
101
103
  "check:published": "node scripts/check-published-surface.mjs",
102
104
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
103
105
  "benchmark": "node scripts/benchmark/run.mjs",
104
106
  "check:surface": "node scripts/check-public-surface.mjs",
105
107
  "clean": "rm -rf dist coverage",
106
- "lint": "eslint src",
108
+ "lint": "eslint src && pnpm check:spec-headers && pnpm check:suppressions",
107
109
  "lint:fix": "eslint src --fix",
108
110
  "mutation": "stryker run",
109
111
  "mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
110
112
  "mutation:dry-run": "stryker run --dryRunOnly",
111
- "prepublishOnly": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:file-length && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm check:runtime",
113
+ "prepublishOnly": "pnpm verify && pnpm check:runtime",
112
114
  "release": "npm publish --provenance --access public",
113
115
  "size": "node scripts/check-size.mjs",
114
116
  "test": "jest",
@@ -118,6 +120,7 @@
118
120
  "test:e2e": "jest --config jest.e2e.config.ts",
119
121
  "test:e2e:cross-instance": "jest --config jest.e2e.cross-instance.config.ts --runInBand",
120
122
  "test:watch": "jest --watch",
123
+ "verify": "pnpm clean && pnpm typecheck && pnpm lint && pnpm check:mutants && pnpm check:file-length && pnpm test:cov:all && pnpm build && pnpm check:published && pnpm check:surface && pnpm size && pnpm check:api",
121
124
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.server.json"
122
125
  },
123
126
  "peerDependencies": {