@bymax-one/nest-realtime 1.2.5 → 1.2.7

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.
@@ -2,6 +2,7 @@ import { randomUUID } from 'crypto';
2
2
  import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, UnauthorizedException } from '@nestjs/common';
3
3
  import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
4
4
  import { takeUntil, catchError, finalize } from 'rxjs/operators';
5
+ import { isIP } from 'net';
5
6
 
6
7
  var __defProp = Object.defineProperty;
7
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -26,6 +27,7 @@ var REALTIME_ERROR_CODES = {
26
27
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
27
28
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
28
29
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
30
+ TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
29
31
  REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
30
32
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
31
33
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
@@ -114,13 +116,27 @@ function describeError(reason) {
114
116
  }
115
117
  }
116
118
 
119
+ // src/server/utils/report-delivery-failure.ts
120
+ function reportDeliveryFailure(logger, hooks, failure, what) {
121
+ logger.warn(`${failure.code} op=${failure.op}: ${what}: ${describeError(failure.error)}`);
122
+ const reported = {
123
+ ...failure,
124
+ error: failure.error instanceof Error ? failure.error : new Error(describeError(failure.error))
125
+ };
126
+ void Promise.resolve().then(() => hooks?.onDeliveryFailure?.(reported)).catch((err) => {
127
+ logger.warn(`onDeliveryFailure hook failed: ${describeError(err)}`);
128
+ });
129
+ }
130
+
117
131
  // src/server/offline-queue/offline-queue-delivery.service.ts
118
132
  var RETRIEVE_LIMIT = 200;
119
133
  var OfflineQueueDeliveryService = class {
120
- constructor(storage) {
134
+ constructor(storage, hooks) {
121
135
  this.storage = storage;
136
+ this.hooks = hooks;
122
137
  }
123
138
  storage;
139
+ hooks;
124
140
  logger = new Logger(OfflineQueueDeliveryService.name);
125
141
  /**
126
142
  * Return events for `userId` that arrived after `lastEventId` and are NOT
@@ -141,7 +157,16 @@ var OfflineQueueDeliveryService = class {
141
157
  try {
142
158
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
143
159
  } catch (err) {
144
- this.logger.warn(`Offline queue retrieve failed: ${describeError(err)}`);
160
+ reportDeliveryFailure(
161
+ this.logger,
162
+ this.hooks,
163
+ {
164
+ code: REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
165
+ op: "offlineRetrieve",
166
+ error: err
167
+ },
168
+ "Offline queue retrieve failed"
169
+ );
145
170
  return [];
146
171
  }
147
172
  if (events.length === RETRIEVE_LIMIT) {
@@ -175,7 +200,9 @@ var OfflineQueueDeliveryService = class {
175
200
  OfflineQueueDeliveryService = __decorateClass([
176
201
  Injectable(),
177
202
  __decorateParam(0, Optional()),
178
- __decorateParam(0, Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
203
+ __decorateParam(0, Inject(REALTIME_OFFLINE_QUEUE_TOKEN)),
204
+ __decorateParam(1, Optional()),
205
+ __decorateParam(1, Inject(REALTIME_HOOKS_TOKEN))
179
206
  ], OfflineQueueDeliveryService);
180
207
 
181
208
  // src/shared/constants/reserved-events.constants.ts
@@ -226,6 +253,25 @@ function parseCookieHeader(cookieHeader) {
226
253
  }
227
254
  return out;
228
255
  }
256
+ var IPV6 = 6;
257
+ function isHeaderAddress(candidate) {
258
+ return typeof candidate === "string" && !candidate.includes("%") && isIP(candidate) !== 0;
259
+ }
260
+ function peerAddress(remoteAddress) {
261
+ if (typeof remoteAddress !== "string") return "";
262
+ const zoneIndex = remoteAddress.indexOf("%");
263
+ const bare = zoneIndex === -1 ? remoteAddress : remoteAddress.slice(0, zoneIndex);
264
+ const family = isIP(bare);
265
+ if (zoneIndex !== -1) return family === IPV6 ? bare : "";
266
+ return family === 0 ? "" : bare;
267
+ }
268
+ function resolveClientAddress(request) {
269
+ const hops = request.ips ?? [];
270
+ for (const candidate of [request.ip, ...hops]) {
271
+ if (isHeaderAddress(candidate)) return candidate;
272
+ }
273
+ return peerAddress(request.socket?.remoteAddress);
274
+ }
229
275
  var ConnectionRegistry = class {
230
276
  byId = /* @__PURE__ */ new Map();
231
277
  byUserId = /* @__PURE__ */ new Map();
@@ -394,6 +440,46 @@ var ROOM_PREFIXES = {
394
440
  function composeRoomId(prefix, ...parts) {
395
441
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
396
442
  }
443
+
444
+ // src/server/utils/unavailable-error.ts
445
+ function unavailableError(code, who, what, cause) {
446
+ return new Error(`[${who}] ${code}: ${what} (${describeError(cause)})`, { cause });
447
+ }
448
+ var InMemoryPubSub = class {
449
+ handlers = /* @__PURE__ */ new Set();
450
+ /**
451
+ * Publish a message to all subscribed handlers.
452
+ *
453
+ * Delivery is deferred one microtask so a handler that enqueues further publishes
454
+ * does not deepen the current call stack. One handler's failure does not block others.
455
+ *
456
+ * @param message - The pub/sub message to fan out.
457
+ */
458
+ async publish(message) {
459
+ await Promise.resolve();
460
+ for (const handler of this.handlers) {
461
+ try {
462
+ handler(message);
463
+ } catch {
464
+ }
465
+ }
466
+ }
467
+ /**
468
+ * Subscribe to pub/sub messages.
469
+ *
470
+ * @param handler - Called for every published message.
471
+ * @returns An async unsubscribe function that removes this handler.
472
+ */
473
+ async subscribe(handler) {
474
+ this.handlers.add(handler);
475
+ return async () => {
476
+ this.handlers.delete(handler);
477
+ };
478
+ }
479
+ };
480
+ InMemoryPubSub = __decorateClass([
481
+ Injectable()
482
+ ], InMemoryPubSub);
397
483
  var DEFAULT_REPLAY_BUFFER_SIZE = 100;
398
484
  var EventReplayBuffer = class {
399
485
  constructor(opts) {
@@ -606,15 +692,59 @@ var SseTransport = class {
606
692
  getConnection(connectionId) {
607
693
  return this.connections.get(connectionId);
608
694
  }
695
+ /**
696
+ * Emit to a user: live here, to the other instances over the bus, and into the offline queue
697
+ * when the user has no live connection on this instance.
698
+ *
699
+ * A failed publish or a failed append is reported (log and `onDeliveryFailure`) and the call
700
+ * still resolves, since delivery to the other instances is at-most-once. It rejects only when
701
+ * the event has no delivery path left: the user is offline here, the queue could not keep it,
702
+ * and the bus either failed or cannot reach another instance (the in-memory bus). A rejection
703
+ * carries the queue failure as its cause and is not also reported to the hook.
704
+ */
609
705
  async emitToUser(userId, event, data) {
610
706
  const id = this.idGen.next();
611
707
  this.emitToUserLocal(userId, event, data, id);
612
- if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
613
- void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
614
- (error) => this.logger.warn(`Offline queue append failed: ${describeError(error)}`)
708
+ const queue = this.offlineQueue;
709
+ const offline = queue !== void 0 && this.connections.byUser(userId, "sse").length === 0;
710
+ const [queueFailure, publishFailure] = await Promise.all([
711
+ offline ? this.tryAppend(queue, userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }) : void 0,
712
+ this.tryPublish({ op: "emitToUser", args: { userId, event, data, id } })
713
+ ]);
714
+ if (queueFailure !== void 0 && (publishFailure !== void 0 || !this.busReachesOtherInstances())) {
715
+ throw unavailableError(
716
+ REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
717
+ SseTransport.name,
718
+ `${event} for ${userId} has no delivery path: the user is offline here and the offline queue failed`,
719
+ queueFailure.error
615
720
  );
616
721
  }
617
- await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
722
+ if (publishFailure !== void 0) this.reportPublishFailure("emitToUser", publishFailure);
723
+ if (queueFailure !== void 0) {
724
+ reportDeliveryFailure(
725
+ this.logger,
726
+ this.hooks,
727
+ {
728
+ code: REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
729
+ op: "offlineAppend",
730
+ error: queueFailure.error
731
+ },
732
+ "Offline queue append failed"
733
+ );
734
+ }
735
+ }
736
+ /** Append to the offline queue; resolves with the failure, or `undefined` once it is kept. */
737
+ async tryAppend(queue, userId, event) {
738
+ try {
739
+ await queue.append(userId, event);
740
+ return void 0;
741
+ } catch (error) {
742
+ return { error };
743
+ }
744
+ }
745
+ /** Whether the bus can carry an event to another instance (the in-memory bus cannot). */
746
+ busReachesOtherInstances() {
747
+ return !(this.pubsub instanceof InMemoryPubSub);
618
748
  }
619
749
  async emitToTenant(tenantId, event, data) {
620
750
  const id = this.idGen.next();
@@ -631,20 +761,44 @@ var SseTransport = class {
631
761
  this.broadcastLocal(event, data, id);
632
762
  await this.publish({ op: "broadcast", args: { event, data, id } });
633
763
  }
764
+ /** Join a connection this instance holds to a room; any other id is left alone. */
634
765
  async joinRoom(connectionId, roomId) {
635
- this.rooms.join(connectionId, roomId);
766
+ if (this.connections.get(connectionId)?.transport === "sse")
767
+ this.rooms.join(connectionId, roomId);
636
768
  }
769
+ /** Remove a connection this instance holds from a room; any other id is left alone. */
637
770
  async leaveRoom(connectionId, roomId) {
638
- this.rooms.leave(connectionId, roomId);
771
+ if (this.connections.get(connectionId)?.transport === "sse")
772
+ this.rooms.leave(connectionId, roomId);
639
773
  }
640
- /** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
774
+ /**
775
+ * Disconnect a connection locally if owned here, otherwise revoke cross-instance.
776
+ *
777
+ * Resolves once the connection is closed here or the revocation has been handed to the bus. A
778
+ * connection held here as a WebSocket is left to the WebSocket transport and nothing is
779
+ * published. It rejects with `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses it: nothing has reached
780
+ * the connection, so the caller must not read the resolution as a revocation.
781
+ */
641
782
  async disconnect(connectionId, reason) {
642
783
  const record = this.connections.get(connectionId);
643
- if (record && record.transport === "sse") {
784
+ if (record) {
644
785
  await this.disconnectLocal(connectionId, reason);
645
786
  return;
646
787
  }
647
- await this.publish({ op: "disconnect", args: { connectionId, reason } });
788
+ try {
789
+ await this.pubsub.publish({
790
+ op: "disconnect",
791
+ args: { connectionId, reason },
792
+ origin: this.instanceId
793
+ });
794
+ } catch (error) {
795
+ throw unavailableError(
796
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
797
+ SseTransport.name,
798
+ `the revocation of ${connectionId} could not be published`,
799
+ error
800
+ );
801
+ }
648
802
  }
649
803
  /**
650
804
  * Deliver an event to a user's local SSE connections and update the replay buffer.
@@ -720,14 +874,28 @@ var SseTransport = class {
720
874
  this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
721
875
  }
722
876
  }
723
- /** Publish once to the bus; pub/sub failures never affect the live emit path. */
724
- async publish(message) {
877
+ /** Publish once to the bus; resolves with the failure, or `undefined` once the bus accepted it. */
878
+ async tryPublish(message) {
725
879
  try {
726
880
  await this.pubsub.publish({ ...message, origin: this.instanceId });
881
+ return void 0;
727
882
  } catch (error) {
728
- this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
883
+ return { error };
729
884
  }
730
885
  }
886
+ /** Publish once to the bus. A failure is reported and never fails the live emit path. */
887
+ async publish(message) {
888
+ const failure = await this.tryPublish(message);
889
+ if (failure !== void 0) this.reportPublishFailure(message.op, failure);
890
+ }
891
+ reportPublishFailure(op, { error }) {
892
+ reportDeliveryFailure(
893
+ this.logger,
894
+ this.hooks,
895
+ { code: REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE, op, error },
896
+ "pubsub.publish failed"
897
+ );
898
+ }
731
899
  /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
732
900
  async evictBeyondLimit(userId) {
733
901
  const max = this.options.sse?.maxConnectionsPerUser;
@@ -760,11 +928,6 @@ SseTransport = __decorateClass([
760
928
  function singleHeader(value) {
761
929
  return typeof value === "string" ? value : void 0;
762
930
  }
763
- function resolveIp(req) {
764
- const forwarded = req.headers["x-forwarded-for"];
765
- const candidate = (typeof forwarded === "string" ? forwarded.split(",")[0] : void 0) ?? "";
766
- return candidate.trim() || req.ip || "unknown";
767
- }
768
931
  function normalizeHeaders(headers) {
769
932
  const out = /* @__PURE__ */ Object.create(null);
770
933
  for (const [key, value] of Object.entries(headers)) {
@@ -786,7 +949,7 @@ function buildAuthContext(req) {
786
949
  cookies: parseCookieHeader(singleHeader(req.headers["cookie"]) ?? ""),
787
950
  headers,
788
951
  query: sanitizeQuery(req.query),
789
- ip: resolveIp(req),
952
+ ip: resolveClientAddress(req),
790
953
  remoteAddress: req.socket?.remoteAddress,
791
954
  userAgent: singleHeader(req.headers["user-agent"]),
792
955
  transport: "sse"
@@ -1101,46 +1264,29 @@ function createSseController(endpoint) {
1101
1264
  ], DynamicSseController);
1102
1265
  return DynamicSseController;
1103
1266
  }
1104
- var InMemoryPubSub = class {
1105
- handlers = /* @__PURE__ */ new Set();
1106
- /**
1107
- * Publish a message to all subscribed handlers.
1108
- *
1109
- * Delivery is deferred one microtask so a handler that enqueues further publishes
1110
- * does not deepen the current call stack. One handler's failure does not block others.
1111
- *
1112
- * @param message - The pub/sub message to fan out.
1113
- */
1114
- async publish(message) {
1115
- await Promise.resolve();
1116
- for (const handler of this.handlers) {
1117
- try {
1118
- handler(message);
1119
- } catch {
1120
- }
1121
- }
1267
+ var RealtimeService = class {
1268
+ constructor(transport, pubsub) {
1269
+ this.transport = transport;
1270
+ this.pubsub = pubsub;
1122
1271
  }
1272
+ transport;
1273
+ pubsub;
1123
1274
  /**
1124
- * Subscribe to pub/sub messages.
1275
+ * Whether this instance hears the events and revocations other instances publish. False while
1276
+ * the bus is unreachable or its subscriber connection is down, so a readiness probe can take a
1277
+ * deaf instance out of rotation. True for a bus that does not report a state, and with
1278
+ * `transport: 'websocket'`, which does not subscribe to the bus.
1125
1279
  *
1126
- * @param handler - Called for every published message.
1127
- * @returns An async unsubscribe function that removes this handler.
1280
+ * @example
1281
+ * ```ts
1282
+ * // In a health indicator: `isHealthy` is false while the instance cannot hear the others.
1283
+ * return indicator.check('realtime', realtime.isPubSubReady())
1284
+ * ```
1128
1285
  */
1129
- async subscribe(handler) {
1130
- this.handlers.add(handler);
1131
- return async () => {
1132
- this.handlers.delete(handler);
1133
- };
1134
- }
1135
- };
1136
- InMemoryPubSub = __decorateClass([
1137
- Injectable()
1138
- ], InMemoryPubSub);
1139
- var RealtimeService = class {
1140
- constructor(transport) {
1141
- this.transport = transport;
1286
+ isPubSubReady() {
1287
+ if (this.transport.kind === "websocket") return true;
1288
+ return this.pubsub?.isSubscribed?.() ?? true;
1142
1289
  }
1143
- transport;
1144
1290
  /**
1145
1291
  * Send to all of a user's connections (across devices/tabs).
1146
1292
  *
@@ -1173,22 +1319,41 @@ var RealtimeService = class {
1173
1319
  * The room id is not checked. Never pass client-supplied input that could start
1174
1320
  * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
1175
1321
  * receives that tenant's events.
1322
+ *
1323
+ * Acts on a connection this instance holds; for any other id it resolves and changes
1324
+ * nothing. A failure of the transport that holds the connection rejects the call.
1176
1325
  */
1177
1326
  joinRoom(connectionId, roomId) {
1178
1327
  return this.transport.joinRoom(connectionId, roomId);
1179
1328
  }
1180
- /** Remove a specific connection from a room. */
1329
+ /**
1330
+ * Remove a specific connection from a room.
1331
+ *
1332
+ * Acts on a connection this instance holds; for any other id it resolves and changes
1333
+ * nothing. A failure of the transport that holds the connection rejects the call.
1334
+ */
1181
1335
  leaveRoom(connectionId, roomId) {
1182
1336
  return this.transport.leaveRoom(connectionId, roomId);
1183
1337
  }
1184
- /** Force-disconnect a specific connection (e.g. on auth revocation). */
1338
+ /**
1339
+ * Force-disconnect a specific connection (e.g. on auth revocation).
1340
+ *
1341
+ * Resolves once the connection is closed on this instance or the revocation has been handed
1342
+ * to the bus for the instance that holds it.
1343
+ *
1344
+ * @throws {Error} `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the revocation, or
1345
+ * `REALTIME_TRANSPORT_UNAVAILABLE` when the transport that holds the connection fails.
1346
+ * The connection may still be connected: retry.
1347
+ */
1185
1348
  disconnect(connectionId, reason) {
1186
1349
  return this.transport.disconnect(connectionId, reason);
1187
1350
  }
1188
1351
  };
1189
1352
  RealtimeService = __decorateClass([
1190
1353
  Injectable(),
1191
- __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN))
1354
+ __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN)),
1355
+ __decorateParam(1, Optional()),
1356
+ __decorateParam(1, Inject(REALTIME_PUBSUB_TOKEN))
1192
1357
  ], RealtimeService);
1193
1358
  function resolvePolicy(raw) {
1194
1359
  return {
@@ -1226,7 +1391,11 @@ var ReauthenticationService = class {
1226
1391
  this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
1227
1392
  return;
1228
1393
  }
1229
- this.timer = setInterval(() => void this.runCycle(), this.policy.intervalSeconds * 1e3);
1394
+ this.timer = setInterval(() => {
1395
+ this.runCycle().catch((err) => {
1396
+ this.logger.warn(`Reauthentication cycle failed: ${describeError(err)}`);
1397
+ });
1398
+ }, this.policy.intervalSeconds * 1e3);
1230
1399
  this.timer.unref();
1231
1400
  this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
1232
1401
  }
@@ -1272,13 +1441,27 @@ var ReauthenticationService = class {
1272
1441
  this.positiveCache.set(conn.connectionId, now);
1273
1442
  continue;
1274
1443
  }
1275
- await this.handleFailure(conn);
1444
+ await this.revoke(conn);
1276
1445
  } catch (err) {
1277
1446
  this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1278
- await this.handleFailure(conn);
1447
+ await this.revoke(conn);
1279
1448
  }
1280
1449
  }
1281
1450
  }
1451
+ /**
1452
+ * Revoke a connection whose revalidation failed, and keep the cycle going when the
1453
+ * revocation itself is rejected. The positive-cache entry is already gone, so the next
1454
+ * cycle revalidates the connection and tries again.
1455
+ */
1456
+ async revoke(conn) {
1457
+ try {
1458
+ await this.handleFailure(conn);
1459
+ } catch (err) {
1460
+ this.logger.warn(
1461
+ `Revocation of ${conn.connectionId} failed, retrying next cycle: ${describeError(err)}`
1462
+ );
1463
+ }
1464
+ }
1282
1465
  /** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
1283
1466
  async handleFailure(conn) {
1284
1467
  this.positiveCache.delete(conn.connectionId);
@@ -1491,13 +1674,7 @@ var RealtimePubSubSubscriber = class {
1491
1674
  logger = new Logger(RealtimePubSubSubscriber.name);
1492
1675
  unsubscribe = null;
1493
1676
  async onModuleInit() {
1494
- try {
1495
- this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1496
- } catch (err) {
1497
- this.logger.warn(
1498
- `Failed to subscribe to pub/sub: ${describeError(err)}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1499
- );
1500
- }
1677
+ this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1501
1678
  }
1502
1679
  async onApplicationShutdown() {
1503
1680
  if (this.unsubscribe) {
@@ -1535,7 +1712,13 @@ var RealtimePubSubSubscriber = class {
1535
1712
  }
1536
1713
  case "disconnect": {
1537
1714
  const a = msg.args;
1538
- void this.sse.disconnectLocal(a.connectionId, a.reason);
1715
+ Promise.resolve(this.sse.disconnectLocal(a.connectionId, a.reason)).catch(
1716
+ (err) => {
1717
+ this.logger.warn(
1718
+ `Remote disconnect of ${a.connectionId} failed: ${describeError(err)}`
1719
+ );
1720
+ }
1721
+ );
1539
1722
  break;
1540
1723
  }
1541
1724
  default: {
@@ -1643,9 +1826,13 @@ BymaxRealtimeModule = __decorateClass([
1643
1826
  Global(),
1644
1827
  Module({})
1645
1828
  ], BymaxRealtimeModule);
1646
-
1647
- // src/server/pubsub/redis-realtime-pubsub.ts
1648
- var RedisRealtimePubSub = class {
1829
+ var MALFORMED_REPORT_INTERVAL_MS = 6e4;
1830
+ function connectionReason(err) {
1831
+ const code = err?.code;
1832
+ const text = describeError(err);
1833
+ return [typeof code === "string" ? code : "", text].filter(Boolean).join(" ") || String(err);
1834
+ }
1835
+ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1649
1836
  /**
1650
1837
  * The publishing Redis client.
1651
1838
  *
@@ -1659,10 +1846,29 @@ var RedisRealtimePubSub = class {
1659
1846
  /** The lazily created subscriber connection, which carries the same credentials. */
1660
1847
  #subInit = null;
1661
1848
  handlers = /* @__PURE__ */ new Set();
1849
+ logger = new Logger(_RedisRealtimePubSub.name);
1850
+ /** Payloads dropped as unparsable since the last report, and when that report was made. */
1851
+ malformedDropped = 0;
1852
+ malformedReportedAt = 0;
1853
+ /** Whether the subscriber connection holds a confirmed SUBSCRIBE right now. */
1854
+ #subscribed = false;
1855
+ /** Whether the current outage has been logged, so a retry loop adds no line. */
1856
+ // Stryker disable next-line BooleanLiteral: equivalent — createSubscriber sets it before any use
1857
+ #outageLogged = false;
1858
+ /** Connections closed on purpose, whose `close` is not an outage and says nothing of a successor. */
1859
+ #retired = /* @__PURE__ */ new WeakSet();
1662
1860
  constructor(options) {
1663
1861
  this.#pub = options.client;
1664
1862
  this.channel = options.channel ?? "bymax:realtime";
1665
1863
  }
1864
+ /**
1865
+ * Whether this instance holds a confirmed subscription to the channel, so the events and
1866
+ * revocations other instances publish reach it. False before the first successful subscribe,
1867
+ * while the subscriber connection is down, and after the last handler has unsubscribed.
1868
+ */
1869
+ isSubscribed() {
1870
+ return this.#subscribed;
1871
+ }
1666
1872
  /** JSON-encodes the message and PUBLISHes it to the configured channel. */
1667
1873
  async publish(message) {
1668
1874
  await this.#pub.publish(this.channel, JSON.stringify(message));
@@ -1671,7 +1877,7 @@ var RedisRealtimePubSub = class {
1671
1877
  * Lazily creates the single shared subscribe client on first call; returns an async
1672
1878
  * unsubscribe that quits the client when the last handler is removed. Concurrent
1673
1879
  * subscribe calls are idempotent — only one client is ever created. Malformed
1674
- * payloads are dropped silently.
1880
+ * payloads are dropped, and reported at most once a minute with their count.
1675
1881
  *
1676
1882
  * If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
1677
1883
  * the handler registration is rolled back and the cached init promise is cleared so
@@ -1691,8 +1897,12 @@ var RedisRealtimePubSub = class {
1691
1897
  this.handlers.delete(handler);
1692
1898
  if (this.handlers.size === 0) {
1693
1899
  this.#subInit = null;
1900
+ this.#retired.add(sub);
1901
+ const connected = this.#subscribed;
1902
+ this.#subscribed = false;
1694
1903
  try {
1695
- await sub.quit();
1904
+ if (connected) await sub.quit();
1905
+ else sub.disconnect();
1696
1906
  } catch {
1697
1907
  }
1698
1908
  }
@@ -1704,16 +1914,97 @@ var RedisRealtimePubSub = class {
1704
1914
  return this.#subInit;
1705
1915
  }
1706
1916
  async createSubscriber() {
1707
- const sub = this.#pub.duplicate();
1708
- await sub.subscribe(this.channel);
1917
+ this.#outageLogged = false;
1918
+ const sub = this.#pub.duplicate({ autoResubscribe: false });
1919
+ let attached = false;
1709
1920
  sub.on("message", (_ch, payload) => this.dispatch(payload));
1921
+ const unreachableFirst = new Promise((resolve) => {
1922
+ sub.on("error", (err) => {
1923
+ if (err.name !== "ReplyError") resolve({ unreachable: err });
1924
+ });
1925
+ sub.on("close", () => {
1926
+ resolve({ unreachable: new Error() });
1927
+ if (!this.#retired.has(sub)) this.markDown("connection closed");
1928
+ });
1929
+ });
1930
+ sub.on("ready", () => {
1931
+ if (attached) this.confirm(sub);
1932
+ });
1933
+ const first = sub.subscribe(this.channel);
1934
+ try {
1935
+ const outcome = await Promise.race([
1936
+ first.then(() => "subscribed"),
1937
+ unreachableFirst
1938
+ ]);
1939
+ if (outcome === "subscribed") {
1940
+ this.markUp();
1941
+ } else {
1942
+ this.markDown(connectionReason(outcome.unreachable));
1943
+ first.catch((err) => this.refused(err));
1944
+ }
1945
+ } catch (err) {
1946
+ this.#retired.add(sub);
1947
+ sub.disconnect();
1948
+ throw unavailableError(
1949
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1950
+ _RedisRealtimePubSub.name,
1951
+ `could not subscribe to "${this.channel}"`,
1952
+ err
1953
+ );
1954
+ }
1955
+ attached = true;
1710
1956
  return sub;
1711
1957
  }
1958
+ confirm(sub) {
1959
+ sub.subscribe(this.channel).then(
1960
+ () => this.markUp(),
1961
+ (err) => this.refused(err)
1962
+ );
1963
+ }
1964
+ /** A server that was reached and refused the SUBSCRIBE after boot: it stays unsubscribed. */
1965
+ refused(err) {
1966
+ if (err?.name !== "ReplyError") return;
1967
+ this.#subscribed = false;
1968
+ this.logger.warn(
1969
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${describeError(err)}`
1970
+ );
1971
+ }
1972
+ markUp() {
1973
+ if (this.#subscribed) return;
1974
+ this.#subscribed = true;
1975
+ this.#outageLogged = false;
1976
+ this.logger.log(
1977
+ `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
1978
+ );
1979
+ }
1980
+ markDown(reason) {
1981
+ this.#subscribed = false;
1982
+ if (this.#outageLogged) return;
1983
+ this.#outageLogged = true;
1984
+ this.logger.warn(
1985
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: not subscribed to "${this.channel}": ${reason}. Remote events and revocations will not reach this instance until it subscribes again`
1986
+ );
1987
+ }
1988
+ /**
1989
+ * Count a payload dropped as unparsable and report the count at most once per minute, so a
1990
+ * producer on an incompatible version is visible without flooding the log.
1991
+ */
1992
+ reportMalformed() {
1993
+ this.malformedDropped++;
1994
+ const now = Date.now();
1995
+ if (now - this.malformedReportedAt < MALFORMED_REPORT_INTERVAL_MS) return;
1996
+ this.logger.warn(
1997
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: dropped ${this.malformedDropped} malformed payload(s) on "${this.channel}" since the last report`
1998
+ );
1999
+ this.malformedDropped = 0;
2000
+ this.malformedReportedAt = now;
2001
+ }
1712
2002
  dispatch(payload) {
1713
2003
  let msg;
1714
2004
  try {
1715
2005
  msg = JSON.parse(payload);
1716
2006
  } catch {
2007
+ this.reportMalformed();
1717
2008
  return;
1718
2009
  }
1719
2010
  for (const h of this.handlers) {
@@ -1811,4 +2102,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1811
2102
  }
1812
2103
  };
1813
2104
 
1814
- export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, resolveAuthTenant, sseWiring };
2105
+ export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
@@ -1 +1 @@
1
- export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
@@ -1 +1 @@
1
- export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';
1
+ export { AuthenticationResult, BymaxRealtimeModule, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, ConnectionAuthContext, ConnectionEventMeta, ConnectionRegistry, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, InMemoryPubSub, OfflineQueuedEvent, PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, RealtimeService, ReauthenticationPolicy, RedisOfflineQueue, RedisOfflineQueueOptions, RedisRealtimePubSub, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, WebSocketOptions, composeRoomId } from '@bymax-one/nest-realtime/internal';