@bymax-one/nest-realtime 1.2.13 → 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.
@@ -1,4 +1,4 @@
1
- import { ModuleMetadata, Type, Abstract, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown } from '@nestjs/common';
1
+ import { ModuleMetadata, Type, Abstract, Provider, Logger, DynamicModule, MessageEvent, OnModuleInit, OnApplicationShutdown, ServiceUnavailableException } from '@nestjs/common';
2
2
  import { Subject, Observable } from 'rxjs';
3
3
  import { Redis } from 'ioredis';
4
4
 
@@ -133,6 +133,16 @@ interface AuthenticationResult {
133
133
  */
134
134
  readonly metadata?: Record<string, unknown>;
135
135
  }
136
+ /** What `IConnectionAuthenticator.authenticate` and `revalidate` are handed besides their subject. */
137
+ interface AuthenticatorCallOptions {
138
+ /**
139
+ * Aborted when the call has not settled in time: `authenticateTimeoutMs` for `authenticate`, after
140
+ * which the handshake is refused, and `reauthenticationPolicy.revalidateTimeoutMs` for
141
+ * `revalidate`, after which the connection is disconnected, whatever the call returns later. Pass
142
+ * it to the work behind the call so that it stops.
143
+ */
144
+ readonly signal: AbortSignal;
145
+ }
136
146
  /**
137
147
  * Connection authenticator contract — the only auth surface the library owns.
138
148
  *
@@ -166,14 +176,19 @@ interface IConnectionAuthenticator {
166
176
  * because the credentials were accepted and the fault is in this method. Return
167
177
  * `null` to reject a client.
168
178
  */
169
- authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
179
+ authenticate(context: ConnectionAuthContext, options?: AuthenticatorCallOptions): Promise<AuthenticationResult | null>;
170
180
  /**
171
181
  * Optionally re-validate during long sessions. Called periodically based on
172
182
  * `reauthenticationPolicy.intervalSeconds`.
173
183
  *
174
- * @returns `true` to keep the connection alive, `false` to disconnect.
184
+ * A call that has not settled within `reauthenticationPolicy.revalidateTimeoutMs` is treated as
185
+ * one that threw: the connection is disconnected, not kept, whatever the call returns later.
186
+ * Pass `options.signal` to the work behind it (a `fetch`, a query) so that it stops then too.
187
+ *
188
+ * @returns `true` to keep the connection alive. `false` disconnects it, and so does anything
189
+ * else (including no return value): only an explicit `true` keeps it.
175
190
  */
176
- revalidate?(connectionId: string, originalAuth: AuthenticationResult): Promise<boolean>;
191
+ revalidate?(connectionId: string, originalAuth: AuthenticationResult, options?: AuthenticatorCallOptions): Promise<boolean>;
177
192
  }
178
193
 
179
194
  /**
@@ -187,6 +202,8 @@ interface IConnectionAuthenticator {
187
202
  * `TOO_MANY_CONNECTIONS` signals FIFO eviction: when a user exceeds
188
203
  * `maxConnectionsPerUser`, the OLDEST connection is evicted (closed with this
189
204
  * code) and the new one is admitted — it is never an HTTP 429 rejection.
205
+ * `SLOW_CONSUMER` is the reason an SSE connection is closed when the client does not read
206
+ * what is sent to it.
190
207
  */
191
208
  declare const REALTIME_ERROR_CODES: {
192
209
  readonly INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS";
@@ -194,6 +211,7 @@ declare const REALTIME_ERROR_CODES: {
194
211
  readonly AUTH_FAILED: "REALTIME_AUTH_FAILED";
195
212
  readonly REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED";
196
213
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
214
+ readonly SLOW_CONSUMER: "REALTIME_SLOW_CONSUMER";
197
215
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
198
216
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
199
217
  readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
@@ -410,6 +428,11 @@ interface SseOptions {
410
428
  replayBufferSize?: number;
411
429
  maxConnectionsPerUser?: number;
412
430
  emitConnectionEvent?: boolean;
431
+ replayTtlMs?: number;
432
+ replayMaxIdleUsers?: number;
433
+ maxQueuedBytes?: number;
434
+ maxQueuedEvents?: number;
435
+ stallHeartbeats?: number;
413
436
  }
414
437
  /** WebSocket-transport-specific options. */
415
438
  interface WebSocketOptions {
@@ -418,6 +441,10 @@ interface WebSocketOptions {
418
441
  maxHttpBufferSize?: number;
419
442
  pingIntervalMs?: number;
420
443
  pingTimeoutMs?: number;
444
+ /**
445
+ * Connections one user may hold at once; beyond it the OLDEST is closed. Defaults to `5`,
446
+ * the SSE default. `0` switches the bound off.
447
+ */
421
448
  maxConnectionsPerUser?: number;
422
449
  /**
423
450
  * Emit a `connection:established` event to the client immediately after a
@@ -441,6 +468,8 @@ interface ReauthenticationPolicy {
441
468
  intervalSeconds?: number;
442
469
  onFailure?: 'disconnect' | 'event';
443
470
  cacheTtlMs?: number;
471
+ revalidateTimeoutMs?: number;
472
+ concurrency?: number;
444
473
  }
445
474
  /** Synchronous module configuration. */
446
475
  interface BymaxRealtimeModuleOptions {
@@ -458,6 +487,16 @@ interface BymaxRealtimeModuleOptions {
458
487
  */
459
488
  tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
460
489
  hooks?: IConnectionLifecycleHooks;
490
+ hookTimeoutMs?: number;
491
+ authenticateTimeoutMs?: number;
492
+ maxPendingHandshakes?: number;
493
+ /**
494
+ * Connections one instance holds at once, both transports together. A handshake that arrives
495
+ * when the instance already holds this many is refused before the authenticator is asked: a
496
+ * `503` on SSE, a generic `connect_error` on WebSocket. An integer of 1 or more; defaults to
497
+ * `10000`. Keep it below the process's file-descriptor limit.
498
+ */
499
+ maxConnections?: number;
461
500
  pubsub?: IRealtimePubSub;
462
501
  offlineQueue?: IOfflineQueueStorage;
463
502
  presence?: IPresenceStorage;
@@ -704,6 +743,8 @@ declare const REALTIME_OFFLINE_QUEUE_TOKEN: unique symbol;
704
743
  declare const REALTIME_PRESENCE_TOKEN: unique symbol;
705
744
  declare const REALTIME_HOOKS_TOKEN: unique symbol;
706
745
  declare const REALTIME_INSTANCE_ID_TOKEN: unique symbol;
746
+ /** How long the library waits for a lifecycle hook it awaits before giving up on it. */
747
+ declare const DEFAULT_HOOK_TIMEOUT_MS = 5000;
707
748
 
708
749
  /** Transport kind a connection belongs to. */
709
750
  type ConnectionTransport = 'sse' | 'websocket';
@@ -726,6 +767,11 @@ interface ConnectionRecord {
726
767
  subject: Subject<MessageEvent> | null;
727
768
  /** Server-initiated teardown signal (SSE only); `null` for WebSocket. */
728
769
  close$: Subject<void> | null;
770
+ /**
771
+ * When the re-authentication policy last confirmed the credentials behind this connection, in
772
+ * epoch milliseconds. Kept on the record so that it cannot outlive the connection it describes.
773
+ */
774
+ revalidatedAt?: number | undefined;
729
775
  /** Snapshot of the original authentication result — used by the re-auth policy. */
730
776
  originalAuth: {
731
777
  userId: string;
@@ -952,9 +998,11 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
952
998
  private readonly hooks?;
953
999
  private readonly logger;
954
1000
  private timer;
955
- /** connectionId → epoch-ms timestamp of last successful revalidation. */
956
- private readonly positiveCache;
957
1001
  private readonly policy;
1002
+ /** Connections with a revalidation queued or running: one call at a time for each. */
1003
+ private readonly inFlight;
1004
+ /** The cap on revalidations in flight, shared by every cycle. */
1005
+ private readonly slots;
958
1006
  constructor(connections: ConnectionRegistry, realtime: RealtimeService, auth: IConnectionAuthenticator, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined);
959
1007
  /**
960
1008
  * Schedule the periodic revalidation cycle.
@@ -965,7 +1013,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
965
1013
  */
966
1014
  onModuleInit(): void;
967
1015
  /**
968
- * Clear the timer and the positive cache.
1016
+ * Clear the timer.
969
1017
  *
970
1018
  * Called by NestJS on graceful shutdown to prevent leaks.
971
1019
  */
@@ -973,21 +1021,35 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
973
1021
  /**
974
1022
  * Run one revalidation cycle over every active connection, SSE and WebSocket alike.
975
1023
  *
976
- * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
977
- * refreshes the cache. A negative result (or a thrown error) invokes the configured
978
- * `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
1024
+ * Connections are revalidated concurrently, up to `concurrency` at a time across every cycle that
1025
+ * overlaps, and each for at most `revalidateTimeoutMs`: a call that does not settle in time is
1026
+ * handled as one that threw, so one connection cannot hold up the revocation of another. A
1027
+ * connection with a call already in flight is left to it. A connection revalidated within
1028
+ * `cacheTtlMs` is skipped, and a positive result refreshes that. A negative result (or a thrown
1029
+ * error, or a timeout) invokes the configured `onFailure` policy and fires the
1030
+ * `onReauthenticationFailed` hook best-effort.
979
1031
  *
980
1032
  * Exposed as public for test access.
981
1033
  */
982
1034
  runCycle(): Promise<void>;
1035
+ /** Revalidate one connection unless it is cached or already being revalidated. */
1036
+ private check;
1037
+ private revalidate;
1038
+ /**
1039
+ * Run `work`, giving up when it has not settled in `revalidateTimeoutMs`: the signal it was handed
1040
+ * is aborted and the call rejects. Whatever the abandoned work returns or throws later is ignored.
1041
+ * The same bound holds for the call to `revalidate` and for the revocation after it, because both
1042
+ * run in a slot that every connection shares.
1043
+ */
1044
+ private bounded;
983
1045
  /**
984
1046
  * Revoke a connection whose revalidation failed, and keep the cycle going when the
985
- * revocation itself is rejected. The positive-cache entry is already gone, so the next
986
- * cycle revalidates the connection and tries again.
1047
+ * revocation itself is rejected or does not settle in time. The last confirmation is already
1048
+ * forgotten, so the next cycle revalidates the connection and tries again.
987
1049
  */
988
1050
  private revoke;
989
1051
  /**
990
- * Evict the positive-cache entry, optionally start the failure event, then disconnect. The
1052
+ * Forget the last confirmation, optionally start the failure event, then disconnect. The
991
1053
  * event is a notification: it is started first, so its local delivery precedes the disconnect,
992
1054
  * but the revocation never waits for it. A failure to send it is logged.
993
1055
  */
@@ -996,6 +1058,99 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
996
1058
  private notify;
997
1059
  }
998
1060
 
1061
+ /**
1062
+ * A handshake was refused because the authenticator could not be asked or did not answer in time:
1063
+ * a fault of the system, not of the credentials, and carrying nothing about either.
1064
+ */
1065
+ declare class AuthenticationUnavailableError extends Error {
1066
+ readonly reason: 'saturated' | 'timeout';
1067
+ constructor(reason: 'saturated' | 'timeout');
1068
+ }
1069
+ /**
1070
+ * Calls the consumer's `authenticate` for every handshake, on both transports.
1071
+ *
1072
+ * A call that has not settled in `authenticateTimeoutMs` is given up on for the client: the
1073
+ * handshake is refused and the call's signal is aborted. The call keeps its place among the
1074
+ * `maxPendingHandshakes` until it actually settles, so an authenticator that never answers fills the
1075
+ * limit and further handshakes are refused at once, without being asked: a dependency that is down is
1076
+ * not given a new call for every handshake while the abandoned ones stay open against it.
1077
+ */
1078
+ declare class AuthenticationGate {
1079
+ private readonly authenticator;
1080
+ private readonly logger;
1081
+ private readonly maxPending;
1082
+ private readonly timeoutMs;
1083
+ private pending;
1084
+ private windowStartedAt;
1085
+ private refused;
1086
+ constructor(options: BymaxRealtimeModuleOptions, authenticator: IConnectionAuthenticator);
1087
+ /**
1088
+ * Ask the authenticator about one handshake.
1089
+ *
1090
+ * @throws AuthenticationUnavailableError when too many are waiting, or this one did not settle in
1091
+ * time. Whatever the authenticator itself throws is thrown as it is.
1092
+ */
1093
+ authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
1094
+ /** Count a refusal, and log at most one line for each window, so an attack cannot flood the log. */
1095
+ private refuse;
1096
+ }
1097
+
1098
+ /** A handshake was refused because the instance already holds `maxConnections` connections. */
1099
+ declare class ConnectionLimitError extends Error {
1100
+ readonly limit: number;
1101
+ constructor(limit: number);
1102
+ }
1103
+ /** A place held for a connection that has been admitted and is not registered yet. */
1104
+ interface AdmissionTicket {
1105
+ /** Give the place back. Safe to call more than once: only the first call counts. */
1106
+ release(): void;
1107
+ /**
1108
+ * Take the place again if the time bound gave it back while the handshake was still alive, as a
1109
+ * connection that is about to be registered must hold one. Does nothing for a place that is still
1110
+ * held or was released.
1111
+ *
1112
+ * @throws ConnectionLimitError when the place was given back and the instance has since filled.
1113
+ */
1114
+ renew(): void;
1115
+ }
1116
+ /** The ticket of a transport with no admission, which holds nothing. */
1117
+ declare const UNBOUNDED_TICKET: AdmissionTicket;
1118
+ /**
1119
+ * Decides, before a handshake is authenticated, whether the instance has room for one more
1120
+ * connection.
1121
+ *
1122
+ * The room is `maxConnections` less the connections registered, on either transport, and the
1123
+ * places held for connections admitted and not yet registered. A place is given back when the
1124
+ * connection is registered or when its request or socket closes, whichever comes first, and a place
1125
+ * that has been given back by neither within `authenticateTimeoutMs` and a margin is given back at
1126
+ * the next admission, so a handshake that dies half way, on a framework that reports no close, never
1127
+ * leaves the count above what is really held. There is no timer: a place is reclaimed only when
1128
+ * someone asks for room, which is when it matters.
1129
+ */
1130
+ declare class ConnectionAdmission {
1131
+ private readonly registry;
1132
+ private readonly logger;
1133
+ private readonly max;
1134
+ private readonly holdMs;
1135
+ /** The places held, oldest first, each with the time it is given back at whatever happens. */
1136
+ private readonly held;
1137
+ private windowStartedAt;
1138
+ private refused;
1139
+ constructor(options: BymaxRealtimeModuleOptions, registry: ConnectionRegistry);
1140
+ /**
1141
+ * Take a place for one connection.
1142
+ *
1143
+ * @throws ConnectionLimitError when the instance already holds `maxConnections`.
1144
+ */
1145
+ admit(): AdmissionTicket;
1146
+ /** Hold `place` if the instance has room, after giving back the places whose time has passed. */
1147
+ private take;
1148
+ /** Give back the places whose time has passed; they were taken in order, so the oldest come first. */
1149
+ private reclaim;
1150
+ /** Count a refusal, and log at most one line for each window, so an attack cannot flood the log. */
1151
+ private refuse;
1152
+ }
1153
+
999
1154
  /**
1000
1155
  * Indexed registry of room membership.
1001
1156
  *
@@ -1020,6 +1175,16 @@ declare class RoomRegistry {
1020
1175
  countRooms(): number;
1021
1176
  }
1022
1177
 
1178
+ /** What the first read of a reconnect's gap came to. */
1179
+ interface OfflineQueueRead {
1180
+ /** The gap events, in queue order. */
1181
+ readonly events: OfflineQueuedEvent[];
1182
+ /**
1183
+ * Whether the store failed: the gap is then empty, and the reconnect is served without it, so no
1184
+ * second read is made for it.
1185
+ */
1186
+ readonly degraded: boolean;
1187
+ }
1023
1188
  /**
1024
1189
  * Fetches events from the offline queue that the client missed since `lastEventId`
1025
1190
  * and de-duplicates them against the in-memory replay buffer.
@@ -1036,7 +1201,12 @@ declare class OfflineQueueDeliveryService {
1036
1201
  private readonly storage?;
1037
1202
  private readonly hooks?;
1038
1203
  private readonly logger;
1039
- constructor(storage?: IOfflineQueueStorage | undefined, hooks?: IConnectionLifecycleHooks | undefined);
1204
+ private readonly timeoutMs;
1205
+ private readonly maxPending;
1206
+ private pending;
1207
+ private windowStartedAt;
1208
+ private timedOut;
1209
+ constructor(storage?: IOfflineQueueStorage | undefined, hooks?: IConnectionLifecycleHooks | undefined, options?: BymaxRealtimeModuleOptions);
1040
1210
  /**
1041
1211
  * Return events for `userId` that arrived after `lastEventId` and are NOT
1042
1212
  * already covered by `ringBufferIds` (already replayed from in-memory buffer).
@@ -1048,9 +1218,25 @@ declare class OfflineQueueDeliveryService {
1048
1218
  * @param userId - The reconnecting user.
1049
1219
  * @param lastEventId - The `Last-Event-ID` header value.
1050
1220
  * @param ringBufferIds - Set of event ids already replayed from the ring buffer.
1051
- * @returns Gap events, or an empty array when no offline queue is configured.
1221
+ * @returns Gap events, or an empty array when no offline queue is configured or it fails.
1222
+ * @throws OfflineQueueTimeoutError when the queue has not answered in `authenticateTimeoutMs`: the
1223
+ * read is part of the handshake, so a queue that hangs must not keep the request open. The call
1224
+ * to the storage cannot be cancelled and runs on, and its late answer is ignored. It keeps its
1225
+ * place among the `maxPendingHandshakes` reads waiting at once until it settles, and a read that
1226
+ * finds them all taken is refused the same way without calling the storage.
1052
1227
  */
1053
1228
  retrieve(userId: string, lastEventId: string, ringBufferIds: Set<string>): Promise<OfflineQueuedEvent[]>;
1229
+ /**
1230
+ * The first read of a reconnect's gap: what {@link retrieve} returns, with whether the store failed.
1231
+ * A reconnect that was served without the gap because the store failed is not asked a second time
1232
+ * for what was appended since ({@link retrieveAppended}): the store is down, and the reconnect
1233
+ * is served without the gap.
1234
+ *
1235
+ * @param userId - The reconnecting user.
1236
+ * @param lastEventId - The `Last-Event-ID` header value.
1237
+ * @throws OfflineQueueTimeoutError as {@link retrieve} does.
1238
+ */
1239
+ retrieveGap(userId: string, lastEventId: string): Promise<OfflineQueueRead>;
1054
1240
  /**
1055
1241
  * Acknowledge delivered offline events so the storage backend can prune them.
1056
1242
  *
@@ -1063,15 +1249,47 @@ declare class OfflineQueueDeliveryService {
1063
1249
  * @param events - The delivered gap events; the last id is the prune watermark.
1064
1250
  */
1065
1251
  acknowledge(userId: string, events: readonly OfflineQueuedEvent[]): Promise<void>;
1252
+ /**
1253
+ * Return what was appended to the queue after `read`, the first read of the same reconnect: the
1254
+ * events with an id after the last of them, or after `lastEventId` when it returned none, never
1255
+ * more than the one reconnect's limit in all. The first read is made before the response is
1256
+ * committed, and a user with no connection here has no replay ring, so an event emitted while the
1257
+ * application's interceptors ran sits in the queue and nowhere else.
1258
+ *
1259
+ * When the first read failed (`read.degraded`) there is nothing to add to: the store is down and the
1260
+ * reconnect is served without the gap and without a second read. When it succeeded, every
1261
+ * failure of this read is thrown, the store's own error included, and the attempt ends before it
1262
+ * delivers anything: a stream built without these events moves the client's cursor past them with
1263
+ * the next event it receives, and an attempt that delivers nothing leaves the cursor where it was.
1264
+ * The read has the same deadline and the same share of `maxPendingHandshakes` as the first.
1265
+ *
1266
+ * @param userId - The reconnecting user.
1267
+ * @param lastEventId - The `Last-Event-ID` header value.
1268
+ * @param read - What the first read of this reconnect returned.
1269
+ * @returns The events appended since, in queue order; empty when no queue is configured, the first
1270
+ * read failed, or it already reached the limit.
1271
+ * @throws OfflineQueueTimeoutError when the queue did not answer in time or the reads waiting at
1272
+ * once are all taken; the store's own error when it fails.
1273
+ */
1274
+ retrieveAppended(userId: string, lastEventId: string, read: OfflineQueueRead): Promise<OfflineQueuedEvent[]>;
1275
+ /** One bounded call to the storage: refused at once when the reads waiting are all taken. */
1276
+ private read;
1277
+ /** Settle with `read`, or reject with an OfflineQueueTimeoutError once the deadline has passed. */
1278
+ private withinDeadline;
1279
+ /** Count a timeout, and log at most one line for each window, so a hung queue cannot flood the log. */
1280
+ private countTimeout;
1066
1281
  }
1067
1282
 
1068
1283
  /**
1069
1284
  * Per-user ring buffer of recent events for `Last-Event-ID` replay.
1070
1285
  *
1071
- * In-memory by design — it survives only as long as the process. Per-user buffers
1072
- * prevent one user from poisoning another's replay state. For durable replay
1073
- * (instance restart, or a gap larger than the buffer), a consumer can plug
1074
- * `IOfflineQueueStorage` as a fallback.
1286
+ * In-memory by design, and per instance: it survives only as long as the process, and it holds the
1287
+ * events of the users that have a connection here or had one lately. A user whose connections have
1288
+ * all closed is idle, and an idle entry is kept for `sse.replayTtlMs` and no more than
1289
+ * `sse.replayMaxIdleUsers` of them are kept at once, the one that closed longest ago going first. A
1290
+ * user with a connection open is never evicted: their number is bounded by the connections. Expiry
1291
+ * is checked when the buffer is used, so there is no timer to leak. For durable replay (another
1292
+ * instance, a restart, or a gap larger than the buffer), a consumer can plug `IOfflineQueueStorage`.
1075
1293
  *
1076
1294
  * @example
1077
1295
  * ```ts
@@ -1081,9 +1299,18 @@ declare class OfflineQueueDeliveryService {
1081
1299
  */
1082
1300
  declare class EventReplayBuffer {
1083
1301
  private readonly opts;
1084
- private readonly buffers;
1302
+ private readonly rings;
1303
+ /** The users with no connection open, in the order their last one closed, with the time it did. */
1304
+ private readonly idle;
1085
1305
  constructor(opts: BymaxRealtimeModuleOptions);
1086
- /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
1306
+ /** A connection of the user opened: from now on their events are kept, and the entry cannot expire. */
1307
+ open(userId: string): void;
1308
+ /** A connection of the user closed: with the last one the entry becomes idle and starts to age. */
1309
+ close(userId: string): void;
1310
+ /**
1311
+ * Append an event to a user's ring buffer, evicting the oldest beyond the cap. A user with no
1312
+ * entry has had no connection here, so nothing would ever replay it, and it is not kept.
1313
+ */
1087
1314
  append(userId: string, event: MessageEvent): void;
1088
1315
  /**
1089
1316
  * Return the events emitted after `lastEventId`.
@@ -1094,6 +1321,9 @@ declare class EventReplayBuffer {
1094
1321
  since(userId: string, lastEventId: string): MessageEvent[];
1095
1322
  /** Number of events currently buffered for a user (diagnostics). */
1096
1323
  size(userId: string): number;
1324
+ /** Forget the idle entries that have aged past the TTL, oldest first. */
1325
+ private sweep;
1326
+ private drop;
1097
1327
  }
1098
1328
 
1099
1329
  /** Minimal response surface the heartbeat needs — a writable text stream. */
@@ -1125,7 +1355,7 @@ declare class HeartbeatService {
1125
1355
  * `[5_000, 90_000]`.
1126
1356
  * @throws {Error} When `intervalMs` is outside the valid range.
1127
1357
  */
1128
- start(connectionId: string, res: HeartbeatWritable, intervalMs: number): void;
1358
+ start(connectionId: string, res: HeartbeatWritable, intervalMs: number, onTick?: () => void): void;
1129
1359
  /** Stop and clear the keepalive timer for a connection (idempotent). */
1130
1360
  stop(connectionId: string): void;
1131
1361
  /** Stop every keepalive timer (used on shutdown). */
@@ -1198,6 +1428,41 @@ interface SseResponse {
1198
1428
  setHeader(name: string, value: string): unknown;
1199
1429
  /** Write raw bytes to the open stream — the `: keepalive` comment. */
1200
1430
  write(chunk: string): unknown;
1431
+ /** The socket, when the response has one: `bytesWritten` counts what is still buffered in it. */
1432
+ readonly socket?: {
1433
+ readonly bytesWritten?: number;
1434
+ readonly writableLength?: number;
1435
+ once?(event: 'close', listener: () => void): unknown;
1436
+ off?(event: 'close', listener: () => void): unknown;
1437
+ } | null | undefined;
1438
+ /** Bytes the response is holding until the client reads. */
1439
+ readonly writableLength?: number | undefined;
1440
+ /**
1441
+ * Subscribe once to the response's `close`, which a Node response emits when the connection ends
1442
+ * or the response completes. Express hands the handler such a response; Fastify hands it a reply,
1443
+ * which has no `once` and carries the Node response as `raw`.
1444
+ */
1445
+ once?(event: 'close', listener: () => void): unknown;
1446
+ /** Remove a listener added with `once`. */
1447
+ off?(event: 'close', listener: () => void): unknown;
1448
+ /** The underlying Node response, on a framework whose own response object is a wrapper (Fastify). */
1449
+ readonly raw?: {
1450
+ once?(event: 'close', listener: () => void): unknown;
1451
+ off?(event: 'close', listener: () => void): unknown;
1452
+ } | undefined;
1453
+ }
1454
+
1455
+ /**
1456
+ * @fileoverview What an SSE connection has been sent but its client has not yet read.
1457
+ * @layer transport
1458
+ */
1459
+
1460
+ /** What the transport can read from a connection's response without owning it. */
1461
+ interface OutboundProbe {
1462
+ /** Bytes the socket has accepted so far; it only grows. */
1463
+ written(): number;
1464
+ /** Bytes the response is holding while the client does not read. */
1465
+ buffered(): number;
1201
1466
  }
1202
1467
 
1203
1468
  /** Parameters required to register a freshly authenticated SSE connection. */
@@ -1208,6 +1473,8 @@ interface RegisterSseConnectionParams {
1208
1473
  close$: Subject<void>;
1209
1474
  ip: string;
1210
1475
  userAgent: string | undefined;
1476
+ /** What the response has taken and holds; without it the connection's backlog is not bounded. */
1477
+ outbound?: OutboundProbe | undefined;
1211
1478
  }
1212
1479
  /**
1213
1480
  * SSE transport implementation.
@@ -1219,9 +1486,10 @@ interface RegisterSseConnectionParams {
1219
1486
  * self-originated messages are filtered there — so a single instance never
1220
1487
  * double-delivers and multiple instances never ping-pong.
1221
1488
  *
1222
- * Teardown of an SSE stream is driven by the per-connection `close$` subject:
1223
- * `disconnectLocal` completes it (which ends the `@Sse` Observable via
1224
- * `takeUntil`) before unregistering. See `docs/technical_specification.md` §6.1.
1489
+ * Teardown of an SSE stream is driven by the per-connection `close$` subject: `disconnectLocal`
1490
+ * removes the connection from the registries, then completes `close$` (which ends the `@Sse`
1491
+ * Observable via `takeUntil`), and only then runs the consumer's `onDisconnect`. See
1492
+ * `docs/technical_specification.md` §6.1.
1225
1493
  */
1226
1494
  declare class SseTransport implements ITransport {
1227
1495
  #private;
@@ -1230,15 +1498,17 @@ declare class SseTransport implements ITransport {
1230
1498
  private readonly replayBuffer;
1231
1499
  private readonly idGen;
1232
1500
  private readonly heartbeat;
1233
- private readonly auth;
1501
+ private readonly gate;
1234
1502
  private readonly pubsub;
1235
1503
  private readonly hooks;
1236
1504
  private readonly options;
1237
1505
  private readonly instanceId;
1238
1506
  private readonly offlineQueue?;
1507
+ private readonly admission?;
1239
1508
  readonly kind: "sse";
1240
1509
  private readonly logger;
1241
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, auth: IConnectionAuthenticator, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined);
1510
+ private readonly outbound;
1511
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, gate: AuthenticationGate, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined, admission?: ConnectionAdmission | undefined);
1242
1512
  /**
1243
1513
  * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
1244
1514
  * nearer the root than the realtime module still runs first, and until it returns a stream is
@@ -1262,6 +1532,12 @@ declare class SseTransport implements ITransport {
1262
1532
  get heartbeatMs(): number;
1263
1533
  /** Whether the `connection:established` event should be emitted on connect. */
1264
1534
  get emitConnectionEvent(): boolean;
1535
+ /**
1536
+ * Take a place for a connection before it is authenticated.
1537
+ *
1538
+ * @throws ConnectionLimitError when the instance already holds `maxConnections`.
1539
+ */
1540
+ admit(): AdmissionTicket;
1265
1541
  /** Authenticate a connection through the consumer-provided authenticator. */
1266
1542
  authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
1267
1543
  /**
@@ -1272,8 +1548,18 @@ declare class SseTransport implements ITransport {
1272
1548
  * handler can carry a consistent connection record reference.
1273
1549
  */
1274
1550
  registerConnection(params: RegisterSseConnectionParams): Promise<void>;
1275
- /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
1551
+ /**
1552
+ * Idempotent cleanup for a connection that has already gone — runs the disconnect hook exactly
1553
+ * once, which the library waits for no longer than `hookTimeoutMs`.
1554
+ */
1276
1555
  unregisterConnection(connectionId: string, reason?: string): Promise<void>;
1556
+ /**
1557
+ * Forget a connection: its record, its rooms, its heartbeat and its backlog. Synchronous, so that
1558
+ * nothing a consumer's code does can come between a connection and its removal.
1559
+ */
1560
+ private release;
1561
+ /** Run `onDisconnect` for a released connection, giving up on it after `hookTimeoutMs`. */
1562
+ private notifyDisconnect;
1277
1563
  /** Replay the events a user missed after `lastEventId`. */
1278
1564
  getReplayEvents(userId: string, lastEventId: string): MessageEvent[];
1279
1565
  /**
@@ -1366,6 +1652,11 @@ declare class SseTransport implements ITransport {
1366
1652
  private buildMessage;
1367
1653
  /** Deliver to one connection, isolating failures so others still receive the event. */
1368
1654
  private deliver;
1655
+ /** Start bounding a connection's backlog, when its response can be measured. */
1656
+ private track;
1657
+ /** Called on each heartbeat: closes a connection whose client has stopped reading altogether. */
1658
+ checkStall(connectionId: string): void;
1659
+ private cutSlowConsumer;
1369
1660
  /** Publish once to the bus; resolves with the failure, or `undefined` once the bus accepted it. */
1370
1661
  private tryPublish;
1371
1662
  /** Publish once to the bus. A failure is reported and never fails the live emit path. */
@@ -1411,7 +1702,7 @@ declare class SseSubscriptionHandler {
1411
1702
  * without a message.
1412
1703
  *
1413
1704
  * @param auth - The result the consumer's authenticator returned.
1414
- * @returns The same result with the routing tenant resolved.
1705
+ * @returns The result with the routing tenant resolved and `rooms` replaced by the validated, frozen copy.
1415
1706
  * @throws InternalServerErrorException with the generic body when a trait is present
1416
1707
  * but blank.
1417
1708
  */
@@ -1445,10 +1736,36 @@ declare class SseSubscriptionHandler {
1445
1736
  * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
1446
1737
  * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
1447
1738
  */
1448
- authenticateBeforeCommit(req: SseRequest): Promise<void>;
1739
+ authenticateBeforeCommit(req: SseRequest, res?: SseResponse): Promise<void>;
1449
1740
  private toClientError;
1450
1741
  private serverError;
1451
1742
  private authenticateRequest;
1743
+ /**
1744
+ * Read the offline queue's gap for a reconnect, WITHOUT acknowledging (acknowledgment is deferred
1745
+ * until the events have been emitted to an open subscriber, so delivery is at-least-once).
1746
+ *
1747
+ * This runs with the authentication, in the guard, because a refusal that needs I/O is a status
1748
+ * only if it is decided before Nest commits the response: with an interceptor registered it
1749
+ * commits `200` from a timer once the route returns, and a refusal after that can only end the
1750
+ * stream. A queue that did not answer in time is a `503` with the generic body; a queue that fails
1751
+ * is reported by the service and gives an empty gap marked as degraded, and anything else it throws
1752
+ * is a generic `500`, whatever its error says.
1753
+ */
1754
+ private readQueue;
1755
+ /**
1756
+ * Add what was appended to the offline queue since the guard read it, so that an event emitted to
1757
+ * this user while the application's interceptors ran, which is in the queue and in no replay ring,
1758
+ * is delivered with the rest of the gap. The earlier read ended at the last event it returned, and
1759
+ * this one starts after it, so the two lists are disjoint and keep queue order.
1760
+ *
1761
+ * When the first read failed, the store is down and the reconnect is served without a gap and
1762
+ * there is no second read. When the first read succeeded, a second one that did not
1763
+ * answer in time, was refused because the reads waiting are all taken, or failed ends the attempt
1764
+ * here, before any event is delivered: a stream that skipped these events moves the client's cursor
1765
+ * past them with the next event it receives, where an attempt that delivered nothing leaves it where
1766
+ * it was.
1767
+ */
1768
+ private readAppended;
1452
1769
  /**
1453
1770
  * Build the live Observable using a subscribe-before-register pattern.
1454
1771
  *
@@ -1764,17 +2081,25 @@ declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'te
1764
2081
  declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
1765
2082
 
1766
2083
  /**
1767
- * Refuse an authentication result whose `rooms` break the admission rules.
2084
+ * Validate the `rooms` of an authentication result and return the result the connection is
2085
+ * admitted with.
1768
2086
  *
1769
2087
  * Like a blank identity, a bad room is a contract violation by the authenticator, so it
1770
2088
  * is refused at admission rather than trimmed or skipped: a connection quietly missing a
1771
2089
  * room it was meant to join would be live and unscoped. Every check is on the runtime
1772
2090
  * value, because the declared type is a promise, not a fact.
1773
2091
  *
2092
+ * The rooms that are joined are the ones validated: the list is copied once, reading stops at
2093
+ * the bound, the copy is what is checked, and the returned result carries the frozen copy.
2094
+ * The authenticator keeps a reference to the array it returned, and the join happens after an
2095
+ * await, so reading the original there would join whatever it holds by then.
2096
+ *
1774
2097
  * @param auth - The resolved authentication result.
2098
+ * @returns `auth` itself when it has no `rooms`; otherwise a result with the same fields and a
2099
+ * frozen copy of its `rooms`.
1775
2100
  * @throws Error carrying `REALTIME_AUTH_FAILED` when `rooms` is present and invalid.
1776
2101
  */
1777
- declare function assertAdmissionRooms(auth: AuthenticationResult): void;
2102
+ declare function admitRooms(auth: AuthenticationResult): AuthenticationResult;
1778
2103
 
1779
2104
  /**
1780
2105
  * @fileoverview Canonical room id prefixes for scoping emits and auto-join.
@@ -1832,6 +2157,83 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
1832
2157
  /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
1833
2158
  declare function describeError(reason: unknown): string;
1834
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
+
2184
+ /**
2185
+ * @fileoverview Runs a consumer's lifecycle hook so that its failure is a value, never an exception.
2186
+ * @layer utils
2187
+ */
2188
+ /** What a hook that failed left behind, boxed so that a thrown `undefined` is still a failure. */
2189
+ interface HookFailure {
2190
+ readonly error: unknown;
2191
+ }
2192
+ /**
2193
+ * Run a consumer's hook and settle with its failure instead of raising it.
2194
+ *
2195
+ * A hook is a consumer's notification, not a condition of the connection it is about. It may
2196
+ * throw before it returns or reject afterwards, and it runs where nothing awaits the caller (a
2197
+ * disconnect handler) or where a failure would undo the library's own work, so neither is let
2198
+ * out. The hook is called synchronously, before the first `await`.
2199
+ *
2200
+ * With `timeoutMs`, a hook that has not settled in that time is given up on: the failure says so,
2201
+ * and whatever the abandoned hook returns or throws later is ignored. A hook that nothing waits
2202
+ * for needs no bound; one the library awaits does, or a hook that never settles holds the caller.
2203
+ *
2204
+ * @param invoke - A function that calls the hook, handling its being absent.
2205
+ * @param timeoutMs - How long to wait for the hook to settle; no limit when absent.
2206
+ * @returns The failure, or `undefined` when the hook completed.
2207
+ */
2208
+ declare function runHook(invoke: () => void | Promise<void>, timeoutMs?: number): Promise<HookFailure | undefined>;
2209
+
2210
+ /**
2211
+ * @fileoverview The error a call rejects with when it could not reach what it was asked to act on.
2212
+ * @layer utils
2213
+ */
2214
+
2215
+ /** A 503 that carries one of the library's stable codes as a property. */
2216
+ type UnavailableError = ServiceUnavailableException & {
2217
+ readonly code: RealtimeErrorCode;
2218
+ };
2219
+ /**
2220
+ * Builds the rejection for a call whose effect did not happen, such as a revocation that never
2221
+ * reached its connection. The stable code leads the message, as it does in the other errors this
2222
+ * library raises, is also the `code` property, and the original failure travels as `cause`.
2223
+ *
2224
+ * It is Nest's `ServiceUnavailableException`, so a consumer's controller that lets it escape
2225
+ * answers 503 with the generic body, and the library's own text never reaches a client: the
2226
+ * message, the code and the cause are on the instance for whoever logs it, and the response says
2227
+ * only that the service is unavailable. `ServiceUnavailableException` is `@nestjs/common`'s, a peer
2228
+ * the package has one copy of, so `instanceof` holds across the package's bundles.
2229
+ *
2230
+ * @param code - The stable error code to carry.
2231
+ * @param who - The class that raises it, shown in brackets.
2232
+ * @param what - What could not be reached.
2233
+ * @param cause - The failure underneath, whatever was thrown.
2234
+ */
2235
+ declare function unavailableError(code: RealtimeErrorCode, who: string, what: string, cause: unknown): UnavailableError;
2236
+
1835
2237
  /**
1836
2238
  * @fileoverview The error every coded failure of this library is built with.
1837
2239
  * @layer utils
@@ -1857,23 +2259,6 @@ declare function realtimeError(code: RealtimeErrorCode, detail: string, options?
1857
2259
  readonly cause?: unknown;
1858
2260
  }): CodedError;
1859
2261
 
1860
- /**
1861
- * @fileoverview The error a call rejects with when it could not reach what it was asked to act on.
1862
- * @layer utils
1863
- */
1864
-
1865
- /**
1866
- * Builds the rejection for a call whose effect did not happen, such as a revocation that never
1867
- * reached its connection. The stable code leads the message, as it does in the other errors this
1868
- * library raises, is also the `code` property, and the original failure travels as `cause`.
1869
- *
1870
- * @param code - The stable error code to carry.
1871
- * @param who - The class that raises it, shown in brackets.
1872
- * @param what - What could not be reached.
1873
- * @param cause - The failure underneath, whatever was thrown.
1874
- */
1875
- declare function unavailableError(code: RealtimeErrorCode, who: string, what: string, cause: unknown): CodedError;
1876
-
1877
2262
  /**
1878
2263
  * @fileoverview Makes a delivery path's failure visible without failing the call that used it.
1879
2264
  * @layer utils
@@ -2008,5 +2393,5 @@ declare const RESERVED_EVENT_NAMES: {
2008
2393
  /** Union of reserved event name values. */
2009
2394
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2010
2395
 
2011
- export { ADMISSION_ROOM_LIMITS, BymaxRealtimeModule, ConnectionRegistry, 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, assertAdmissionRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
2012
- export type { AuthenticationResult, 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 };