@bymax-one/nest-realtime 1.2.6 → 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.
@@ -27,6 +27,7 @@ var REALTIME_ERROR_CODES = {
27
27
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
28
28
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
29
29
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
30
+ TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
30
31
  REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
31
32
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
32
33
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
@@ -115,13 +116,27 @@ function describeError(reason) {
115
116
  }
116
117
  }
117
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
+
118
131
  // src/server/offline-queue/offline-queue-delivery.service.ts
119
132
  var RETRIEVE_LIMIT = 200;
120
133
  var OfflineQueueDeliveryService = class {
121
- constructor(storage) {
134
+ constructor(storage, hooks) {
122
135
  this.storage = storage;
136
+ this.hooks = hooks;
123
137
  }
124
138
  storage;
139
+ hooks;
125
140
  logger = new Logger(OfflineQueueDeliveryService.name);
126
141
  /**
127
142
  * Return events for `userId` that arrived after `lastEventId` and are NOT
@@ -142,7 +157,16 @@ var OfflineQueueDeliveryService = class {
142
157
  try {
143
158
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
144
159
  } catch (err) {
145
- 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
+ );
146
170
  return [];
147
171
  }
148
172
  if (events.length === RETRIEVE_LIMIT) {
@@ -176,7 +200,9 @@ var OfflineQueueDeliveryService = class {
176
200
  OfflineQueueDeliveryService = __decorateClass([
177
201
  Injectable(),
178
202
  __decorateParam(0, Optional()),
179
- __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))
180
206
  ], OfflineQueueDeliveryService);
181
207
 
182
208
  // src/shared/constants/reserved-events.constants.ts
@@ -414,6 +440,46 @@ var ROOM_PREFIXES = {
414
440
  function composeRoomId(prefix, ...parts) {
415
441
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
416
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);
417
483
  var DEFAULT_REPLAY_BUFFER_SIZE = 100;
418
484
  var EventReplayBuffer = class {
419
485
  constructor(opts) {
@@ -626,15 +692,59 @@ var SseTransport = class {
626
692
  getConnection(connectionId) {
627
693
  return this.connections.get(connectionId);
628
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
+ */
629
705
  async emitToUser(userId, event, data) {
630
706
  const id = this.idGen.next();
631
707
  this.emitToUserLocal(userId, event, data, id);
632
- if (this.offlineQueue && this.connections.byUser(userId, "sse").length === 0) {
633
- void this.offlineQueue.append(userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }).catch(
634
- (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
635
720
  );
636
721
  }
637
- 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);
638
748
  }
639
749
  async emitToTenant(tenantId, event, data) {
640
750
  const id = this.idGen.next();
@@ -651,20 +761,44 @@ var SseTransport = class {
651
761
  this.broadcastLocal(event, data, id);
652
762
  await this.publish({ op: "broadcast", args: { event, data, id } });
653
763
  }
764
+ /** Join a connection this instance holds to a room; any other id is left alone. */
654
765
  async joinRoom(connectionId, roomId) {
655
- this.rooms.join(connectionId, roomId);
766
+ if (this.connections.get(connectionId)?.transport === "sse")
767
+ this.rooms.join(connectionId, roomId);
656
768
  }
769
+ /** Remove a connection this instance holds from a room; any other id is left alone. */
657
770
  async leaveRoom(connectionId, roomId) {
658
- this.rooms.leave(connectionId, roomId);
771
+ if (this.connections.get(connectionId)?.transport === "sse")
772
+ this.rooms.leave(connectionId, roomId);
659
773
  }
660
- /** 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
+ */
661
782
  async disconnect(connectionId, reason) {
662
783
  const record = this.connections.get(connectionId);
663
- if (record && record.transport === "sse") {
784
+ if (record) {
664
785
  await this.disconnectLocal(connectionId, reason);
665
786
  return;
666
787
  }
667
- 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
+ }
668
802
  }
669
803
  /**
670
804
  * Deliver an event to a user's local SSE connections and update the replay buffer.
@@ -740,14 +874,28 @@ var SseTransport = class {
740
874
  this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
741
875
  }
742
876
  }
743
- /** Publish once to the bus; pub/sub failures never affect the live emit path. */
744
- async publish(message) {
877
+ /** Publish once to the bus; resolves with the failure, or `undefined` once the bus accepted it. */
878
+ async tryPublish(message) {
745
879
  try {
746
880
  await this.pubsub.publish({ ...message, origin: this.instanceId });
881
+ return void 0;
747
882
  } catch (error) {
748
- this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
883
+ return { error };
749
884
  }
750
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
+ }
751
899
  /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
752
900
  async evictBeyondLimit(userId) {
753
901
  const max = this.options.sse?.maxConnectionsPerUser;
@@ -1116,46 +1264,29 @@ function createSseController(endpoint) {
1116
1264
  ], DynamicSseController);
1117
1265
  return DynamicSseController;
1118
1266
  }
1119
- var InMemoryPubSub = class {
1120
- handlers = /* @__PURE__ */ new Set();
1121
- /**
1122
- * Publish a message to all subscribed handlers.
1123
- *
1124
- * Delivery is deferred one microtask so a handler that enqueues further publishes
1125
- * does not deepen the current call stack. One handler's failure does not block others.
1126
- *
1127
- * @param message - The pub/sub message to fan out.
1128
- */
1129
- async publish(message) {
1130
- await Promise.resolve();
1131
- for (const handler of this.handlers) {
1132
- try {
1133
- handler(message);
1134
- } catch {
1135
- }
1136
- }
1267
+ var RealtimeService = class {
1268
+ constructor(transport, pubsub) {
1269
+ this.transport = transport;
1270
+ this.pubsub = pubsub;
1137
1271
  }
1272
+ transport;
1273
+ pubsub;
1138
1274
  /**
1139
- * 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.
1140
1279
  *
1141
- * @param handler - Called for every published message.
1142
- * @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
+ * ```
1143
1285
  */
1144
- async subscribe(handler) {
1145
- this.handlers.add(handler);
1146
- return async () => {
1147
- this.handlers.delete(handler);
1148
- };
1149
- }
1150
- };
1151
- InMemoryPubSub = __decorateClass([
1152
- Injectable()
1153
- ], InMemoryPubSub);
1154
- var RealtimeService = class {
1155
- constructor(transport) {
1156
- this.transport = transport;
1286
+ isPubSubReady() {
1287
+ if (this.transport.kind === "websocket") return true;
1288
+ return this.pubsub?.isSubscribed?.() ?? true;
1157
1289
  }
1158
- transport;
1159
1290
  /**
1160
1291
  * Send to all of a user's connections (across devices/tabs).
1161
1292
  *
@@ -1188,22 +1319,41 @@ var RealtimeService = class {
1188
1319
  * The room id is not checked. Never pass client-supplied input that could start
1189
1320
  * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
1190
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.
1191
1325
  */
1192
1326
  joinRoom(connectionId, roomId) {
1193
1327
  return this.transport.joinRoom(connectionId, roomId);
1194
1328
  }
1195
- /** 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
+ */
1196
1335
  leaveRoom(connectionId, roomId) {
1197
1336
  return this.transport.leaveRoom(connectionId, roomId);
1198
1337
  }
1199
- /** 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
+ */
1200
1348
  disconnect(connectionId, reason) {
1201
1349
  return this.transport.disconnect(connectionId, reason);
1202
1350
  }
1203
1351
  };
1204
1352
  RealtimeService = __decorateClass([
1205
1353
  Injectable(),
1206
- __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN))
1354
+ __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN)),
1355
+ __decorateParam(1, Optional()),
1356
+ __decorateParam(1, Inject(REALTIME_PUBSUB_TOKEN))
1207
1357
  ], RealtimeService);
1208
1358
  function resolvePolicy(raw) {
1209
1359
  return {
@@ -1241,7 +1391,11 @@ var ReauthenticationService = class {
1241
1391
  this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
1242
1392
  return;
1243
1393
  }
1244
- 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);
1245
1399
  this.timer.unref();
1246
1400
  this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
1247
1401
  }
@@ -1287,13 +1441,27 @@ var ReauthenticationService = class {
1287
1441
  this.positiveCache.set(conn.connectionId, now);
1288
1442
  continue;
1289
1443
  }
1290
- await this.handleFailure(conn);
1444
+ await this.revoke(conn);
1291
1445
  } catch (err) {
1292
1446
  this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1293
- await this.handleFailure(conn);
1447
+ await this.revoke(conn);
1294
1448
  }
1295
1449
  }
1296
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
+ }
1297
1465
  /** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
1298
1466
  async handleFailure(conn) {
1299
1467
  this.positiveCache.delete(conn.connectionId);
@@ -1506,13 +1674,7 @@ var RealtimePubSubSubscriber = class {
1506
1674
  logger = new Logger(RealtimePubSubSubscriber.name);
1507
1675
  unsubscribe = null;
1508
1676
  async onModuleInit() {
1509
- try {
1510
- this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1511
- } catch (err) {
1512
- this.logger.warn(
1513
- `Failed to subscribe to pub/sub: ${describeError(err)}. Cross-instance fan-out disabled; remote events will not reach this instance.`
1514
- );
1515
- }
1677
+ this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1516
1678
  }
1517
1679
  async onApplicationShutdown() {
1518
1680
  if (this.unsubscribe) {
@@ -1550,7 +1712,13 @@ var RealtimePubSubSubscriber = class {
1550
1712
  }
1551
1713
  case "disconnect": {
1552
1714
  const a = msg.args;
1553
- 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
+ );
1554
1722
  break;
1555
1723
  }
1556
1724
  default: {
@@ -1658,9 +1826,13 @@ BymaxRealtimeModule = __decorateClass([
1658
1826
  Global(),
1659
1827
  Module({})
1660
1828
  ], BymaxRealtimeModule);
1661
-
1662
- // src/server/pubsub/redis-realtime-pubsub.ts
1663
- 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 {
1664
1836
  /**
1665
1837
  * The publishing Redis client.
1666
1838
  *
@@ -1674,10 +1846,29 @@ var RedisRealtimePubSub = class {
1674
1846
  /** The lazily created subscriber connection, which carries the same credentials. */
1675
1847
  #subInit = null;
1676
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();
1677
1860
  constructor(options) {
1678
1861
  this.#pub = options.client;
1679
1862
  this.channel = options.channel ?? "bymax:realtime";
1680
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
+ }
1681
1872
  /** JSON-encodes the message and PUBLISHes it to the configured channel. */
1682
1873
  async publish(message) {
1683
1874
  await this.#pub.publish(this.channel, JSON.stringify(message));
@@ -1686,7 +1877,7 @@ var RedisRealtimePubSub = class {
1686
1877
  * Lazily creates the single shared subscribe client on first call; returns an async
1687
1878
  * unsubscribe that quits the client when the last handler is removed. Concurrent
1688
1879
  * subscribe calls are idempotent — only one client is ever created. Malformed
1689
- * payloads are dropped silently.
1880
+ * payloads are dropped, and reported at most once a minute with their count.
1690
1881
  *
1691
1882
  * If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
1692
1883
  * the handler registration is rolled back and the cached init promise is cleared so
@@ -1706,8 +1897,12 @@ var RedisRealtimePubSub = class {
1706
1897
  this.handlers.delete(handler);
1707
1898
  if (this.handlers.size === 0) {
1708
1899
  this.#subInit = null;
1900
+ this.#retired.add(sub);
1901
+ const connected = this.#subscribed;
1902
+ this.#subscribed = false;
1709
1903
  try {
1710
- await sub.quit();
1904
+ if (connected) await sub.quit();
1905
+ else sub.disconnect();
1711
1906
  } catch {
1712
1907
  }
1713
1908
  }
@@ -1719,16 +1914,97 @@ var RedisRealtimePubSub = class {
1719
1914
  return this.#subInit;
1720
1915
  }
1721
1916
  async createSubscriber() {
1722
- const sub = this.#pub.duplicate();
1723
- await sub.subscribe(this.channel);
1917
+ this.#outageLogged = false;
1918
+ const sub = this.#pub.duplicate({ autoResubscribe: false });
1919
+ let attached = false;
1724
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;
1725
1956
  return sub;
1726
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
+ }
1727
2002
  dispatch(payload) {
1728
2003
  let msg;
1729
2004
  try {
1730
2005
  msg = JSON.parse(payload);
1731
2006
  } catch {
2007
+ this.reportMalformed();
1732
2008
  return;
1733
2009
  }
1734
2010
  for (const h of this.handlers) {
@@ -1826,4 +2102,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1826
2102
  }
1827
2103
  };
1828
2104
 
1829
- 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';
@@ -30,6 +30,7 @@ var REALTIME_ERROR_CODES = {
30
30
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
31
31
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
32
32
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
33
+ TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
33
34
  REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
34
35
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
35
36
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
153
153
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
154
154
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
155
155
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
156
+ readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
156
157
  readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
157
158
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
158
159
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
153
153
  readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
154
154
  readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
155
155
  readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
156
+ readonly TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE";
156
157
  readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
157
158
  readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
158
159
  readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
@@ -28,6 +28,7 @@ var REALTIME_ERROR_CODES = {
28
28
  TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
29
29
  INVALID_TICKET: "REALTIME_INVALID_TICKET",
30
30
  PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
31
+ TRANSPORT_UNAVAILABLE: "REALTIME_TRANSPORT_UNAVAILABLE",
31
32
  REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
32
33
  PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
33
34
  REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"