@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.
@@ -16,6 +16,24 @@ var PRESENCE_EVENT_NAMES = {
16
16
  ONLINE: "presence:online",
17
17
  OFFLINE: "presence:offline"
18
18
  };
19
+
20
+ // src/react/internal/backoff.ts
21
+ var MAX_TIMER_MS = 2147483647;
22
+ function nextBackoff(lastMs, maxMs) {
23
+ return Math.min(lastMs * 2, maxMs, MAX_TIMER_MS);
24
+ }
25
+ function validDelay(ms, fallback) {
26
+ return ms !== void 0 && Number.isInteger(ms) && ms > 0 ? ms : fallback;
27
+ }
28
+ function withLastEventId(url, id) {
29
+ if (id === void 0) return url;
30
+ const hash = url.indexOf("#");
31
+ const head = hash < 0 ? url : url.slice(0, hash);
32
+ const mark = head.indexOf("?");
33
+ const query = new URLSearchParams(mark < 0 ? "" : head.slice(mark + 1));
34
+ query.set("lastEventId", id);
35
+ return `${mark < 0 ? head : head.slice(0, mark)}?${query}${hash < 0 ? "" : url.slice(hash)}`;
36
+ }
19
37
  var NAMED_SSE_EVENTS = [
20
38
  RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED,
21
39
  RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED,
@@ -33,9 +51,10 @@ function useRealtimeSse(opts) {
33
51
  const [error, setError] = react.useState(void 0);
34
52
  const [reconnectAttempts, setReconnectAttempts] = react.useState(0);
35
53
  const sourceRef = react.useRef(null);
36
- const reconnectMsRef = react.useRef(opts.reconnectInitialMs ?? 1e3);
54
+ const reconnectMsRef = react.useRef(validDelay(opts.reconnectInitialMs, 1e3));
37
55
  const attemptsRef = react.useRef(0);
38
56
  const timerRef = react.useRef(null);
57
+ const lastIdRef = react.useRef(void 0);
39
58
  const extraEventNames = (opts.eventNames ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
40
59
  const clearReconnectTimer = react.useCallback(() => {
41
60
  if (timerRef.current !== null) {
@@ -47,13 +66,16 @@ function useRealtimeSse(opts) {
47
66
  if (opts.enabled === false) return;
48
67
  sourceRef.current?.close();
49
68
  clearReconnectTimer();
50
- const source = new EventSource(opts.url, { withCredentials: opts.withCredentials ?? false });
69
+ if (lastIdRef.current?.url !== opts.url) lastIdRef.current = void 0;
70
+ const source = new EventSource(withLastEventId(opts.url, lastIdRef.current?.id), {
71
+ withCredentials: opts.withCredentials ?? false
72
+ });
51
73
  sourceRef.current = source;
52
74
  source.onopen = () => {
53
75
  setConnected(true);
54
76
  setError(void 0);
55
77
  clearReconnectTimer();
56
- reconnectMsRef.current = opts.reconnectInitialMs ?? 1e3;
78
+ reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
57
79
  attemptsRef.current = 0;
58
80
  setReconnectAttempts(0);
59
81
  };
@@ -67,11 +89,12 @@ function useRealtimeSse(opts) {
67
89
  return;
68
90
  }
69
91
  clearReconnectTimer();
70
- const delay = Math.min(reconnectMsRef.current * 2, opts.reconnectMaxMs ?? 3e4);
92
+ const delay = nextBackoff(reconnectMsRef.current, validDelay(opts.reconnectMaxMs, 3e4));
71
93
  reconnectMsRef.current = delay;
72
94
  timerRef.current = setTimeout(connect, delay);
73
95
  };
74
96
  const handleEvent = (e) => {
97
+ if (e.lastEventId !== "") lastIdRef.current = { url: opts.url, id: e.lastEventId };
75
98
  let data;
76
99
  try {
77
100
  data = JSON.parse(e.data);
@@ -114,7 +137,7 @@ function useRealtimeSse(opts) {
114
137
  };
115
138
  }, [connect, opts.enabled, clearReconnectTimer]);
116
139
  const reconnect = react.useCallback(() => {
117
- reconnectMsRef.current = opts.reconnectInitialMs ?? 1e3;
140
+ reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
118
141
  attemptsRef.current = 0;
119
142
  setReconnectAttempts(0);
120
143
  connect();
@@ -14,6 +14,24 @@ var PRESENCE_EVENT_NAMES = {
14
14
  ONLINE: "presence:online",
15
15
  OFFLINE: "presence:offline"
16
16
  };
17
+
18
+ // src/react/internal/backoff.ts
19
+ var MAX_TIMER_MS = 2147483647;
20
+ function nextBackoff(lastMs, maxMs) {
21
+ return Math.min(lastMs * 2, maxMs, MAX_TIMER_MS);
22
+ }
23
+ function validDelay(ms, fallback) {
24
+ return ms !== void 0 && Number.isInteger(ms) && ms > 0 ? ms : fallback;
25
+ }
26
+ function withLastEventId(url, id) {
27
+ if (id === void 0) return url;
28
+ const hash = url.indexOf("#");
29
+ const head = hash < 0 ? url : url.slice(0, hash);
30
+ const mark = head.indexOf("?");
31
+ const query = new URLSearchParams(mark < 0 ? "" : head.slice(mark + 1));
32
+ query.set("lastEventId", id);
33
+ return `${mark < 0 ? head : head.slice(0, mark)}?${query}${hash < 0 ? "" : url.slice(hash)}`;
34
+ }
17
35
  var NAMED_SSE_EVENTS = [
18
36
  RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED,
19
37
  RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED,
@@ -31,9 +49,10 @@ function useRealtimeSse(opts) {
31
49
  const [error, setError] = useState(void 0);
32
50
  const [reconnectAttempts, setReconnectAttempts] = useState(0);
33
51
  const sourceRef = useRef(null);
34
- const reconnectMsRef = useRef(opts.reconnectInitialMs ?? 1e3);
52
+ const reconnectMsRef = useRef(validDelay(opts.reconnectInitialMs, 1e3));
35
53
  const attemptsRef = useRef(0);
36
54
  const timerRef = useRef(null);
55
+ const lastIdRef = useRef(void 0);
37
56
  const extraEventNames = (opts.eventNames ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
38
57
  const clearReconnectTimer = useCallback(() => {
39
58
  if (timerRef.current !== null) {
@@ -45,13 +64,16 @@ function useRealtimeSse(opts) {
45
64
  if (opts.enabled === false) return;
46
65
  sourceRef.current?.close();
47
66
  clearReconnectTimer();
48
- const source = new EventSource(opts.url, { withCredentials: opts.withCredentials ?? false });
67
+ if (lastIdRef.current?.url !== opts.url) lastIdRef.current = void 0;
68
+ const source = new EventSource(withLastEventId(opts.url, lastIdRef.current?.id), {
69
+ withCredentials: opts.withCredentials ?? false
70
+ });
49
71
  sourceRef.current = source;
50
72
  source.onopen = () => {
51
73
  setConnected(true);
52
74
  setError(void 0);
53
75
  clearReconnectTimer();
54
- reconnectMsRef.current = opts.reconnectInitialMs ?? 1e3;
76
+ reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
55
77
  attemptsRef.current = 0;
56
78
  setReconnectAttempts(0);
57
79
  };
@@ -65,11 +87,12 @@ function useRealtimeSse(opts) {
65
87
  return;
66
88
  }
67
89
  clearReconnectTimer();
68
- const delay = Math.min(reconnectMsRef.current * 2, opts.reconnectMaxMs ?? 3e4);
90
+ const delay = nextBackoff(reconnectMsRef.current, validDelay(opts.reconnectMaxMs, 3e4));
69
91
  reconnectMsRef.current = delay;
70
92
  timerRef.current = setTimeout(connect, delay);
71
93
  };
72
94
  const handleEvent = (e) => {
95
+ if (e.lastEventId !== "") lastIdRef.current = { url: opts.url, id: e.lastEventId };
73
96
  let data;
74
97
  try {
75
98
  data = JSON.parse(e.data);
@@ -112,7 +135,7 @@ function useRealtimeSse(opts) {
112
135
  };
113
136
  }, [connect, opts.enabled, clearReconnectTimer]);
114
137
  const reconnect = useCallback(() => {
115
- reconnectMsRef.current = opts.reconnectInitialMs ?? 1e3;
138
+ reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
116
139
  attemptsRef.current = 0;
117
140
  setReconnectAttempts(0);
118
141
  connect();
@@ -1 +1 @@
1
- export { ADMISSION_ROOM_LIMITS, AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { ADMISSION_ROOM_LIMITS, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
@@ -1 +1 @@
1
- export { ADMISSION_ROOM_LIMITS, AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { ADMISSION_ROOM_LIMITS, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, 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, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
@@ -34,6 +34,7 @@ var REALTIME_ERROR_CODES = {
34
34
  AUTH_FAILED: "REALTIME_AUTH_FAILED",
35
35
  REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED",
36
36
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
37
+ SLOW_CONSUMER: "REALTIME_SLOW_CONSUMER",
37
38
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
38
39
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
39
40
  TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
@@ -165,6 +165,8 @@ type PresenceEventName = (typeof PRESENCE_EVENT_NAMES)[keyof typeof PRESENCE_EVE
165
165
  * `TOO_MANY_CONNECTIONS` signals FIFO eviction: when a user exceeds
166
166
  * `maxConnectionsPerUser`, the OLDEST connection is evicted (closed with this
167
167
  * code) and the new one is admitted — it is never an HTTP 429 rejection.
168
+ * `SLOW_CONSUMER` is the reason an SSE connection is closed when the client does not read
169
+ * what is sent to it.
168
170
  */
169
171
  declare const REALTIME_ERROR_CODES: {
170
172
  readonly INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS";
@@ -172,6 +174,7 @@ declare const REALTIME_ERROR_CODES: {
172
174
  readonly AUTH_FAILED: "REALTIME_AUTH_FAILED";
173
175
  readonly REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED";
174
176
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
177
+ readonly SLOW_CONSUMER: "REALTIME_SLOW_CONSUMER";
175
178
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
176
179
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
177
180
  readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
@@ -165,6 +165,8 @@ type PresenceEventName = (typeof PRESENCE_EVENT_NAMES)[keyof typeof PRESENCE_EVE
165
165
  * `TOO_MANY_CONNECTIONS` signals FIFO eviction: when a user exceeds
166
166
  * `maxConnectionsPerUser`, the OLDEST connection is evicted (closed with this
167
167
  * code) and the new one is admitted — it is never an HTTP 429 rejection.
168
+ * `SLOW_CONSUMER` is the reason an SSE connection is closed when the client does not read
169
+ * what is sent to it.
168
170
  */
169
171
  declare const REALTIME_ERROR_CODES: {
170
172
  readonly INVALID_OPTIONS: "REALTIME_INVALID_OPTIONS";
@@ -172,6 +174,7 @@ declare const REALTIME_ERROR_CODES: {
172
174
  readonly AUTH_FAILED: "REALTIME_AUTH_FAILED";
173
175
  readonly REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED";
174
176
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
177
+ readonly SLOW_CONSUMER: "REALTIME_SLOW_CONSUMER";
175
178
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
176
179
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
177
180
  readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
@@ -32,6 +32,7 @@ var REALTIME_ERROR_CODES = {
32
32
  AUTH_FAILED: "REALTIME_AUTH_FAILED",
33
33
  REAUTHENTICATION_FAILED: "REALTIME_REAUTHENTICATION_FAILED",
34
34
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
35
+ SLOW_CONSUMER: "REALTIME_SLOW_CONSUMER",
35
36
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
36
37
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
37
38
  TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
@@ -32,14 +32,16 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
32
32
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
33
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
34
34
  var CONNECTION_ROOM_PREFIX = "connection";
35
+ var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
35
36
  var _shuttingDown;
36
37
  exports.WebSocketTransport = class WebSocketTransport {
37
- constructor(connections, rooms, auth, hooks, options) {
38
+ constructor(connections, rooms, gate, hooks, options, admission) {
38
39
  this.connections = connections;
39
40
  this.rooms = rooms;
40
- this.auth = auth;
41
+ this.gate = gate;
41
42
  this.hooks = hooks;
42
43
  this.options = options;
44
+ this.admission = admission;
43
45
  __publicField(this, "kind", "websocket");
44
46
  __publicField(this, "logger", new common.Logger(exports.WebSocketTransport.name));
45
47
  __publicField(this, "server", null);
@@ -48,9 +50,10 @@ exports.WebSocketTransport = class WebSocketTransport {
48
50
  }
49
51
  connections;
50
52
  rooms;
51
- auth;
53
+ gate;
52
54
  hooks;
53
55
  options;
56
+ admission;
54
57
  onModuleDestroy() {
55
58
  __privateSet(this, _shuttingDown, true);
56
59
  }
@@ -79,8 +82,8 @@ exports.WebSocketTransport = class WebSocketTransport {
79
82
  const sockets = server.sockets;
80
83
  return sockets instanceof Map ? sockets : sockets.sockets;
81
84
  }
82
- authenticator() {
83
- return this.auth;
85
+ authenticate(context) {
86
+ return this.gate.authenticate(context);
84
87
  }
85
88
  async registerSocket(socket, auth) {
86
89
  const connectedAt = /* @__PURE__ */ new Date();
@@ -110,17 +113,21 @@ exports.WebSocketTransport = class WebSocketTransport {
110
113
  if (auth.tenantId) this.rooms.join(socket.id, `${internal.ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
111
114
  for (const room of auth.rooms ?? []) this.rooms.join(socket.id, room);
112
115
  await this.evictBeyondLimit(auth.userId);
113
- await this.hooks.onConnect?.({
114
- connectionId: socket.id,
115
- userId: auth.userId,
116
- tenantId: auth.tenantId,
117
- roles: auth.roles,
118
- metadata: auth.metadata,
119
- transport: "websocket",
120
- ip: socket.handshake.address,
121
- userAgent: socket.handshake.headers["user-agent"],
122
- connectedAt
123
- });
116
+ const failed = await internal.runHook(
117
+ () => this.hooks.onConnect?.({
118
+ connectionId: socket.id,
119
+ userId: auth.userId,
120
+ tenantId: auth.tenantId,
121
+ roles: auth.roles,
122
+ metadata: auth.metadata,
123
+ transport: "websocket",
124
+ ip: socket.handshake.address,
125
+ userAgent: socket.handshake.headers["user-agent"],
126
+ connectedAt
127
+ }),
128
+ this.options.hookTimeoutMs ?? internal.DEFAULT_HOOK_TIMEOUT_MS
129
+ );
130
+ if (failed) this.logger.error(`onConnect hook failed: ${internal.describeError(failed.error)}`);
124
131
  }
125
132
  async unregisterSocket(connectionId, reason) {
126
133
  const record = this.connections.unregister(connectionId);
@@ -139,7 +146,11 @@ exports.WebSocketTransport = class WebSocketTransport {
139
146
  durationMs: Date.now() - record.connectedAt.getTime(),
140
147
  ...reason !== void 0 ? { reason } : {}
141
148
  };
142
- await this.hooks.onDisconnect?.(disconnectMeta);
149
+ const failed = await internal.runHook(
150
+ () => this.hooks.onDisconnect?.(disconnectMeta),
151
+ this.options.hookTimeoutMs ?? internal.DEFAULT_HOOK_TIMEOUT_MS
152
+ );
153
+ if (failed) this.logger.error(`onDisconnect hook failed: ${internal.describeError(failed.error)}`);
143
154
  }
144
155
  async emitToUser(userId, event, data) {
145
156
  this.attached("emitToUser")?.to(`${internal.ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
@@ -190,9 +201,12 @@ exports.WebSocketTransport = class WebSocketTransport {
190
201
  );
191
202
  }
192
203
  }
204
+ admit() {
205
+ return this.admission?.admit() ?? internal.UNBOUNDED_TICKET;
206
+ }
193
207
  async evictBeyondLimit(userId) {
194
- const max = this.options.websocket?.maxConnectionsPerUser;
195
- if (max === void 0 || max <= 0) return;
208
+ const max = this.options.websocket?.maxConnectionsPerUser ?? DEFAULT_MAX_CONNECTIONS_PER_USER;
209
+ if (max <= 0) return;
196
210
  let userConnections = this.connections.byUser(userId, "websocket");
197
211
  while (userConnections.length > max) {
198
212
  const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
@@ -207,9 +221,11 @@ exports.WebSocketTransport = __decorateClass([
207
221
  common.Injectable(),
208
222
  __decorateParam(0, common.Inject(internal.ConnectionRegistry)),
209
223
  __decorateParam(1, common.Inject(internal.RoomRegistry)),
210
- __decorateParam(2, common.Inject(internal.REALTIME_AUTHENTICATOR_TOKEN)),
224
+ __decorateParam(2, common.Inject(internal.AuthenticationGate)),
211
225
  __decorateParam(3, common.Inject(internal.REALTIME_HOOKS_TOKEN)),
212
- __decorateParam(4, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
226
+ __decorateParam(4, common.Inject(internal.REALTIME_OPTIONS_TOKEN)),
227
+ __decorateParam(5, common.Optional()),
228
+ __decorateParam(5, common.Inject(internal.ConnectionAdmission))
213
229
  ], exports.WebSocketTransport);
214
230
 
215
231
  // src/websocket/transports/composite/composite.transport.ts
@@ -297,6 +313,7 @@ exports.CompositeTransport = __decorateClass([
297
313
  __decorateParam(0, common.Inject(internal.SseTransport)),
298
314
  __decorateParam(1, common.Inject(exports.WebSocketTransport))
299
315
  ], exports.CompositeTransport);
316
+ var ADAPTER_COMMANDS = ["subscribe", "psubscribe", "unsubscribe", "punsubscribe"];
300
317
  var realtimeServers = /* @__PURE__ */ new WeakSet();
301
318
  function isRealtimeIoServer(server) {
302
319
  return typeof server === "object" && server !== null && realtimeServers.has(server);
@@ -304,6 +321,7 @@ function isRealtimeIoServer(server) {
304
321
  var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
305
322
  adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
306
323
  options;
324
+ subscribers = /* @__PURE__ */ new Set();
307
325
  constructor(app) {
308
326
  super(app);
309
327
  this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
@@ -339,13 +357,47 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
339
357
  realtimeServers.add(server);
340
358
  return server;
341
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
+ }
342
384
  installRedisAdapter(server, pubClient) {
385
+ let sub;
343
386
  try {
344
387
  const { createAdapter } = __require("@socket.io/redis-adapter");
345
388
  const pub = pubClient;
346
- const sub = pub.duplicate();
389
+ sub = pub.duplicate({ disconnectTimeout: 1 });
390
+ this.subscribers.add(sub);
391
+ this.guardCommands(sub);
347
392
  server.adapter(createAdapter(pub, sub));
348
393
  } catch (err) {
394
+ if (sub !== void 0) {
395
+ this.subscribers.delete(sub);
396
+ try {
397
+ sub.disconnect();
398
+ } catch {
399
+ }
400
+ }
349
401
  const reason = internal.describeError(err);
350
402
  throw internal.realtimeError(
351
403
  internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
@@ -373,13 +425,18 @@ exports.RealtimeGateway = class RealtimeGateway {
373
425
  logger = new common.Logger(exports.RealtimeGateway.name);
374
426
  server;
375
427
  authenticated = /* @__PURE__ */ new WeakMap();
428
+ tickets = /* @__PURE__ */ new WeakMap();
376
429
  authenticateHandshake = async (socket, next) => {
430
+ let ticket;
431
+ let handedOver = false;
377
432
  try {
378
433
  if (this.transport.shuttingDown) {
379
434
  next(this.unavailable());
380
435
  return;
381
436
  }
382
- const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
437
+ const held = this.admit(socket);
438
+ ticket = held;
439
+ const auth = await this.transport.authenticate(this.buildAuthContext(socket));
383
440
  if (this.transport.shuttingDown) {
384
441
  next(this.unavailable());
385
442
  return;
@@ -392,16 +449,25 @@ exports.RealtimeGateway = class RealtimeGateway {
392
449
  }
393
450
  const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
394
451
  internal.assertIdentityIsNotBlank(resolvedAuth);
395
- internal.assertAdmissionRooms(resolvedAuth);
396
- this.authenticated.set(socket, resolvedAuth);
452
+ this.authenticated.set(socket, internal.admitRooms(resolvedAuth));
453
+ this.tickets.set(socket, held);
454
+ handedOver = true;
397
455
  next();
398
456
  } catch (err) {
399
- this.logger.error(`handshake refused for socket ${socket.id}: ${internal.describeError(err)}`);
400
- next(new Error("Internal Server Error"));
457
+ next(this.refusalFor(socket, err));
458
+ } finally {
459
+ if (!handedOver) ticket?.release();
401
460
  }
402
461
  };
403
- unavailable() {
404
- const refusal = new Error(internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
462
+ refusalFor(socket, err) {
463
+ if (err instanceof internal.AuthenticationUnavailableError || err instanceof internal.ConnectionLimitError) {
464
+ return this.unavailable("Internal Server Error");
465
+ }
466
+ this.logger.error(`handshake refused for socket ${socket.id}: ${internal.describeError(err)}`);
467
+ return new Error("Internal Server Error");
468
+ }
469
+ unavailable(message = internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE) {
470
+ const refusal = new Error(message);
405
471
  refusal.data = { code: internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE };
406
472
  return refusal;
407
473
  }
@@ -437,39 +503,69 @@ exports.RealtimeGateway = class RealtimeGateway {
437
503
  };
438
504
  }
439
505
  async handleConnection(socket) {
506
+ let ticket;
440
507
  try {
441
- let resolvedAuth = this.authenticated.get(socket);
442
- this.authenticated.delete(socket);
443
- if (!resolvedAuth) {
444
- if (this.transport.shuttingDown) {
445
- socket.disconnect(true);
446
- return;
447
- }
448
- const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
449
- if (!auth) {
450
- socket.disconnect(true);
451
- return;
452
- }
453
- resolvedAuth = internal.resolveAuthTenant(this.options, auth);
454
- internal.assertIdentityIsNotBlank(resolvedAuth);
455
- internal.assertAdmissionRooms(resolvedAuth);
456
- }
457
- await this.transport.registerSocket(socket, resolvedAuth);
508
+ const handshake = await this.takeHandshake(socket);
509
+ if (!handshake) return;
510
+ ticket = handshake.ticket;
511
+ const { auth } = handshake;
512
+ ticket?.renew();
513
+ const registering = this.transport.registerSocket(socket, auth);
514
+ ticket?.release();
515
+ await registering;
458
516
  if (this.options.websocket?.emitConnectionEvent !== false) {
459
517
  socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
460
518
  connectionId: socket.id,
461
- traits: {
462
- userId: resolvedAuth.userId,
463
- tenantId: resolvedAuth.tenantId,
464
- roles: resolvedAuth.roles
465
- }
519
+ traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
466
520
  });
467
521
  }
468
522
  } catch (err) {
469
- this.logger.error(
470
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${internal.describeError(err)}`
471
- );
523
+ if (!(err instanceof internal.AuthenticationUnavailableError || err instanceof internal.ConnectionLimitError)) {
524
+ this.logger.error(
525
+ `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${internal.describeError(err)}`
526
+ );
527
+ }
528
+ socket.disconnect(true);
529
+ } finally {
530
+ ticket?.release();
531
+ }
532
+ }
533
+ admit(socket) {
534
+ const held = this.transport.admit();
535
+ const onClose = () => held.release();
536
+ socket.conn.once("close", onClose);
537
+ return {
538
+ release: () => {
539
+ socket.conn.off("close", onClose);
540
+ held.release();
541
+ },
542
+ renew: () => held.renew()
543
+ };
544
+ }
545
+ async takeHandshake(socket) {
546
+ const auth = this.authenticated.get(socket);
547
+ const ticket = this.tickets.get(socket);
548
+ this.authenticated.delete(socket);
549
+ this.tickets.delete(socket);
550
+ if (auth) return { auth, ticket };
551
+ if (this.transport.shuttingDown) {
472
552
  socket.disconnect(true);
553
+ return void 0;
554
+ }
555
+ const held = this.admit(socket);
556
+ try {
557
+ const fresh = await this.transport.authenticate(this.buildAuthContext(socket));
558
+ if (!fresh) {
559
+ socket.disconnect(true);
560
+ held.release();
561
+ return void 0;
562
+ }
563
+ const resolved = internal.resolveAuthTenant(this.options, fresh);
564
+ internal.assertIdentityIsNotBlank(resolved);
565
+ return { auth: internal.admitRooms(resolved), ticket: held };
566
+ } catch (err) {
567
+ held.release();
568
+ throw err;
473
569
  }
474
570
  }
475
571
  async handleDisconnect(socket) {