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