@bymax-one/nest-realtime 1.2.18 → 1.2.20

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,5 +1,5 @@
1
1
  import { randomUUID } from 'crypto';
2
- import { Injectable, Optional, Inject, Logger, Global, Module, ServiceUnavailableException, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, UnauthorizedException } from '@nestjs/common';
2
+ import { Injectable, Optional, Inject, Logger, Global, Module, ServiceUnavailableException, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, HttpStatus, UnauthorizedException } from '@nestjs/common';
3
3
  import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
4
4
  import { takeUntil, catchError, finalize } from 'rxjs/operators';
5
5
  import { isIP } from 'net';
@@ -41,6 +41,16 @@ var REALTIME_ERROR_CODES = {
41
41
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
42
42
  };
43
43
 
44
+ // src/server/utils/is-plain-object.ts
45
+ function isPlainObject(value) {
46
+ if (typeof value !== "object") return false;
47
+ try {
48
+ return Object.prototype.toString.call(value) === "[object Object]";
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
44
54
  // src/server/config/drop-unset.ts
45
55
  var SSE_KEYS = {
46
56
  endpoint: true,
@@ -105,8 +115,7 @@ function dropUnset(options) {
105
115
  const kept = readSet(options, TOP_LEVEL_KEYS);
106
116
  for (const [group, keys] of Object.entries(GROUPS)) {
107
117
  const value = kept[group];
108
- if (typeof value === "object" && !Array.isArray(value))
109
- kept[group] = readSet(value, keys);
118
+ if (isPlainObject(value)) kept[group] = readSet(value, keys);
110
119
  }
111
120
  return kept;
112
121
  }
@@ -132,6 +141,30 @@ function applyDefaults(raw) {
132
141
  });
133
142
  }
134
143
 
144
+ // src/server/utils/realtime-error.ts
145
+ function realtimeError(code, detail, options = {}) {
146
+ const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
147
+ const message = `${lead}: ${detail}`;
148
+ const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
149
+ return Object.assign(error, { code });
150
+ }
151
+
152
+ // src/server/config/guard-host-reads.ts
153
+ var LIBRARY_CODES = new Set(Object.values(REALTIME_ERROR_CODES));
154
+ var isLibraryError = (error) => error instanceof Error && LIBRARY_CODES.has(error.code);
155
+ function guardHostReads(what, read) {
156
+ try {
157
+ return read();
158
+ } catch (error) {
159
+ if (isLibraryError(error)) throw error;
160
+ throw realtimeError(
161
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
162
+ `${what} could not be read: a getter or a proxy on it throws`,
163
+ { who: "BymaxRealtimeModule", cause: error }
164
+ );
165
+ }
166
+ }
167
+
135
168
  // src/server/constants/injection-tokens.constants.ts
136
169
  var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
137
170
  var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
@@ -160,15 +193,18 @@ function describeReceived(value) {
160
193
  return Number.isFinite(value) ? String(value) : "a number that is not finite";
161
194
  }
162
195
  if (value === null) return "null";
163
- return Array.isArray(value) ? "an array" : KIND_OF_TYPE[typeof value] ?? "an object";
196
+ if (Array.isArray(value)) return "an array";
197
+ if (typeof value === "object" && !isPlainObject(value)) return "a built-in object";
198
+ return KIND_OF_TYPE[typeof value] ?? "an object";
164
199
  }
165
200
 
166
- // src/server/utils/realtime-error.ts
167
- function realtimeError(code, detail, options = {}) {
168
- const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
169
- const message = `${lead}: ${detail}`;
170
- const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
171
- return Object.assign(error, { code });
201
+ // src/server/utils/refuse-object.ts
202
+ function refuseObject(who, path, value) {
203
+ throw realtimeError(
204
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
205
+ `${path} must be an object, received ${describeReceived(value)}`,
206
+ { who }
207
+ );
172
208
  }
173
209
 
174
210
  // src/server/config/validate-shapes.ts
@@ -192,11 +228,8 @@ function refuse(path, expected, received) {
192
228
  { who: "BymaxRealtimeModule" }
193
229
  );
194
230
  }
195
- function isObject(value) {
196
- return typeof value === "object" && value !== null && !Array.isArray(value);
197
- }
198
231
  function assertObject(path, value) {
199
- if (value !== void 0 && !isObject(value)) refuse(path, "an object", value);
232
+ if (value !== void 0 && !isPlainObject(value)) refuse(path, "an object", value);
200
233
  }
201
234
  function assertFunction(path, value) {
202
235
  if (typeof value !== "function") refuse(path, "a function", value);
@@ -207,10 +240,15 @@ function assertOptionalFunction(path, value) {
207
240
  function assertBoolean(path, value) {
208
241
  if (value !== void 0 && typeof value !== "boolean") refuse(path, "a boolean", value);
209
242
  }
210
- function assertEndpoint(path, value) {
211
- if (value !== void 0 && !(typeof value === "string" && value.trim().length > 0)) {
243
+ function assertSseEndpoint(path, value) {
244
+ if (value === void 0 || value === null) return;
245
+ if (typeof value !== "string" || value.trim().length === 0) {
212
246
  refuse(path, "a non-blank string", value);
213
247
  }
248
+ if (/\s/.test(value)) refuse(path, "a string without whitespace", value);
249
+ }
250
+ function assertOptionsObject(value, who = "BymaxRealtimeModule") {
251
+ if (!isPlainObject(value)) refuseObject(who, "options", value);
214
252
  }
215
253
  function validatePieces(options) {
216
254
  for (const [name, functions] of Object.entries(REQUIRED_FUNCTIONS)) {
@@ -235,12 +273,37 @@ function validateShapes(options) {
235
273
  assertOptionalFunction("tenantResolver", options.tenantResolver);
236
274
  assertBoolean("sse.emitConnectionEvent", options.sse?.emitConnectionEvent);
237
275
  assertBoolean("websocket.emitConnectionEvent", options.websocket?.emitConnectionEvent);
238
- assertEndpoint("sse.endpoint", options.sse?.endpoint);
276
+ assertSseEndpoint("sse.endpoint", options.sse?.endpoint);
277
+ }
278
+ function assertExtraProviders(value) {
279
+ if (value === void 0 || value === null) return;
280
+ if (!Array.isArray(value)) {
281
+ throw realtimeError(
282
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
283
+ `extraProviders must be an array of providers, received ${describeReceived(value)}`,
284
+ { who: "BymaxRealtimeModule" }
285
+ );
286
+ }
287
+ value.forEach((entry, index) => {
288
+ const isClass = typeof entry === "function";
289
+ const hasProvide = isPlainObject(entry) && "provide" in entry;
290
+ if (isClass || hasProvide) return;
291
+ const received = isPlainObject(entry) && !Array.isArray(entry) ? "an object with no provide" : describeReceived(entry);
292
+ throw realtimeError(
293
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
294
+ `extraProviders[${index}] must be a provider (a class or an object with provide), received ${received}`,
295
+ { who: "BymaxRealtimeModule" }
296
+ );
297
+ });
239
298
  }
240
299
 
241
300
  // src/server/config/validate-options.ts
242
301
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
243
302
  function validateOptions(raw) {
303
+ guardHostReads("the options", () => validateReadOptions(raw));
304
+ }
305
+ function validateReadOptions(raw) {
306
+ assertOptionsObject(raw);
244
307
  const options = dropUnset(raw);
245
308
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
246
309
  throw realtimeError(
@@ -331,12 +394,6 @@ function validateReauthPolicy(options) {
331
394
  { who: "BymaxRealtimeModule" }
332
395
  );
333
396
  }
334
- if (policy?.cacheTtlMs !== void 0 && policy.intervalSeconds !== void 0 && policy.cacheTtlMs > policy.intervalSeconds * 1e3) {
335
- Logger.warn(
336
- `[BymaxRealtimeModule] reauthenticationPolicy.cacheTtlMs (${policy.cacheTtlMs} ms) exceeds intervalSeconds*1000 (${policy.intervalSeconds * 1e3} ms): the positive reauth cache outlives the interval, so revalidate is skipped on ticks within the cache window \u2014 reauthentication is effectively weakened`,
337
- "BymaxRealtimeModule"
338
- );
339
- }
340
397
  }
341
398
  function validateSseOptions(options) {
342
399
  const sse = options.sse;
@@ -368,6 +425,138 @@ function validateSseOptions(options) {
368
425
  MAX_PER_USER_CONNECTIONS
369
426
  );
370
427
  }
428
+ var REFUSAL_REASONS = ["limit", "unauthorized", "unavailable", "error"];
429
+ var EVICTION_REASONS = ["per_user_cap", "slow_consumer", "revoked"];
430
+ var TALLY_TRANSPORTS = ["sse", "websocket"];
431
+ function zeroed(keys) {
432
+ return Object.fromEntries(keys.map((key) => [key, 0]));
433
+ }
434
+ var _refused, _evicted, _emitted, _slowConsumerDrops;
435
+ var RealtimeMetricsTally = class {
436
+ constructor() {
437
+ __privateAdd(this, _refused, zeroed(REFUSAL_REASONS));
438
+ __privateAdd(this, _evicted, zeroed(EVICTION_REASONS));
439
+ __privateAdd(this, _emitted, zeroed(TALLY_TRANSPORTS));
440
+ __privateAdd(this, _slowConsumerDrops, 0);
441
+ }
442
+ refused(reason) {
443
+ __privateGet(this, _refused)[reason] += 1;
444
+ }
445
+ evicted(reason) {
446
+ __privateGet(this, _evicted)[reason] += 1;
447
+ }
448
+ emitted(transport) {
449
+ __privateGet(this, _emitted)[transport] += 1;
450
+ }
451
+ slowConsumerDropped() {
452
+ __privateSet(this, _slowConsumerDrops, __privateGet(this, _slowConsumerDrops) + 1);
453
+ }
454
+ snapshot() {
455
+ return {
456
+ refused: { ...__privateGet(this, _refused) },
457
+ evicted: { ...__privateGet(this, _evicted) },
458
+ emitted: { ...__privateGet(this, _emitted) },
459
+ slowConsumerDrops: __privateGet(this, _slowConsumerDrops)
460
+ };
461
+ }
462
+ };
463
+ _refused = new WeakMap();
464
+ _evicted = new WeakMap();
465
+ _emitted = new WeakMap();
466
+ _slowConsumerDrops = new WeakMap();
467
+ RealtimeMetricsTally = __decorateClass([
468
+ Injectable()
469
+ ], RealtimeMetricsTally);
470
+ var STATUS_ERROR = 2;
471
+ var TRACER_NAME = "@bymax-one/nest-realtime";
472
+ var LIBRARY_CODE = /^REALTIME_[A-Z_]+$/;
473
+ function codeOf(error) {
474
+ if (typeof error !== "object" || error === null) return "REALTIME_ERROR";
475
+ const { code, message, data } = error;
476
+ for (const candidate of [code, data?.code, message]) {
477
+ if (typeof candidate === "string" && LIBRARY_CODE.test(candidate)) return candidate;
478
+ }
479
+ return "REALTIME_ERROR";
480
+ }
481
+ var _api;
482
+ var RealtimeTracing = class {
483
+ constructor() {
484
+ __privateAdd(this, _api);
485
+ }
486
+ async onModuleInit() {
487
+ try {
488
+ __privateSet(this, _api, await import('@opentelemetry/api'));
489
+ } catch {
490
+ }
491
+ }
492
+ async traced(span, run) {
493
+ let result;
494
+ try {
495
+ result = await run();
496
+ } catch (error) {
497
+ attempt(() => span.setStatus({ code: STATUS_ERROR, message: codeOf(error) }));
498
+ attempt(() => span.end());
499
+ throw error;
500
+ }
501
+ attempt(() => span.end());
502
+ return result;
503
+ }
504
+ span(name, attributes, run) {
505
+ const api = __privateGet(this, _api);
506
+ if (!api) return run();
507
+ const latch = { claimed: false };
508
+ attempt(
509
+ () => api.trace.getTracer(TRACER_NAME).startActiveSpan(name, { attributes }, (span) => {
510
+ if (!latch.claimed) {
511
+ latch.claimed = true;
512
+ latch.started = this.traced(span, run);
513
+ }
514
+ return latch.started;
515
+ })
516
+ );
517
+ if (latch.started) return latch.started;
518
+ latch.claimed = true;
519
+ return run();
520
+ }
521
+ };
522
+ _api = new WeakMap();
523
+ RealtimeTracing = __decorateClass([
524
+ Injectable()
525
+ ], RealtimeTracing);
526
+ function attempt(call) {
527
+ try {
528
+ Promise.resolve(call()).catch(() => void 0);
529
+ } catch {
530
+ }
531
+ }
532
+
533
+ // src/server/utils/log-event.ts
534
+ var REALTIME_LOG_EVENTS = [
535
+ "REALTIME_REAUTH_CACHE_WEAKENS_POLICY",
536
+ "REALTIME_HANDSHAKE_FAILED",
537
+ "REALTIME_HOOK_FAILED",
538
+ "REALTIME_DELIVERY_FAILED",
539
+ "REALTIME_SLOW_CONSUMER",
540
+ "REALTIME_DISCONNECT_FAILED",
541
+ "REALTIME_RECONNECTS_GIVEN_UP",
542
+ "REALTIME_OFFLINE_QUEUE_LIMIT",
543
+ "REALTIME_OFFLINE_QUEUE_ACK_FAILED",
544
+ "REALTIME_PUBSUB_NOT_PROVIDED",
545
+ "REALTIME_PUBSUB_UNSUBSCRIBE_FAILED",
546
+ "REALTIME_PUBSUB_DROPPED",
547
+ "REALTIME_PUBSUB_UNAVAILABLE",
548
+ "REALTIME_CONNECTIONS_REFUSED",
549
+ "REALTIME_HANDSHAKES_REFUSED",
550
+ "REALTIME_REAUTH_FAILED",
551
+ "REALTIME_REVOCATION_FAILED",
552
+ "REALTIME_ADAPTER_MISSING",
553
+ "REALTIME_ADAPTER_COMMAND_FAILED",
554
+ "REALTIME_COMPOSITE_PARTIAL_FAILURE",
555
+ "REALTIME_SERVER_NOT_ATTACHED"
556
+ ];
557
+ function logEvent(logger, level, event, message, fields = {}, error) {
558
+ logger[level]({ event, message, ...fields, ...error === void 0 ? {} : { err: error } });
559
+ }
371
560
 
372
561
  // src/server/utils/describe-error.ts
373
562
  function describeError(reason) {
@@ -381,13 +570,32 @@ function describeError(reason) {
381
570
 
382
571
  // src/server/utils/report-delivery-failure.ts
383
572
  function reportDeliveryFailure(logger, hooks, failure, what) {
384
- logger.warn(`${failure.code} op=${failure.op}: ${what}: ${describeError(failure.error)}`);
573
+ logEvent(
574
+ logger,
575
+ "warn",
576
+ "REALTIME_DELIVERY_FAILED",
577
+ `${what}`,
578
+ {
579
+ code: failure.code,
580
+ op: failure.op
581
+ },
582
+ failure.error
583
+ );
385
584
  const reported = {
386
585
  ...failure,
387
586
  error: failure.error instanceof Error ? failure.error : new Error(describeError(failure.error))
388
587
  };
389
588
  void Promise.resolve().then(() => hooks?.onDeliveryFailure?.(reported)).catch((err) => {
390
- logger.warn(`onDeliveryFailure hook failed: ${describeError(err)}`);
589
+ logEvent(
590
+ logger,
591
+ "warn",
592
+ "REALTIME_HOOK_FAILED",
593
+ `onDeliveryFailure hook failed`,
594
+ {
595
+ hook: "onDeliveryFailure"
596
+ },
597
+ err
598
+ );
391
599
  });
392
600
  }
393
601
 
@@ -432,8 +640,12 @@ var OfflineQueueDeliveryService = class {
432
640
  timeouts = windowedReport(
433
641
  () => 0,
434
642
  (count) => {
435
- this.logger.warn(
436
- `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`
643
+ logEvent(
644
+ this.logger,
645
+ "warn",
646
+ "REALTIME_RECONNECTS_GIVEN_UP",
647
+ `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`,
648
+ { count, timeoutMs: this.timeoutMs, maxPending: this.maxPending }
437
649
  );
438
650
  }
439
651
  );
@@ -462,8 +674,12 @@ var OfflineQueueDeliveryService = class {
462
674
  return { events: [], degraded: true };
463
675
  }
464
676
  if (events.length === RETRIEVE_LIMIT) {
465
- this.logger.warn(
466
- `Offline queue retrieve hit the ${RETRIEVE_LIMIT}-event limit for user; older gap events may be dropped.`
677
+ logEvent(
678
+ this.logger,
679
+ "warn",
680
+ "REALTIME_OFFLINE_QUEUE_LIMIT",
681
+ `Offline queue retrieve hit the ${RETRIEVE_LIMIT}-event limit for user; older gap events may be dropped.`,
682
+ { limit: RETRIEVE_LIMIT }
467
683
  );
468
684
  }
469
685
  return { events, degraded: false };
@@ -474,7 +690,14 @@ var OfflineQueueDeliveryService = class {
474
690
  try {
475
691
  await this.storage.acknowledge(userId, lastId);
476
692
  } catch (err) {
477
- this.logger.warn(`Offline queue acknowledge failed: ${describeError(err)}`);
693
+ logEvent(
694
+ this.logger,
695
+ "warn",
696
+ "REALTIME_OFFLINE_QUEUE_ACK_FAILED",
697
+ `Offline queue acknowledge failed`,
698
+ {},
699
+ err
700
+ );
478
701
  }
479
702
  }
480
703
  async retrieveAppended(userId, lastEventId, read) {
@@ -680,6 +903,7 @@ var AuthenticationUnavailableError = class extends Error {
680
903
  this.reason = reason;
681
904
  }
682
905
  reason;
906
+ code = REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE;
683
907
  };
684
908
  var AuthenticationGate = class {
685
909
  constructor(options, authenticator) {
@@ -695,8 +919,17 @@ var AuthenticationGate = class {
695
919
  refusals = windowedReport(
696
920
  () => ({ saturated: 0, timeout: 0 }),
697
921
  ({ saturated, timeout }) => {
698
- this.logger.warn(
699
- `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`
922
+ logEvent(
923
+ this.logger,
924
+ "warn",
925
+ "REALTIME_HANDSHAKES_REFUSED",
926
+ `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`,
927
+ {
928
+ saturated,
929
+ timedOut: timeout,
930
+ maxPendingHandshakes: this.maxPending,
931
+ authenticateTimeoutMs: this.timeoutMs
932
+ }
700
933
  );
701
934
  }
702
935
  );
@@ -812,6 +1045,7 @@ var ConnectionLimitError = class extends Error {
812
1045
  this.limit = limit;
813
1046
  }
814
1047
  limit;
1048
+ code = REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE;
815
1049
  };
816
1050
  var UNBOUNDED_TICKET = {
817
1051
  release: () => void 0,
@@ -831,8 +1065,12 @@ var ConnectionAdmission = class {
831
1065
  refusals = windowedReport(
832
1066
  () => 0,
833
1067
  (count) => {
834
- this.logger.warn(
835
- `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
1068
+ logEvent(
1069
+ this.logger,
1070
+ "warn",
1071
+ "REALTIME_CONNECTIONS_REFUSED",
1072
+ `connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`,
1073
+ { count, maxConnections: this.max }
836
1074
  );
837
1075
  }
838
1076
  );
@@ -975,7 +1213,7 @@ function composeRoomId(prefix, ...parts) {
975
1213
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
976
1214
  }
977
1215
  function unavailableError(code, who, what, cause) {
978
- const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
1216
+ const { message } = realtimeError(code, what, { who });
979
1217
  const error = Object.assign(new ServiceUnavailableException(), { code });
980
1218
  Object.defineProperties(error, {
981
1219
  message: { value: message, enumerable: false, writable: true, configurable: true },
@@ -1216,7 +1454,7 @@ var StallWatch = class {
1216
1454
  // src/server/transports/sse/sse.transport.ts
1217
1455
  var _shuttingDown;
1218
1456
  var SseTransport = class {
1219
- constructor(connections, rooms, replayBuffer, idGen, heartbeat, gate, pubsub, hooks, options, instanceId, offlineQueue, admission) {
1457
+ constructor(connections, rooms, replayBuffer, idGen, heartbeat, gate, pubsub, hooks, options, instanceId, offlineQueue, admission, tally) {
1220
1458
  this.connections = connections;
1221
1459
  this.rooms = rooms;
1222
1460
  this.replayBuffer = replayBuffer;
@@ -1229,6 +1467,7 @@ var SseTransport = class {
1229
1467
  this.instanceId = instanceId;
1230
1468
  this.offlineQueue = offlineQueue;
1231
1469
  this.admission = admission;
1470
+ this.tally = tally;
1232
1471
  __publicField(this, "kind", "sse");
1233
1472
  __publicField(this, "logger", new Logger(SseTransport.name));
1234
1473
  __privateAdd(this, _shuttingDown, false);
@@ -1246,6 +1485,7 @@ var SseTransport = class {
1246
1485
  instanceId;
1247
1486
  offlineQueue;
1248
1487
  admission;
1488
+ tally;
1249
1489
  onModuleDestroy() {
1250
1490
  __privateSet(this, _shuttingDown, true);
1251
1491
  }
@@ -1332,7 +1572,18 @@ var SseTransport = class {
1332
1572
  }),
1333
1573
  this.options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
1334
1574
  );
1335
- if (failed) this.logger.error(`onDisconnect hook failed: ${describeError(failed.error)}`);
1575
+ if (failed) {
1576
+ logEvent(
1577
+ this.logger,
1578
+ "error",
1579
+ "REALTIME_HOOK_FAILED",
1580
+ `onDisconnect hook failed`,
1581
+ {
1582
+ hook: "onDisconnect"
1583
+ },
1584
+ failed.error
1585
+ );
1586
+ }
1336
1587
  }
1337
1588
  getReplayEvents(userId, lastEventId) {
1338
1589
  return this.replayBuffer.since(userId, lastEventId);
@@ -1434,15 +1685,18 @@ var SseTransport = class {
1434
1685
  }
1435
1686
  emitToUserLocal(userId, event, data, id) {
1436
1687
  const message = this.buildMessage(id, event, data);
1688
+ this.tally?.emitted("sse");
1437
1689
  this.replayBuffer.append(userId, message);
1438
1690
  for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
1439
1691
  }
1440
1692
  emitToTenantLocal(tenantId, event, data, id) {
1441
1693
  const message = this.buildMessage(id, event, data);
1694
+ this.tally?.emitted("sse");
1442
1695
  for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
1443
1696
  }
1444
1697
  emitToRoomLocal(roomId, event, data, id) {
1445
1698
  const message = this.buildMessage(id, event, data);
1699
+ this.tally?.emitted("sse");
1446
1700
  for (const connectionId of this.rooms.members(roomId)) {
1447
1701
  const conn = this.connections.get(connectionId);
1448
1702
  if (conn && conn.transport === "sse") this.deliver(conn, message);
@@ -1450,6 +1704,7 @@ var SseTransport = class {
1450
1704
  }
1451
1705
  broadcastLocal(event, data, id) {
1452
1706
  const message = this.buildMessage(id, event, data);
1707
+ this.tally?.emitted("sse");
1453
1708
  for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
1454
1709
  }
1455
1710
  async disconnectLocal(connectionId, reason) {
@@ -1472,7 +1727,16 @@ var SseTransport = class {
1472
1727
  }
1473
1728
  conn.subject?.next(message);
1474
1729
  } catch (error) {
1475
- this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
1730
+ logEvent(
1731
+ this.logger,
1732
+ "warn",
1733
+ "REALTIME_DELIVERY_FAILED",
1734
+ `SSE delivery failed`,
1735
+ {
1736
+ connectionId: conn.connectionId
1737
+ },
1738
+ error
1739
+ );
1476
1740
  }
1477
1741
  }
1478
1742
  track(params) {
@@ -1499,13 +1763,23 @@ var SseTransport = class {
1499
1763
  }
1500
1764
  }
1501
1765
  cutSlowConsumer(connectionId, why, tracked) {
1502
- this.logger.warn(
1503
- `${REALTIME_ERROR_CODES.SLOW_CONSUMER}: closing SSE connection ${connectionId}, ${why} (${tracked.backlog.queuedEvents} events, ${tracked.backlog.queuedBytes} bytes queued, ${tracked.probe.buffered()} bytes held by the response)`
1504
- );
1766
+ this.tally?.evicted("slow_consumer");
1767
+ this.tally?.slowConsumerDropped();
1768
+ logEvent(this.logger, "warn", "REALTIME_SLOW_CONSUMER", `closing an SSE connection, ${why}`, {
1769
+ connectionId,
1770
+ queuedEvents: tracked.backlog.queuedEvents,
1771
+ queuedBytes: tracked.backlog.queuedBytes,
1772
+ heldBytes: tracked.probe.buffered()
1773
+ });
1505
1774
  this.disconnectLocal(connectionId, REALTIME_ERROR_CODES.SLOW_CONSUMER).catch(
1506
1775
  (error) => {
1507
- this.logger.warn(
1508
- `Closing slow SSE connection ${connectionId} failed: ${describeError(error)}`
1776
+ logEvent(
1777
+ this.logger,
1778
+ "warn",
1779
+ "REALTIME_DISCONNECT_FAILED",
1780
+ `Closing a slow SSE connection failed`,
1781
+ { connectionId },
1782
+ error
1509
1783
  );
1510
1784
  }
1511
1785
  );
@@ -1536,6 +1810,7 @@ var SseTransport = class {
1536
1810
  let userConnections = this.connections.byUser(userId, "sse");
1537
1811
  while (userConnections.length > max) {
1538
1812
  const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
1813
+ this.tally?.evicted("per_user_cap");
1539
1814
  await this.disconnectLocal(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
1540
1815
  userConnections = this.connections.byUser(userId, "sse");
1541
1816
  }
@@ -1557,7 +1832,9 @@ SseTransport = __decorateClass([
1557
1832
  __decorateParam(10, Optional()),
1558
1833
  __decorateParam(10, Inject(REALTIME_OFFLINE_QUEUE_TOKEN)),
1559
1834
  __decorateParam(11, Optional()),
1560
- __decorateParam(11, Inject(ConnectionAdmission))
1835
+ __decorateParam(11, Inject(ConnectionAdmission)),
1836
+ __decorateParam(12, Optional()),
1837
+ __decorateParam(12, Inject(RealtimeMetricsTally))
1561
1838
  ], SseTransport);
1562
1839
 
1563
1840
  // src/server/transports/sse/response-close.ts
@@ -1631,18 +1908,22 @@ function buildMeta(record) {
1631
1908
  };
1632
1909
  }
1633
1910
  var SseSubscriptionHandler = class {
1634
- constructor(transport, heartbeat, options, hooks, offlineDelivery) {
1911
+ constructor(transport, heartbeat, options, hooks, offlineDelivery, tally, tracing) {
1635
1912
  this.transport = transport;
1636
1913
  this.heartbeat = heartbeat;
1637
1914
  this.options = options;
1638
1915
  this.hooks = hooks;
1639
1916
  this.offlineDelivery = offlineDelivery;
1917
+ this.tally = tally;
1918
+ this.tracing = tracing;
1640
1919
  }
1641
1920
  transport;
1642
1921
  heartbeat;
1643
1922
  options;
1644
1923
  hooks;
1645
1924
  offlineDelivery;
1925
+ tally;
1926
+ tracing;
1646
1927
  logger = new Logger(SseSubscriptionHandler.name);
1647
1928
  authenticated = /* @__PURE__ */ new WeakMap();
1648
1929
  resolveAndValidateIdentity(auth) {
@@ -1651,7 +1932,15 @@ var SseSubscriptionHandler = class {
1651
1932
  assertIdentityIsNotBlank(resolvedAuth);
1652
1933
  resolvedAuth = admitRooms(resolvedAuth);
1653
1934
  } catch (err) {
1654
- this.logger.error(`SSE connection refused \u2014 responding 500: ${describeError(err)}`);
1935
+ this.tally?.refused("error");
1936
+ logEvent(
1937
+ this.logger,
1938
+ "error",
1939
+ "REALTIME_HANDSHAKE_FAILED",
1940
+ `SSE connection refused \u2014 responding 500`,
1941
+ {},
1942
+ err
1943
+ );
1655
1944
  throw new InternalServerErrorException();
1656
1945
  }
1657
1946
  return resolvedAuth;
@@ -1686,6 +1975,7 @@ var SseSubscriptionHandler = class {
1686
1975
  }
1687
1976
  refuseDuringShutdown() {
1688
1977
  if (this.transport.shuttingDown) {
1978
+ this.tally?.refused("unavailable");
1689
1979
  throw new ServiceUnavailableException(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
1690
1980
  }
1691
1981
  }
@@ -1723,16 +2013,29 @@ var SseSubscriptionHandler = class {
1723
2013
  }
1724
2014
  }
1725
2015
  toClientError(err, what) {
1726
- if (err instanceof AuthenticationUnavailableError || err instanceof ConnectionLimitError) {
2016
+ if (err instanceof ConnectionLimitError) {
2017
+ this.tally?.refused("limit");
2018
+ return new ServiceUnavailableException();
2019
+ }
2020
+ if (err instanceof AuthenticationUnavailableError) {
2021
+ this.tally?.refused("unavailable");
1727
2022
  return new ServiceUnavailableException();
1728
2023
  }
2024
+ if (err instanceof HttpException && err.getStatus() === HttpStatus.UNAUTHORIZED) {
2025
+ this.tally?.refused("unauthorized");
2026
+ }
1729
2027
  return err instanceof HttpException ? err : this.serverError(err, what);
1730
2028
  }
1731
2029
  serverError(err, what) {
1732
- this.logger.error(`${what} \u2014 responding 500: ${describeError(err)}`);
2030
+ this.tally?.refused("error");
2031
+ logEvent(this.logger, "error", "REALTIME_HANDSHAKE_FAILED", `${what} \u2014 responding 500`, {}, err);
1733
2032
  return new InternalServerErrorException();
1734
2033
  }
1735
- async authenticateRequest(req, res) {
2034
+ authenticateRequest(req, res) {
2035
+ const run = () => this.admitAndAuthenticate(req, res);
2036
+ return this.tracing ? this.tracing.span("realtime.handshake", { "bymax.realtime.transport": "sse" }, run) : run();
2037
+ }
2038
+ async admitAndAuthenticate(req, res) {
1736
2039
  const held = this.transport.admit();
1737
2040
  const detach = onResponseClose(res, () => ticket.release());
1738
2041
  const ticket = {
@@ -1866,7 +2169,14 @@ var SseSubscriptionHandler = class {
1866
2169
  fireHook(invoke, onFailure) {
1867
2170
  void runHook(invoke).then((failed) => {
1868
2171
  if (!failed) return;
1869
- this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
2172
+ logEvent(
2173
+ this.logger,
2174
+ "warn",
2175
+ "REALTIME_HOOK_FAILED",
2176
+ `Lifecycle hook failed`,
2177
+ {},
2178
+ failed.error
2179
+ );
1870
2180
  onFailure?.();
1871
2181
  });
1872
2182
  }
@@ -1879,7 +2189,11 @@ SseSubscriptionHandler = __decorateClass([
1879
2189
  __decorateParam(3, Optional()),
1880
2190
  __decorateParam(3, Inject(REALTIME_HOOKS_TOKEN)),
1881
2191
  __decorateParam(4, Optional()),
1882
- __decorateParam(4, Inject(OfflineQueueDeliveryService))
2192
+ __decorateParam(4, Inject(OfflineQueueDeliveryService)),
2193
+ __decorateParam(5, Optional()),
2194
+ __decorateParam(5, Inject(RealtimeMetricsTally)),
2195
+ __decorateParam(6, Optional()),
2196
+ __decorateParam(6, Inject(RealtimeTracing))
1883
2197
  ], SseSubscriptionHandler);
1884
2198
 
1885
2199
  // src/server/utils/normalize-endpoint-path.ts
@@ -1930,12 +2244,14 @@ function createSseController(endpoint) {
1930
2244
  return DynamicSseController;
1931
2245
  }
1932
2246
  var RealtimeService = class {
1933
- constructor(transport, pubsub) {
2247
+ constructor(transport, pubsub, tally) {
1934
2248
  this.transport = transport;
1935
2249
  this.pubsub = pubsub;
2250
+ this.tally = tally;
1936
2251
  }
1937
2252
  transport;
1938
2253
  pubsub;
2254
+ tally;
1939
2255
  isPubSubReady() {
1940
2256
  if (this.transport.kind === "websocket") return true;
1941
2257
  return this.pubsub?.isSubscribed?.() ?? true;
@@ -1961,15 +2277,18 @@ var RealtimeService = class {
1961
2277
  refuseReservedRoom("leaveRoom", roomId);
1962
2278
  return this.transport.leaveRoom(connectionId, roomId);
1963
2279
  }
1964
- disconnect(connectionId, reason) {
1965
- return this.transport.disconnect(connectionId, reason);
2280
+ async disconnect(connectionId, reason) {
2281
+ await this.transport.disconnect(connectionId, reason);
2282
+ this.tally?.evicted("revoked");
1966
2283
  }
1967
2284
  };
1968
2285
  RealtimeService = __decorateClass([
1969
2286
  Injectable(),
1970
2287
  __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN)),
1971
2288
  __decorateParam(1, Optional()),
1972
- __decorateParam(1, Inject(REALTIME_PUBSUB_TOKEN))
2289
+ __decorateParam(1, Inject(REALTIME_PUBSUB_TOKEN)),
2290
+ __decorateParam(2, Optional()),
2291
+ __decorateParam(2, Inject(RealtimeMetricsTally))
1973
2292
  ], RealtimeService);
1974
2293
 
1975
2294
  // src/server/utils/semaphore.ts
@@ -2003,31 +2322,55 @@ function resolvePolicy(raw) {
2003
2322
  };
2004
2323
  }
2005
2324
  var ReauthenticationService = class {
2006
- constructor(connections, realtime, auth, options, hooks) {
2325
+ constructor(connections, realtime, auth, options, hooks, tracing) {
2007
2326
  this.connections = connections;
2008
2327
  this.realtime = realtime;
2009
2328
  this.auth = auth;
2010
2329
  this.hooks = hooks;
2330
+ this.tracing = tracing;
2011
2331
  this.policy = resolvePolicy(options.reauthenticationPolicy);
2332
+ this.declared = options.reauthenticationPolicy;
2012
2333
  this.slots = new Semaphore(this.policy.concurrency);
2013
2334
  }
2014
2335
  connections;
2015
2336
  realtime;
2016
2337
  auth;
2017
2338
  hooks;
2339
+ tracing;
2018
2340
  logger = new Logger(ReauthenticationService.name);
2019
2341
  timer = null;
2020
2342
  policy;
2343
+ declared;
2021
2344
  inFlight = /* @__PURE__ */ new Set();
2022
2345
  slots;
2346
+ warnIfCacheOutlivesInterval() {
2347
+ const { cacheTtlMs, intervalSeconds } = this.declared ?? {};
2348
+ if (cacheTtlMs === void 0 || intervalSeconds === void 0) return;
2349
+ if (cacheTtlMs <= intervalSeconds * 1e3) return;
2350
+ logEvent(
2351
+ this.logger,
2352
+ "warn",
2353
+ "REALTIME_REAUTH_CACHE_WEAKENS_POLICY",
2354
+ `reauthenticationPolicy.cacheTtlMs (${cacheTtlMs} ms) exceeds intervalSeconds*1000 (${intervalSeconds * 1e3} ms): the positive reauth cache outlives the interval, so revalidate is skipped on ticks within the cache window \u2014 reauthentication is effectively weakened`,
2355
+ { cacheTtlMs, intervalMs: intervalSeconds * 1e3 }
2356
+ );
2357
+ }
2023
2358
  onModuleInit() {
2024
2359
  if (!this.auth.revalidate) {
2025
2360
  this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
2026
2361
  return;
2027
2362
  }
2363
+ this.warnIfCacheOutlivesInterval();
2028
2364
  this.timer = setInterval(() => {
2029
2365
  this.runCycle().catch((err) => {
2030
- this.logger.warn(`Reauthentication cycle failed: ${describeError(err)}`);
2366
+ logEvent(
2367
+ this.logger,
2368
+ "warn",
2369
+ "REALTIME_REAUTH_FAILED",
2370
+ `Reauthentication cycle failed`,
2371
+ {},
2372
+ err
2373
+ );
2031
2374
  });
2032
2375
  }, this.policy.intervalSeconds * 1e3);
2033
2376
  this.timer.unref();
@@ -2045,7 +2388,10 @@ var ReauthenticationService = class {
2045
2388
  ...this.connections.allByTransport("sse"),
2046
2389
  ...this.connections.allByTransport("websocket")
2047
2390
  ];
2048
- await Promise.all(connections.map((conn) => this.check(conn, now)));
2391
+ const run = async () => {
2392
+ await Promise.all(connections.map((conn) => this.check(conn, now)));
2393
+ };
2394
+ await (this.tracing ? this.tracing.span("realtime.reauthenticate", {}, run) : run());
2049
2395
  }
2050
2396
  async check(conn, now) {
2051
2397
  if (this.inFlight.has(conn.connectionId)) return;
@@ -2082,7 +2428,14 @@ var ReauthenticationService = class {
2082
2428
  }
2083
2429
  await this.revoke(conn);
2084
2430
  } catch (err) {
2085
- this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
2431
+ logEvent(
2432
+ this.logger,
2433
+ "warn",
2434
+ "REALTIME_REAUTH_FAILED",
2435
+ `Reauthentication errored`,
2436
+ { connectionId: conn.connectionId },
2437
+ err
2438
+ );
2086
2439
  await this.revoke(conn);
2087
2440
  }
2088
2441
  }
@@ -2106,8 +2459,13 @@ var ReauthenticationService = class {
2106
2459
  try {
2107
2460
  await this.bounded("revocation", () => this.handleFailure(conn));
2108
2461
  } catch (err) {
2109
- this.logger.warn(
2110
- `Revocation of ${conn.connectionId} failed, retrying next cycle: ${describeError(err)}`
2462
+ logEvent(
2463
+ this.logger,
2464
+ "warn",
2465
+ "REALTIME_REVOCATION_FAILED",
2466
+ `Revocation failed, retrying next cycle`,
2467
+ { connectionId: conn.connectionId },
2468
+ err
2111
2469
  );
2112
2470
  }
2113
2471
  }
@@ -2128,15 +2486,27 @@ var ReauthenticationService = class {
2128
2486
  })
2129
2487
  ).then((failed) => {
2130
2488
  if (failed) {
2131
- this.logger.warn(`onReauthenticationFailed hook failed: ${describeError(failed.error)}`);
2489
+ logEvent(
2490
+ this.logger,
2491
+ "warn",
2492
+ "REALTIME_HOOK_FAILED",
2493
+ `onReauthenticationFailed hook failed`,
2494
+ { hook: "onReauthenticationFailed" },
2495
+ failed.error
2496
+ );
2132
2497
  }
2133
2498
  });
2134
2499
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
2135
2500
  }
2136
2501
  notify(conn) {
2137
2502
  const failed = (err) => {
2138
- this.logger.warn(
2139
- `Reauthentication notification for ${conn.connectionId} failed, disconnecting anyway: ${describeError(err)}`
2503
+ logEvent(
2504
+ this.logger,
2505
+ "warn",
2506
+ "REALTIME_REAUTH_FAILED",
2507
+ `Reauthentication notification failed, disconnecting anyway`,
2508
+ { connectionId: conn.connectionId },
2509
+ err
2140
2510
  );
2141
2511
  };
2142
2512
  try {
@@ -2155,7 +2525,9 @@ ReauthenticationService = __decorateClass([
2155
2525
  __decorateParam(2, Inject(REALTIME_AUTHENTICATOR_TOKEN)),
2156
2526
  __decorateParam(3, Inject(REALTIME_OPTIONS_TOKEN)),
2157
2527
  __decorateParam(4, Optional()),
2158
- __decorateParam(4, Inject(REALTIME_HOOKS_TOKEN))
2528
+ __decorateParam(4, Inject(REALTIME_HOOKS_TOKEN)),
2529
+ __decorateParam(5, Optional()),
2530
+ __decorateParam(5, Inject(RealtimeTracing))
2159
2531
  ], ReauthenticationService);
2160
2532
 
2161
2533
  // src/server/composition/realtime-module.factory.ts
@@ -2163,6 +2535,7 @@ var DEFAULT_ASYNC_SSE_ENDPOINT = "/events";
2163
2535
  var EXPORTED_TOKENS = [
2164
2536
  RealtimeService,
2165
2537
  ConnectionRegistry,
2538
+ RealtimeMetricsTally,
2166
2539
  REALTIME_OPTIONS_TOKEN,
2167
2540
  REALTIME_INSTANCE_ID_TOKEN,
2168
2541
  REALTIME_AUTHENTICATOR_TOKEN,
@@ -2182,7 +2555,9 @@ var SHARED_SERVICES = [
2182
2555
  ReauthenticationService,
2183
2556
  OfflineQueueDeliveryService,
2184
2557
  AuthenticationGate,
2185
- ConnectionAdmission
2558
+ ConnectionAdmission,
2559
+ RealtimeMetricsTally,
2560
+ RealtimeTracing
2186
2561
  ];
2187
2562
  function assertModeSupported(wiring, mode, moduleName) {
2188
2563
  if (wiring.modes.includes(mode)) return;
@@ -2196,7 +2571,10 @@ function assertModeSupported(wiring, mode, moduleName) {
2196
2571
  function warnIfSingleInstance(pubsub, transport, logger) {
2197
2572
  if (transport === "websocket") return;
2198
2573
  if (!pubsub && process.env["NODE_ENV"] === "production") {
2199
- logger.warn(
2574
+ logEvent(
2575
+ logger,
2576
+ "warn",
2577
+ "REALTIME_PUBSUB_NOT_PROVIDED",
2200
2578
  "No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
2201
2579
  );
2202
2580
  }
@@ -2214,7 +2592,8 @@ function buildCommonProviders(resolved, instanceId) {
2214
2592
  ];
2215
2593
  }
2216
2594
  function composeForRoot(moduleClass, wiring, logger, raw) {
2217
- const options = dropUnset(raw);
2595
+ assertOptionsObject(raw, moduleClass.name);
2596
+ const options = guardHostReads("the options", () => dropUnset(raw));
2218
2597
  validateOptions(options);
2219
2598
  assertModeSupported(wiring, options.transport, moduleClass.name);
2220
2599
  const resolved = applyDefaults(options);
@@ -2248,10 +2627,11 @@ function bindSseEndpoint(resolved, declared, bound, moduleName) {
2248
2627
  return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
2249
2628
  }
2250
2629
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
2251
- if (!raw) {
2630
+ if (raw === void 0 || raw === null) {
2252
2631
  throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
2253
2632
  }
2254
- const options = dropUnset(raw);
2633
+ assertOptionsObject(raw, moduleName);
2634
+ const options = guardHostReads("the options", () => dropUnset(raw));
2255
2635
  validateOptions(options);
2256
2636
  if (options.transport !== declaredMode) {
2257
2637
  throw realtimeError(
@@ -2264,12 +2644,15 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
2264
2644
  logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
2265
2645
  return { resolved, declaredEndpoint: options.sse?.endpoint };
2266
2646
  }
2647
+ function isSet(pattern) {
2648
+ return pattern !== void 0 && pattern !== null;
2649
+ }
2267
2650
  function assertOneFactoryPattern(asyncOptions, moduleName) {
2268
2651
  const patterns = [
2269
2652
  asyncOptions.useFactory,
2270
2653
  asyncOptions.useClass,
2271
2654
  asyncOptions.useExisting
2272
- ].filter((pattern) => pattern !== void 0);
2655
+ ].filter(isSet);
2273
2656
  if (patterns.length === 1) return;
2274
2657
  throw realtimeError(
2275
2658
  REALTIME_ERROR_CODES.INVALID_OPTIONS,
@@ -2278,7 +2661,7 @@ function assertOneFactoryPattern(asyncOptions, moduleName) {
2278
2661
  );
2279
2662
  }
2280
2663
  function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2281
- if (asyncOptions.useFactory) {
2664
+ if (isSet(asyncOptions.useFactory)) {
2282
2665
  return {
2283
2666
  provide: REALTIME_OPTIONS_TOKEN,
2284
2667
  useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
@@ -2287,10 +2670,22 @@ function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
2287
2670
  }
2288
2671
  return {
2289
2672
  provide: REALTIME_OPTIONS_TOKEN,
2290
- useFactory: async (factory) => resolve(
2291
- await factory.createRealtimeOptions(),
2292
- "createRealtimeOptions"
2293
- ),
2673
+ useFactory: async (factory) => {
2674
+ const create = guardHostReads(
2675
+ "the provider named by useExisting or useClass",
2676
+ () => factory?.createRealtimeOptions
2677
+ );
2678
+ if (typeof create !== "function") {
2679
+ throw realtimeError(
2680
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
2681
+ "the provider named by useExisting or useClass must implement createRealtimeOptions"
2682
+ );
2683
+ }
2684
+ return resolve(
2685
+ await create.call(factory),
2686
+ "createRealtimeOptions"
2687
+ );
2688
+ },
2294
2689
  inject: [asyncOptions.useExisting ?? factoryToken]
2295
2690
  };
2296
2691
  }
@@ -2326,14 +2721,17 @@ function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, modul
2326
2721
  }
2327
2722
  function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
2328
2723
  const moduleName = moduleClass.name;
2724
+ assertOptionsObject(asyncOptions, moduleName);
2329
2725
  assertOneFactoryPattern(asyncOptions, moduleName);
2330
2726
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
2727
+ assertSseEndpoint("sseEndpoint", asyncOptions.sseEndpoint);
2331
2728
  assertSseEndpointApplies(asyncOptions, moduleName);
2729
+ assertExtraProviders(asyncOptions.extraProviders);
2332
2730
  const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
2333
2731
  const instanceId = randomUUID();
2334
2732
  const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
2335
2733
  const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
2336
- const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2734
+ const factoryClassProvider = isSet(asyncOptions.useClass) ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
2337
2735
  const { providers: transportProviders, controllers } = wiring.buildAsync({
2338
2736
  mode: asyncOptions.transport,
2339
2737
  sseEndpoint: boundSseEndpoint
@@ -2372,7 +2770,14 @@ var RealtimePubSubSubscriber = class {
2372
2770
  try {
2373
2771
  await this.unsubscribe();
2374
2772
  } catch (err) {
2375
- this.logger.warn(`Pub/sub unsubscribe failed: ${describeError(err)}`);
2773
+ logEvent(
2774
+ this.logger,
2775
+ "warn",
2776
+ "REALTIME_PUBSUB_UNSUBSCRIBE_FAILED",
2777
+ `Pub/sub unsubscribe failed`,
2778
+ {},
2779
+ err
2780
+ );
2376
2781
  }
2377
2782
  this.unsubscribe = null;
2378
2783
  }
@@ -2380,8 +2785,12 @@ var RealtimePubSubSubscriber = class {
2380
2785
  dropped = windowedReport(
2381
2786
  () => ({ count: 0, last: "none" }),
2382
2787
  ({ count, last }) => {
2383
- this.logger.warn(
2384
- `Pub/sub dropped ${count} message(s) it could not act on since the last report (last: ${last})`
2788
+ logEvent(
2789
+ this.logger,
2790
+ "warn",
2791
+ "REALTIME_PUBSUB_DROPPED",
2792
+ `Pub/sub dropped ${count} message(s) it could not act on since the last report (last: ${last})`,
2793
+ { count, last }
2385
2794
  );
2386
2795
  }
2387
2796
  );
@@ -2409,17 +2818,9 @@ var RealtimePubSubSubscriber = class {
2409
2818
  this.sse.broadcastLocal(a.event, a.data, a.id);
2410
2819
  break;
2411
2820
  }
2412
- case "disconnect": {
2413
- const a = msg.args;
2414
- Promise.resolve(this.sse.disconnectLocal(a.connectionId, a.reason)).catch(
2415
- (err) => {
2416
- this.logger.warn(
2417
- `Remote disconnect of ${a.connectionId} failed: ${describeError(err)}`
2418
- );
2419
- }
2420
- );
2821
+ case "disconnect":
2822
+ this.closeLocal(msg.args);
2421
2823
  break;
2422
- }
2423
2824
  default: {
2424
2825
  msg.op;
2425
2826
  this.drop("unknown op");
@@ -2429,6 +2830,18 @@ var RealtimePubSubSubscriber = class {
2429
2830
  this.drop(String(Object(err).constructor?.name ?? "Error"));
2430
2831
  }
2431
2832
  }
2833
+ closeLocal(a) {
2834
+ Promise.resolve(this.sse.disconnectLocal(a.connectionId, a.reason)).catch((err) => {
2835
+ logEvent(
2836
+ this.logger,
2837
+ "warn",
2838
+ "REALTIME_DISCONNECT_FAILED",
2839
+ "Remote disconnect failed",
2840
+ { connectionId: a.connectionId },
2841
+ err
2842
+ );
2843
+ });
2844
+ }
2432
2845
  drop(last) {
2433
2846
  this.dropped(({ count }) => ({ count: count + 1, last }));
2434
2847
  }
@@ -2522,11 +2935,6 @@ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
2522
2935
  var PUBLISHER_WAIT_MS = 2e3;
2523
2936
  var PUBLISH_WAIT_MS = 2e3;
2524
2937
  var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
2525
- function connectionReason(err) {
2526
- const code = err?.code;
2527
- const text = describeError(err);
2528
- return [typeof code === "string" ? code : "", text].filter(Boolean).join(" ") || String(err);
2529
- }
2530
2938
  var RedisRealtimePubSub = class _RedisRealtimePubSub {
2531
2939
  #pub;
2532
2940
  channel;
@@ -2588,7 +2996,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2588
2996
  return unavailableError(
2589
2997
  REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
2590
2998
  _RedisRealtimePubSub.name,
2591
- `cannot publish to "${this.channel}"`,
2999
+ `cannot publish to "${this.channel}" (${reason})`,
2592
3000
  new Error(reason)
2593
3001
  );
2594
3002
  }
@@ -2664,7 +3072,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2664
3072
  if (outcome === "subscribed") {
2665
3073
  this.markUp();
2666
3074
  } else {
2667
- this.markDown(connectionReason(outcome.unreachable));
3075
+ this.markDown(void 0, outcome.unreachable);
2668
3076
  first.catch((err) => this.refused(err));
2669
3077
  }
2670
3078
  } catch (err) {
@@ -2690,8 +3098,13 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2690
3098
  const reason = describeError(err);
2691
3099
  if (reason === this.#lastRefusal) return;
2692
3100
  this.#lastRefusal = reason;
2693
- this.logger.warn(
2694
- `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${reason}`
3101
+ logEvent(
3102
+ this.logger,
3103
+ "warn",
3104
+ "REALTIME_PUBSUB_UNAVAILABLE",
3105
+ "the server refused the subscription",
3106
+ {},
3107
+ err
2695
3108
  );
2696
3109
  }
2697
3110
  markUp() {
@@ -2700,23 +3113,32 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
2700
3113
  this.#outageLogged = false;
2701
3114
  this.#lastRefusal = void 0;
2702
3115
  this.logger.log(
2703
- `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
3116
+ `Subscribed to the realtime channel; remote events and revocations reach this instance`
2704
3117
  );
2705
3118
  }
2706
- markDown(reason) {
3119
+ markDown(wording, error) {
2707
3120
  this.#subscribed = false;
2708
3121
  if (this.#outageLogged) return;
2709
3122
  this.#outageLogged = true;
2710
- this.logger.warn(
2711
- `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: not subscribed to "${this.channel}": ${reason}. Remote events and revocations will not reach this instance until it subscribes again`
3123
+ logEvent(
3124
+ this.logger,
3125
+ "warn",
3126
+ "REALTIME_PUBSUB_UNAVAILABLE",
3127
+ `not subscribed${wording === void 0 ? "" : `: ${wording}`}. Remote events and revocations will not reach this instance until it subscribes again`,
3128
+ {},
3129
+ error
2712
3130
  );
2713
3131
  }
2714
3132
  reportMalformed() {
2715
3133
  this.malformedDropped++;
2716
3134
  const now = Date.now();
2717
3135
  if (now - this.malformedReportedAt < MALFORMED_REPORT_INTERVAL_MS) return;
2718
- this.logger.warn(
2719
- `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: dropped ${this.malformedDropped} malformed payload(s) on "${this.channel}" since the last report`
3136
+ logEvent(
3137
+ this.logger,
3138
+ "warn",
3139
+ "REALTIME_PUBSUB_DROPPED",
3140
+ `dropped ${this.malformedDropped} malformed payload(s) since the last report`,
3141
+ { count: this.malformedDropped, last: "malformed" }
2720
3142
  );
2721
3143
  this.malformedDropped = 0;
2722
3144
  this.malformedReportedAt = now;
@@ -2763,6 +3185,10 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2763
3185
  static MS_PAD = 16;
2764
3186
  static COUNTER_PAD = 6;
2765
3187
  constructor(options) {
3188
+ if (!isPlainObject(options)) refuseObject("RedisOfflineQueue", "options", options);
3189
+ if (typeof options.client !== "object" || options.client === null) {
3190
+ refuseObject("RedisOfflineQueue", "options.client", options.client);
3191
+ }
2766
3192
  this.#client = options.client;
2767
3193
  this.maxPerUser = requireInteger(
2768
3194
  "maxPerUser",
@@ -2828,4 +3254,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
2828
3254
  }
2829
3255
  };
2830
3256
 
2831
- 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 };
3257
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EVICTION_REASONS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_LOG_EVENTS, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, REFUSAL_REASONS, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeMetricsTally, RealtimePubSubSubscriber, RealtimeService, RealtimeTracing, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, TALLY_TRANSPORTS, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, logEvent, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };