@bymax-one/nest-realtime 1.2.14 → 1.2.15
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 +13 -3
- package/README.md +1 -1
- package/dist/internal/index.cjs +27 -1
- package/dist/internal/index.d.cts +26 -2
- package/dist/internal/index.d.ts +26 -2
- package/dist/internal/index.mjs +27 -2
- package/dist/websocket/index.cjs +37 -1
- package/dist/websocket/index.d.cts +21 -0
- package/dist/websocket/index.d.ts +21 -0
- package/dist/websocket/index.mjs +38 -2
- package/package.json +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.2.15] - 2026-11-14
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- **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.
|
|
15
|
+
- **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.
|
|
16
|
+
|
|
17
|
+
#### Apply to a derived backend
|
|
18
|
+
|
|
19
|
+
`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.
|
|
20
|
+
|
|
10
21
|
## [1.2.14] - 2026-11-14
|
|
11
22
|
|
|
12
23
|
### Security
|
|
@@ -45,8 +56,6 @@ A `revalidate` that does not return `true` on every path now disconnects the con
|
|
|
45
56
|
|
|
46
57
|
- **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
58
|
|
|
48
|
-
### Security
|
|
49
|
-
|
|
50
59
|
- **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
60
|
|
|
52
61
|
#### Apply to a derived backend
|
|
@@ -1085,7 +1094,8 @@ First published release.
|
|
|
1085
1094
|
rather than by the manual sweep that raised the NestJS floors — that sweep
|
|
1086
1095
|
asked about NestJS and never put the same question to the other ten peers.
|
|
1087
1096
|
|
|
1088
|
-
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.
|
|
1097
|
+
[Unreleased]: https://github.com/bymaxone/nest-realtime/compare/v1.2.15...HEAD
|
|
1098
|
+
[1.2.15]: https://github.com/bymaxone/nest-realtime/compare/v1.2.14...v1.2.15
|
|
1089
1099
|
[1.2.14]: https://github.com/bymaxone/nest-realtime/compare/v1.2.13...v1.2.14
|
|
1090
1100
|
[1.2.13]: https://github.com/bymaxone/nest-realtime/compare/v1.2.12...v1.2.13
|
|
1091
1101
|
[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
|
|
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
|
|
package/dist/internal/index.cjs
CHANGED
|
@@ -2232,6 +2232,31 @@ exports.BymaxRealtimeModule = __decorateClass([
|
|
|
2232
2232
|
common.Global(),
|
|
2233
2233
|
common.Module({})
|
|
2234
2234
|
], exports.BymaxRealtimeModule);
|
|
2235
|
+
|
|
2236
|
+
// src/server/utils/quit-within.ts
|
|
2237
|
+
var QUIT_WAIT_MS = 2e3;
|
|
2238
|
+
async function quitWithin(client, ms = QUIT_WAIT_MS) {
|
|
2239
|
+
let timer;
|
|
2240
|
+
const bound = new Promise((resolve) => {
|
|
2241
|
+
timer = setTimeout(resolve, ms);
|
|
2242
|
+
timer.unref();
|
|
2243
|
+
});
|
|
2244
|
+
let answered = false;
|
|
2245
|
+
const quit = client.quit().then(
|
|
2246
|
+
() => {
|
|
2247
|
+
answered = true;
|
|
2248
|
+
},
|
|
2249
|
+
() => void 0
|
|
2250
|
+
);
|
|
2251
|
+
try {
|
|
2252
|
+
await Promise.race([quit, bound]);
|
|
2253
|
+
if (!answered) client.disconnect();
|
|
2254
|
+
} finally {
|
|
2255
|
+
clearTimeout(timer);
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
|
|
2259
|
+
// src/server/pubsub/redis-realtime-pubsub.ts
|
|
2235
2260
|
var MALFORMED_REPORT_INTERVAL_MS = 6e4;
|
|
2236
2261
|
var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
|
|
2237
2262
|
"wait",
|
|
@@ -2319,7 +2344,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2319
2344
|
const connected = this.#subscribed;
|
|
2320
2345
|
this.#subscribed = false;
|
|
2321
2346
|
try {
|
|
2322
|
-
if (connected) await sub
|
|
2347
|
+
if (connected) await quitWithin(sub);
|
|
2323
2348
|
else sub.disconnect();
|
|
2324
2349
|
} catch {
|
|
2325
2350
|
}
|
|
@@ -2535,6 +2560,7 @@ exports.composeRoomId = composeRoomId;
|
|
|
2535
2560
|
exports.createSseController = createSseController;
|
|
2536
2561
|
exports.describeError = describeError;
|
|
2537
2562
|
exports.parseCookieHeader = parseCookieHeader;
|
|
2563
|
+
exports.quitWithin = quitWithin;
|
|
2538
2564
|
exports.realtimeError = realtimeError;
|
|
2539
2565
|
exports.reportDeliveryFailure = reportDeliveryFailure;
|
|
2540
2566
|
exports.resolveAuthTenant = resolveAuthTenant;
|
|
@@ -2157,6 +2157,30 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
|
|
|
2157
2157
|
/** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
|
|
2158
2158
|
declare function describeError(reason: unknown): string;
|
|
2159
2159
|
|
|
2160
|
+
/**
|
|
2161
|
+
* @fileoverview Closing a Redis connection without waiting on a server that has stopped answering.
|
|
2162
|
+
* @layer infrastructure
|
|
2163
|
+
*/
|
|
2164
|
+
/** The part of an ioredis client that closing a connection uses. */
|
|
2165
|
+
interface QuitableClient {
|
|
2166
|
+
quit(): Promise<unknown>;
|
|
2167
|
+
disconnect(): void;
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Quits `client`, waiting at most `ms` for the server to answer, and disconnects it when it did
|
|
2171
|
+
* not. QUIT is a command on the connection, so on a connection that no longer answers it never
|
|
2172
|
+
* settles and nothing in ioredis bounds it. A client whose QUIT was answered is already closed and
|
|
2173
|
+
* is left alone: disconnecting it again would arm ioredis's close timer on a socket that has no
|
|
2174
|
+
* close left to clear it.
|
|
2175
|
+
*
|
|
2176
|
+
* Never rejects: an error from QUIT (a connection that is already closed) is the same outcome as a
|
|
2177
|
+
* server that did not answer, and the connection is disconnected.
|
|
2178
|
+
*
|
|
2179
|
+
* @param client - The connection to close.
|
|
2180
|
+
* @param ms - How long to wait for the QUIT to be answered.
|
|
2181
|
+
*/
|
|
2182
|
+
declare function quitWithin(client: QuitableClient, ms?: number): Promise<void>;
|
|
2183
|
+
|
|
2160
2184
|
/**
|
|
2161
2185
|
* @fileoverview Runs a consumer's lifecycle hook so that its failure is a value, never an exception.
|
|
2162
2186
|
* @layer utils
|
|
@@ -2369,5 +2393,5 @@ declare const RESERVED_EVENT_NAMES: {
|
|
|
2369
2393
|
/** Union of reserved event name values. */
|
|
2370
2394
|
type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
|
|
2371
2395
|
|
|
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 };
|
|
2396
|
+
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 };
|
|
2397
|
+
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 };
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -2157,6 +2157,30 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
|
|
|
2157
2157
|
/** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
|
|
2158
2158
|
declare function describeError(reason: unknown): string;
|
|
2159
2159
|
|
|
2160
|
+
/**
|
|
2161
|
+
* @fileoverview Closing a Redis connection without waiting on a server that has stopped answering.
|
|
2162
|
+
* @layer infrastructure
|
|
2163
|
+
*/
|
|
2164
|
+
/** The part of an ioredis client that closing a connection uses. */
|
|
2165
|
+
interface QuitableClient {
|
|
2166
|
+
quit(): Promise<unknown>;
|
|
2167
|
+
disconnect(): void;
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Quits `client`, waiting at most `ms` for the server to answer, and disconnects it when it did
|
|
2171
|
+
* not. QUIT is a command on the connection, so on a connection that no longer answers it never
|
|
2172
|
+
* settles and nothing in ioredis bounds it. A client whose QUIT was answered is already closed and
|
|
2173
|
+
* is left alone: disconnecting it again would arm ioredis's close timer on a socket that has no
|
|
2174
|
+
* close left to clear it.
|
|
2175
|
+
*
|
|
2176
|
+
* Never rejects: an error from QUIT (a connection that is already closed) is the same outcome as a
|
|
2177
|
+
* server that did not answer, and the connection is disconnected.
|
|
2178
|
+
*
|
|
2179
|
+
* @param client - The connection to close.
|
|
2180
|
+
* @param ms - How long to wait for the QUIT to be answered.
|
|
2181
|
+
*/
|
|
2182
|
+
declare function quitWithin(client: QuitableClient, ms?: number): Promise<void>;
|
|
2183
|
+
|
|
2160
2184
|
/**
|
|
2161
2185
|
* @fileoverview Runs a consumer's lifecycle hook so that its failure is a value, never an exception.
|
|
2162
2186
|
* @layer utils
|
|
@@ -2369,5 +2393,5 @@ declare const RESERVED_EVENT_NAMES: {
|
|
|
2369
2393
|
/** Union of reserved event name values. */
|
|
2370
2394
|
type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
|
|
2371
2395
|
|
|
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 };
|
|
2396
|
+
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 };
|
|
2397
|
+
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 };
|
package/dist/internal/index.mjs
CHANGED
|
@@ -2230,6 +2230,31 @@ BymaxRealtimeModule = __decorateClass([
|
|
|
2230
2230
|
Global(),
|
|
2231
2231
|
Module({})
|
|
2232
2232
|
], BymaxRealtimeModule);
|
|
2233
|
+
|
|
2234
|
+
// src/server/utils/quit-within.ts
|
|
2235
|
+
var QUIT_WAIT_MS = 2e3;
|
|
2236
|
+
async function quitWithin(client, ms = QUIT_WAIT_MS) {
|
|
2237
|
+
let timer;
|
|
2238
|
+
const bound = new Promise((resolve) => {
|
|
2239
|
+
timer = setTimeout(resolve, ms);
|
|
2240
|
+
timer.unref();
|
|
2241
|
+
});
|
|
2242
|
+
let answered = false;
|
|
2243
|
+
const quit = client.quit().then(
|
|
2244
|
+
() => {
|
|
2245
|
+
answered = true;
|
|
2246
|
+
},
|
|
2247
|
+
() => void 0
|
|
2248
|
+
);
|
|
2249
|
+
try {
|
|
2250
|
+
await Promise.race([quit, bound]);
|
|
2251
|
+
if (!answered) client.disconnect();
|
|
2252
|
+
} finally {
|
|
2253
|
+
clearTimeout(timer);
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
// src/server/pubsub/redis-realtime-pubsub.ts
|
|
2233
2258
|
var MALFORMED_REPORT_INTERVAL_MS = 6e4;
|
|
2234
2259
|
var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
|
|
2235
2260
|
"wait",
|
|
@@ -2317,7 +2342,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2317
2342
|
const connected = this.#subscribed;
|
|
2318
2343
|
this.#subscribed = false;
|
|
2319
2344
|
try {
|
|
2320
|
-
if (connected) await sub
|
|
2345
|
+
if (connected) await quitWithin(sub);
|
|
2321
2346
|
else sub.disconnect();
|
|
2322
2347
|
} catch {
|
|
2323
2348
|
}
|
|
@@ -2507,4 +2532,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2507
2532
|
}
|
|
2508
2533
|
};
|
|
2509
2534
|
|
|
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 };
|
|
2535
|
+
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 };
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -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
|
-
|
|
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
|
package/dist/websocket/index.mjs
CHANGED
|
@@ -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
|
-
|
|
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.
|
|
3
|
+
"version": "1.2.15",
|
|
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",
|
|
@@ -108,7 +108,7 @@
|
|
|
108
108
|
"mutation": "stryker run",
|
|
109
109
|
"mutation:full": "node -e \"require('node:fs').rmSync('reports/stryker-incremental.json',{force:true,recursive:true})\" && stryker run",
|
|
110
110
|
"mutation:dry-run": "stryker run --dryRunOnly",
|
|
111
|
-
"prepublishOnly": "pnpm
|
|
111
|
+
"prepublishOnly": "pnpm verify && pnpm check:runtime",
|
|
112
112
|
"release": "npm publish --provenance --access public",
|
|
113
113
|
"size": "node scripts/check-size.mjs",
|
|
114
114
|
"test": "jest",
|
|
@@ -118,6 +118,7 @@
|
|
|
118
118
|
"test:e2e": "jest --config jest.e2e.config.ts",
|
|
119
119
|
"test:e2e:cross-instance": "jest --config jest.e2e.cross-instance.config.ts --runInBand",
|
|
120
120
|
"test:watch": "jest --watch",
|
|
121
|
+
"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
122
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.server.json"
|
|
122
123
|
},
|
|
123
124
|
"peerDependencies": {
|