@bymax-one/nest-realtime 1.2.15 → 1.2.17

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.
@@ -108,17 +108,30 @@ function validateOptions(options) {
108
108
  );
109
109
  }
110
110
  validateHookTimeout(options);
111
+ validateOnConnectFailure(options);
111
112
  validateSseOptions(options);
112
113
  validateReauthPolicy(options);
113
114
  }
114
115
  var MAX_TIMER_MS = 2147483647;
116
+ var MAX_PER_USER_CONNECTIONS = 1e5;
117
+ var MAX_REPLAY_EVENTS = 1e5;
118
+ var MAX_HTTP_BUFFER_BYTES = 100 * 1024 * 1024;
115
119
  function assertInteger(path, value, least, most) {
116
120
  if (value === void 0) return;
117
- const valid = typeof value === "number" && Number.isInteger(value) && value >= least && (most === void 0 || value <= most);
121
+ const valid = typeof value === "number" && Number.isSafeInteger(value) && value >= least && (most === void 0 || value <= most);
118
122
  if (valid) return;
119
123
  throw realtimeError(
120
124
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
121
- `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}`,
125
+ `options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
126
+ { who: "BymaxRealtimeModule" }
127
+ );
128
+ }
129
+ function validateOnConnectFailure(options) {
130
+ const value = options.onConnectFailure;
131
+ if (value === void 0 || value === "ignore" || value === "close") return;
132
+ throw realtimeError(
133
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
134
+ `options.onConnectFailure must be 'ignore' or 'close', got ${String(value)}`,
122
135
  { who: "BymaxRealtimeModule" }
123
136
  );
124
137
  }
@@ -127,6 +140,18 @@ function validateHookTimeout(options) {
127
140
  assertInteger("authenticateTimeoutMs", options.authenticateTimeoutMs, 1, MAX_TIMER_MS);
128
141
  assertInteger("maxPendingHandshakes", options.maxPendingHandshakes, 1);
129
142
  assertInteger("maxConnections", options.maxConnections, 1);
143
+ assertInteger(
144
+ "websocket.maxConnectionsPerUser",
145
+ options.websocket?.maxConnectionsPerUser,
146
+ 0,
147
+ MAX_PER_USER_CONNECTIONS
148
+ );
149
+ assertInteger(
150
+ "websocket.maxHttpBufferSize",
151
+ options.websocket?.maxHttpBufferSize,
152
+ 1,
153
+ MAX_HTTP_BUFFER_BYTES
154
+ );
130
155
  assertInteger("websocket.pingIntervalMs", options.websocket?.pingIntervalMs, 1, MAX_TIMER_MS);
131
156
  assertInteger("websocket.pingTimeoutMs", options.websocket?.pingTimeoutMs, 1, MAX_TIMER_MS);
132
157
  }
@@ -166,18 +191,12 @@ function validateSseOptions(options) {
166
191
  { who: "BymaxRealtimeModule" }
167
192
  );
168
193
  }
169
- if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
170
- throw realtimeError(
171
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
172
- `options.sse.replayBufferSize must be >= 0`,
173
- { who: "BymaxRealtimeModule" }
174
- );
175
- }
194
+ assertInteger("sse.replayBufferSize", sse?.replayBufferSize, 0, MAX_REPLAY_EVENTS);
176
195
  assertInteger("sse.replayTtlMs", sse?.replayTtlMs, 1, MAX_TIMER_MS);
177
196
  assertInteger("sse.replayMaxIdleUsers", sse?.replayMaxIdleUsers, 1);
178
197
  for (const name of ["maxQueuedBytes", "maxQueuedEvents", "stallHeartbeats"]) {
179
198
  const value = sse?.[name];
180
- if (value !== void 0 && !(typeof value === "number" && Number.isInteger(value) && value >= 0)) {
199
+ if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
181
200
  throw realtimeError(
182
201
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
183
202
  `options.sse.${name} must be an integer >= 0 (0 switches the bound off), got ${String(value)}`,
@@ -185,13 +204,12 @@ function validateSseOptions(options) {
185
204
  );
186
205
  }
187
206
  }
188
- if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
189
- throw realtimeError(
190
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
191
- `options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
192
- { who: "BymaxRealtimeModule" }
193
- );
194
- }
207
+ assertInteger(
208
+ "sse.maxConnectionsPerUser",
209
+ sse?.maxConnectionsPerUser,
210
+ 0,
211
+ MAX_PER_USER_CONNECTIONS
212
+ );
195
213
  }
196
214
 
197
215
  // src/server/utils/describe-error.ts
@@ -216,11 +234,26 @@ function reportDeliveryFailure(logger, hooks, failure, what) {
216
234
  });
217
235
  }
218
236
 
237
+ // src/server/utils/windowed-report.ts
238
+ var REPORT_WINDOW_MS = 1e4;
239
+ function windowedReport(fresh, emit) {
240
+ let startedAt = Number.NEGATIVE_INFINITY;
241
+ let pending = fresh();
242
+ return (add) => {
243
+ pending = add(pending);
244
+ const now = performance.now();
245
+ if (now - startedAt < REPORT_WINDOW_MS) return;
246
+ startedAt = now;
247
+ const accumulated = pending;
248
+ pending = fresh();
249
+ emit(accumulated);
250
+ };
251
+ }
252
+
219
253
  // src/server/offline-queue/offline-queue-delivery.service.ts
220
254
  var RETRIEVE_LIMIT = 200;
221
255
  var DEFAULT_TIMEOUT_MS = 1e4;
222
256
  var DEFAULT_MAX_PENDING = 1e3;
223
- var REPORT_WINDOW_MS = 1e4;
224
257
  var OfflineQueueTimeoutError = class extends Error {
225
258
  constructor() {
226
259
  super("the offline queue did not answer in time");
@@ -239,8 +272,14 @@ var OfflineQueueDeliveryService = class {
239
272
  timeoutMs;
240
273
  maxPending;
241
274
  pending = 0;
242
- windowStartedAt = Number.NEGATIVE_INFINITY;
243
- timedOut = 0;
275
+ timeouts = windowedReport(
276
+ () => 0,
277
+ (count) => {
278
+ this.logger.warn(
279
+ `reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
280
+ );
281
+ }
282
+ );
244
283
  async retrieve(userId, lastEventId, ringBufferIds) {
245
284
  const { events } = await this.retrieveGap(userId, lastEventId);
246
285
  return events.filter((e) => !ringBufferIds.has(e.id));
@@ -316,15 +355,7 @@ var OfflineQueueDeliveryService = class {
316
355
  }
317
356
  }
318
357
  countTimeout() {
319
- this.timedOut += 1;
320
- const now = performance.now();
321
- if (now - this.windowStartedAt < REPORT_WINDOW_MS) return;
322
- this.windowStartedAt = now;
323
- const count = this.timedOut;
324
- this.timedOut = 0;
325
- this.logger.warn(
326
- `reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
327
- );
358
+ this.timeouts((count) => count + 1);
328
359
  }
329
360
  };
330
361
  OfflineQueueDeliveryService = __decorateClass([
@@ -360,12 +391,39 @@ var ROOM_PREFIXES = {
360
391
  RESOURCE: "resource"
361
392
  };
362
393
 
363
- // src/server/utils/admit-rooms.ts
394
+ // src/server/utils/reserved-room.ts
364
395
  var RESERVED_ROOM_PREFIXES = [
365
396
  `${ROOM_PREFIXES.USER}:`,
366
397
  `${ROOM_PREFIXES.TENANT}:`,
367
398
  "connection:"
368
399
  ];
400
+ function reservedRoomPrefix(room) {
401
+ return RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
402
+ }
403
+ function describeShape(value) {
404
+ if (value === null) return "null";
405
+ return Array.isArray(value) ? "an array" : typeof value;
406
+ }
407
+ function requireRoomName(operation, roomId) {
408
+ if (typeof roomId === "string" && roomId.length > 0) return;
409
+ throw realtimeError(
410
+ REALTIME_ERROR_CODES.AUTH_FAILED,
411
+ `${operation}: \`roomId\` must be a non-empty string, got ${describeShape(roomId)}`,
412
+ { who: "RealtimeService" }
413
+ );
414
+ }
415
+ function refuseReservedRoom(operation, roomId) {
416
+ requireRoomName(operation, roomId);
417
+ const prefix = reservedRoomPrefix(roomId);
418
+ if (prefix === void 0) return;
419
+ throw realtimeError(
420
+ REALTIME_ERROR_CODES.AUTH_FAILED,
421
+ `${operation}: \`roomId\` starts with the reserved prefix "${prefix}", which the library composes itself`,
422
+ { who: "RealtimeService" }
423
+ );
424
+ }
425
+
426
+ // src/server/utils/admit-rooms.ts
369
427
  function refuse(detail) {
370
428
  throw realtimeError(
371
429
  REALTIME_ERROR_CODES.AUTH_FAILED,
@@ -392,7 +450,7 @@ function admitRooms(auth) {
392
450
  if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
393
451
  refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
394
452
  }
395
- const reserved = RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
453
+ const reserved = reservedRoomPrefix(room);
396
454
  if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
397
455
  }
398
456
  return { ...auth, rooms: Object.freeze(admitted) };
@@ -457,7 +515,6 @@ function resolveClientAddress(request) {
457
515
  }
458
516
  return peerAddress(request.socket?.remoteAddress);
459
517
  }
460
- var REPORT_WINDOW_MS2 = 1e4;
461
518
  var AuthenticationUnavailableError = class extends Error {
462
519
  constructor(reason) {
463
520
  super(
@@ -478,8 +535,14 @@ var AuthenticationGate = class {
478
535
  maxPending;
479
536
  timeoutMs;
480
537
  pending = 0;
481
- windowStartedAt = Number.NEGATIVE_INFINITY;
482
- refused = { saturated: 0, timeout: 0 };
538
+ refusals = windowedReport(
539
+ () => ({ saturated: 0, timeout: 0 }),
540
+ ({ saturated, timeout }) => {
541
+ this.logger.warn(
542
+ `handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
543
+ );
544
+ }
545
+ );
483
546
  async authenticate(context) {
484
547
  if (this.pending >= this.maxPending) {
485
548
  this.refuse("saturated");
@@ -508,15 +571,7 @@ var AuthenticationGate = class {
508
571
  }
509
572
  }
510
573
  refuse(reason) {
511
- this.refused[reason] += 1;
512
- const now = performance.now();
513
- if (now - this.windowStartedAt < REPORT_WINDOW_MS2) return;
514
- this.windowStartedAt = now;
515
- const { saturated, timeout } = this.refused;
516
- this.refused = { saturated: 0, timeout: 0 };
517
- this.logger.warn(
518
- `handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
519
- );
574
+ this.refusals((refused) => ({ ...refused, [reason]: refused[reason] + 1 }));
520
575
  }
521
576
  };
522
577
  AuthenticationGate = __decorateClass([
@@ -594,7 +649,6 @@ ConnectionRegistry = __decorateClass([
594
649
  var DEFAULT_AUTHENTICATE_TIMEOUT_MS = 1e4;
595
650
  var DEFAULT_MAX_CONNECTIONS = 1e4;
596
651
  var HOLD_MARGIN_MS = 5e3;
597
- var REPORT_WINDOW_MS3 = 1e4;
598
652
  var ConnectionLimitError = class extends Error {
599
653
  constructor(limit) {
600
654
  super(`the instance already holds ${limit} connections`);
@@ -617,8 +671,14 @@ var ConnectionAdmission = class {
617
671
  max;
618
672
  holdMs;
619
673
  held = /* @__PURE__ */ new Map();
620
- windowStartedAt = Number.NEGATIVE_INFINITY;
621
- refused = 0;
674
+ refusals = windowedReport(
675
+ () => 0,
676
+ (count) => {
677
+ this.logger.warn(
678
+ `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
679
+ );
680
+ }
681
+ );
622
682
  admit() {
623
683
  const place = /* @__PURE__ */ Symbol("place");
624
684
  this.take(place);
@@ -650,15 +710,7 @@ var ConnectionAdmission = class {
650
710
  }
651
711
  }
652
712
  refuse() {
653
- this.refused += 1;
654
- const now = performance.now();
655
- if (now - this.windowStartedAt < REPORT_WINDOW_MS3) return;
656
- this.windowStartedAt = now;
657
- const count = this.refused;
658
- this.refused = 0;
659
- this.logger.warn(
660
- `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
661
- );
713
+ this.refusals((count) => count + 1);
662
714
  }
663
715
  };
664
716
  ConnectionAdmission = __decorateClass([
@@ -767,7 +819,12 @@ function composeRoomId(prefix, ...parts) {
767
819
  }
768
820
  function unavailableError(code, who, what, cause) {
769
821
  const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
770
- return Object.assign(new ServiceUnavailableException(), { code, message, cause });
822
+ const error = Object.assign(new ServiceUnavailableException(), { code });
823
+ Object.defineProperties(error, {
824
+ message: { value: message, enumerable: false, writable: true, configurable: true },
825
+ cause: { value: cause, enumerable: false, writable: true, configurable: true }
826
+ });
827
+ return error;
771
828
  }
772
829
  var InMemoryPubSub = class {
773
830
  handlers = /* @__PURE__ */ new Set();
@@ -1177,6 +1234,7 @@ var SseTransport = class {
1177
1234
  await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
1178
1235
  }
1179
1236
  async emitToRoom(roomId, event, data) {
1237
+ requireRoomName("emitToRoom", roomId);
1180
1238
  const id = this.idGen.next();
1181
1239
  this.emitToRoomLocal(roomId, event, data, id);
1182
1240
  await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
@@ -1187,10 +1245,12 @@ var SseTransport = class {
1187
1245
  await this.publish({ op: "broadcast", args: { event, data, id } });
1188
1246
  }
1189
1247
  async joinRoom(connectionId, roomId) {
1248
+ refuseReservedRoom("joinRoom", roomId);
1190
1249
  if (this.connections.get(connectionId)?.transport === "sse")
1191
1250
  this.rooms.join(connectionId, roomId);
1192
1251
  }
1193
1252
  async leaveRoom(connectionId, roomId) {
1253
+ refuseReservedRoom("leaveRoom", roomId);
1194
1254
  if (this.connections.get(connectionId)?.transport === "sse")
1195
1255
  this.rooms.leave(connectionId, roomId);
1196
1256
  }
@@ -1633,7 +1693,10 @@ var SseSubscriptionHandler = class {
1633
1693
  }
1634
1694
  const record = this.transport.getConnection(connectionId);
1635
1695
  if (record) {
1636
- this.fireHook(() => this.hooks?.onConnect?.(buildMeta(record)));
1696
+ this.fireHook(
1697
+ () => this.hooks?.onConnect?.(buildMeta(record)),
1698
+ this.options.onConnectFailure === "close" ? () => subscriber.complete() : void 0
1699
+ );
1637
1700
  }
1638
1701
  const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
1639
1702
  this.heartbeat.start(
@@ -1643,9 +1706,11 @@ var SseSubscriptionHandler = class {
1643
1706
  () => this.transport.checkStall(connectionId)
1644
1707
  );
1645
1708
  }
1646
- fireHook(invoke) {
1709
+ fireHook(invoke, onFailure) {
1647
1710
  void runHook(invoke).then((failed) => {
1648
- if (failed) this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
1711
+ if (!failed) return;
1712
+ this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
1713
+ onFailure?.();
1649
1714
  });
1650
1715
  }
1651
1716
  };
@@ -1724,16 +1789,19 @@ var RealtimeService = class {
1724
1789
  emitToTenant(tenantId, event, data) {
1725
1790
  return this.transport.emitToTenant(tenantId, event, data);
1726
1791
  }
1727
- emitToRoom(roomId, event, data) {
1792
+ async emitToRoom(roomId, event, data) {
1793
+ requireRoomName("emitToRoom", roomId);
1728
1794
  return this.transport.emitToRoom(roomId, event, data);
1729
1795
  }
1730
1796
  broadcast(event, data) {
1731
1797
  return this.transport.broadcast(event, data);
1732
1798
  }
1733
- joinRoom(connectionId, roomId) {
1799
+ async joinRoom(connectionId, roomId) {
1800
+ refuseReservedRoom("joinRoom", roomId);
1734
1801
  return this.transport.joinRoom(connectionId, roomId);
1735
1802
  }
1736
- leaveRoom(connectionId, roomId) {
1803
+ async leaveRoom(connectionId, roomId) {
1804
+ refuseReservedRoom("leaveRoom", roomId);
1737
1805
  return this.transport.leaveRoom(connectionId, roomId);
1738
1806
  }
1739
1807
  disconnect(connectionId, reason) {
@@ -2037,26 +2105,54 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2037
2105
  logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
2038
2106
  return resolved;
2039
2107
  }
2040
- function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2041
- const moduleName = moduleClass.name;
2108
+ function assertOneFactoryPattern(asyncOptions, moduleName) {
2042
2109
  const patterns = [
2043
2110
  asyncOptions.useFactory,
2044
2111
  asyncOptions.useClass,
2045
2112
  asyncOptions.useExisting
2046
2113
  ].filter((pattern) => pattern !== void 0);
2047
- if (patterns.length !== 1) {
2048
- throw realtimeError(
2049
- REALTIME_ERROR_CODES.INVALID_OPTIONS,
2050
- `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
2051
- { who: moduleName }
2052
- );
2114
+ if (patterns.length === 1) return;
2115
+ throw realtimeError(
2116
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
2117
+ `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
2118
+ { who: moduleName }
2119
+ );
2120
+ }
2121
+ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2122
+ if (asyncOptions.useFactory) {
2123
+ return {
2124
+ provide: REALTIME_OPTIONS_TOKEN,
2125
+ useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2126
+ inject: [...asyncOptions.inject ?? []]
2127
+ };
2053
2128
  }
2054
- assertModeSupported(wiring, asyncOptions.transport, moduleName);
2055
- assertSseEndpointApplies(asyncOptions, moduleName);
2056
- const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2057
- const instanceId = randomUUID();
2058
- const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2059
- const resolve = (raw, source) => {
2129
+ return {
2130
+ provide: REALTIME_OPTIONS_TOKEN,
2131
+ useFactory: async (factory) => resolve(
2132
+ await factory.createRealtimeOptions(),
2133
+ "createRealtimeOptions"
2134
+ ),
2135
+ inject: [asyncOptions.useExisting ?? factoryToken]
2136
+ };
2137
+ }
2138
+ function fromOptions(token, read) {
2139
+ return { provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] };
2140
+ }
2141
+ function buildOptionDerivedProviders(logger, instanceId) {
2142
+ return [
2143
+ fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
2144
+ fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
2145
+ warnIfSingleInstance(opts.pubsub, opts.transport, logger);
2146
+ return opts.pubsub ?? new InMemoryPubSub();
2147
+ }),
2148
+ fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
2149
+ { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2150
+ fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
2151
+ fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence)
2152
+ ];
2153
+ }
2154
+ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
2155
+ return (raw, source) => {
2060
2156
  const resolved = resolveAsyncOptions(
2061
2157
  raw,
2062
2158
  asyncOptions.transport,
@@ -2068,20 +2164,17 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2068
2164
  if (asyncOptions.transport === "websocket") return resolved;
2069
2165
  return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
2070
2166
  };
2071
- const resolvedOptionsProvider = asyncOptions.useFactory ? {
2072
- provide: REALTIME_OPTIONS_TOKEN,
2073
- useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
2074
- inject: [...asyncOptions.inject ?? []]
2075
- } : {
2076
- provide: REALTIME_OPTIONS_TOKEN,
2077
- useFactory: async (factory) => resolve(
2078
- await factory.createRealtimeOptions(),
2079
- "createRealtimeOptions"
2080
- ),
2081
- inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
2082
- };
2167
+ }
2168
+ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2169
+ const moduleName = moduleClass.name;
2170
+ assertOneFactoryPattern(asyncOptions, moduleName);
2171
+ assertModeSupported(wiring, asyncOptions.transport, moduleName);
2172
+ assertSseEndpointApplies(asyncOptions, moduleName);
2173
+ const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2174
+ const instanceId = randomUUID();
2175
+ const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2176
+ const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
2083
2177
  const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2084
- const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
2085
2178
  const { providers: transportProviders, controllers } = wiring.buildAsync({
2086
2179
  mode: asyncOptions.transport,
2087
2180
  sseEndpoint: boundSseEndpoint
@@ -2092,16 +2185,8 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2092
2185
  controllers,
2093
2186
  providers: [
2094
2187
  ...factoryClassProvider,
2095
- resolvedOptionsProvider,
2096
- fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
2097
- fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
2098
- warnIfSingleInstance(opts.pubsub, opts.transport, logger);
2099
- return opts.pubsub ?? new InMemoryPubSub();
2100
- }),
2101
- fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
2102
- { provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
2103
- fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
2104
- fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
2188
+ buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
2189
+ ...buildOptionDerivedProviders(logger, instanceId),
2105
2190
  ...SHARED_SERVICES,
2106
2191
  ...transportProviders,
2107
2192
  ...asyncOptions.extraProviders ?? []
@@ -2133,9 +2218,17 @@ var RealtimePubSubSubscriber = class {
2133
2218
  this.unsubscribe = null;
2134
2219
  }
2135
2220
  }
2221
+ dropped = windowedReport(
2222
+ () => ({ count: 0, last: "none" }),
2223
+ ({ count, last }) => {
2224
+ this.logger.warn(
2225
+ `Pub/sub dropped ${count} message(s) it could not act on since the last report (last: ${last})`
2226
+ );
2227
+ }
2228
+ );
2136
2229
  handle(msg) {
2137
- if (msg.origin === this.instanceId) return;
2138
2230
  try {
2231
+ if (msg.origin === this.instanceId) return;
2139
2232
  switch (msg.op) {
2140
2233
  case "emitToUser": {
2141
2234
  const a = msg.args;
@@ -2169,14 +2262,17 @@ var RealtimePubSubSubscriber = class {
2169
2262
  break;
2170
2263
  }
2171
2264
  default: {
2172
- const exhaustive = msg.op;
2173
- this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
2265
+ msg.op;
2266
+ this.drop("unknown op");
2174
2267
  }
2175
2268
  }
2176
2269
  } catch (err) {
2177
- this.logger.warn(`Pub/sub message handling failed: ${describeError(err)}`);
2270
+ this.drop(String(Object(err).constructor?.name ?? "Error"));
2178
2271
  }
2179
2272
  }
2273
+ drop(last) {
2274
+ this.dropped(({ count }) => ({ count: count + 1, last }));
2275
+ }
2180
2276
  };
2181
2277
  RealtimePubSubSubscriber = __decorateClass([
2182
2278
  Injectable(),
@@ -2265,6 +2361,7 @@ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
2265
2361
  "end"
2266
2362
  ]);
2267
2363
  var PUBLISHER_WAIT_MS = 2e3;
2364
+ var PUBLISH_WAIT_MS = 2e3;
2268
2365
  var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
2269
2366
  function connectionReason(err) {
2270
2367
  const code = err?.code;
@@ -2296,7 +2393,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2296
2393
  this.connectLazyClient();
2297
2394
  throw this.cannotPublish(`the Redis client is ${status}`);
2298
2395
  }
2299
- await this.#pub.publish(this.channel, JSON.stringify(message));
2396
+ const sent = this.#pub.publish(this.channel, JSON.stringify(message));
2397
+ let timer;
2398
+ const expired = new Promise((_resolve, reject) => {
2399
+ timer = setTimeout(
2400
+ () => reject(this.cannotPublish(`the server did not answer within ${PUBLISH_WAIT_MS} ms`)),
2401
+ PUBLISH_WAIT_MS
2402
+ );
2403
+ timer.unref();
2404
+ });
2405
+ try {
2406
+ await Promise.race([sent, expired]);
2407
+ } finally {
2408
+ clearTimeout(timer);
2409
+ }
2300
2410
  }
2301
2411
  connectLazyClient() {
2302
2412
  if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
@@ -2455,7 +2565,12 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2455
2565
  dispatch(payload) {
2456
2566
  let msg;
2457
2567
  try {
2458
- msg = JSON.parse(payload);
2568
+ const parsed = JSON.parse(payload);
2569
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2570
+ this.reportMalformed();
2571
+ return;
2572
+ }
2573
+ msg = parsed;
2459
2574
  } catch {
2460
2575
  this.reportMalformed();
2461
2576
  return;
@@ -2532,4 +2647,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2532
2647
  }
2533
2648
  };
2534
2649
 
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 };
2650
+ 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, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };