@bymax-one/nest-realtime 1.2.6 → 1.2.8

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"
@@ -46,6 +47,21 @@ function applyDefaults(options) {
46
47
  sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
47
48
  });
48
49
  }
50
+
51
+ // src/server/constants/injection-tokens.constants.ts
52
+ var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
53
+ var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
54
+ var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
55
+ var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
56
+ var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
57
+ var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
58
+ var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
59
+ var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
60
+ var DEFAULT_HEARTBEAT_MS = 3e4;
61
+ var HEARTBEAT_MIN_MS = 5e3;
62
+ var HEARTBEAT_MAX_MS = 9e4;
63
+
64
+ // src/server/config/validate-options.ts
49
65
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
50
66
  function validateOptions(options) {
51
67
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
@@ -77,9 +93,10 @@ function validateReauthPolicy(options) {
77
93
  }
78
94
  function validateSseOptions(options) {
79
95
  const sse = options.sse;
80
- if (sse?.heartbeatMs !== void 0 && sse.heartbeatMs <= 0) {
96
+ const heartbeatMs = sse?.heartbeatMs;
97
+ if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
81
98
  throw new Error(
82
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be > 0`
99
+ `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`
83
100
  );
84
101
  }
85
102
  if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
@@ -94,17 +111,6 @@ function validateSseOptions(options) {
94
111
  }
95
112
  }
96
113
 
97
- // src/server/constants/injection-tokens.constants.ts
98
- var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
99
- var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
100
- var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
101
- var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
102
- var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
103
- var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
104
- var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
105
- var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
106
- var DEFAULT_HEARTBEAT_MS = 3e4;
107
-
108
114
  // src/server/utils/describe-error.ts
109
115
  function describeError(reason) {
110
116
  try {
@@ -115,34 +121,44 @@ function describeError(reason) {
115
121
  }
116
122
  }
117
123
 
124
+ // src/server/utils/report-delivery-failure.ts
125
+ function reportDeliveryFailure(logger, hooks, failure, what) {
126
+ logger.warn(`${failure.code} op=${failure.op}: ${what}: ${describeError(failure.error)}`);
127
+ const reported = {
128
+ ...failure,
129
+ error: failure.error instanceof Error ? failure.error : new Error(describeError(failure.error))
130
+ };
131
+ void Promise.resolve().then(() => hooks?.onDeliveryFailure?.(reported)).catch((err) => {
132
+ logger.warn(`onDeliveryFailure hook failed: ${describeError(err)}`);
133
+ });
134
+ }
135
+
118
136
  // src/server/offline-queue/offline-queue-delivery.service.ts
119
137
  var RETRIEVE_LIMIT = 200;
120
138
  var OfflineQueueDeliveryService = class {
121
- constructor(storage) {
139
+ constructor(storage, hooks) {
122
140
  this.storage = storage;
141
+ this.hooks = hooks;
123
142
  }
124
143
  storage;
144
+ hooks;
125
145
  logger = new Logger(OfflineQueueDeliveryService.name);
126
- /**
127
- * Return events for `userId` that arrived after `lastEventId` and are NOT
128
- * already covered by `ringBufferIds` (already replayed from in-memory buffer).
129
- *
130
- * Retrieval does NOT acknowledge: the durable queue is pruned only after the events
131
- * have been emitted to a live subscriber via {@link acknowledge}. This guarantees
132
- * at-least-once delivery — events that never reach the client are never lost.
133
- *
134
- * @param userId - The reconnecting user.
135
- * @param lastEventId - The `Last-Event-ID` header value.
136
- * @param ringBufferIds - Set of event ids already replayed from the ring buffer.
137
- * @returns Gap events, or an empty array when no offline queue is configured.
138
- */
139
146
  async retrieve(userId, lastEventId, ringBufferIds) {
140
147
  if (!this.storage) return [];
141
148
  let events;
142
149
  try {
143
150
  events = await this.storage.retrieveSince(userId, lastEventId, RETRIEVE_LIMIT);
144
151
  } catch (err) {
145
- this.logger.warn(`Offline queue retrieve failed: ${describeError(err)}`);
152
+ reportDeliveryFailure(
153
+ this.logger,
154
+ this.hooks,
155
+ {
156
+ code: REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
157
+ op: "offlineRetrieve",
158
+ error: err
159
+ },
160
+ "Offline queue retrieve failed"
161
+ );
146
162
  return [];
147
163
  }
148
164
  if (events.length === RETRIEVE_LIMIT) {
@@ -152,17 +168,6 @@ var OfflineQueueDeliveryService = class {
152
168
  }
153
169
  return events.filter((e) => !ringBufferIds.has(e.id));
154
170
  }
155
- /**
156
- * Acknowledge delivered offline events so the storage backend can prune them.
157
- *
158
- * At-least-once contract: call this ONLY after the events have been emitted to a
159
- * still-open subscriber. Acknowledging before emission would permanently drop events
160
- * that never reached the client. A failure is swallowed (logged) so a transient
161
- * storage error never disrupts delivery; the events simply redeliver on reconnect.
162
- *
163
- * @param userId - The user whose queue is acknowledged.
164
- * @param events - The delivered gap events; the last id is the prune watermark.
165
- */
166
171
  async acknowledge(userId, events) {
167
172
  if (!this.storage || events.length === 0) return;
168
173
  const lastId = events[events.length - 1].id;
@@ -176,7 +181,9 @@ var OfflineQueueDeliveryService = class {
176
181
  OfflineQueueDeliveryService = __decorateClass([
177
182
  Injectable(),
178
183
  __decorateParam(0, Optional()),
179
- __decorateParam(0, Inject(REALTIME_OFFLINE_QUEUE_TOKEN))
184
+ __decorateParam(0, Inject(REALTIME_OFFLINE_QUEUE_TOKEN)),
185
+ __decorateParam(1, Optional()),
186
+ __decorateParam(1, Inject(REALTIME_HOOKS_TOKEN))
180
187
  ], OfflineQueueDeliveryService);
181
188
 
182
189
  // src/shared/constants/reserved-events.constants.ts
@@ -250,11 +257,6 @@ var ConnectionRegistry = class {
250
257
  byId = /* @__PURE__ */ new Map();
251
258
  byUserId = /* @__PURE__ */ new Map();
252
259
  byTenantId = /* @__PURE__ */ new Map();
253
- /**
254
- * Register a connection and index it by user and tenant.
255
- *
256
- * @internal Transport bookkeeping: applications must not call it.
257
- */
258
260
  register(record) {
259
261
  this.byId.set(record.connectionId, record);
260
262
  this.addToSetMap(this.byUserId, record.userId, record.connectionId);
@@ -262,11 +264,6 @@ var ConnectionRegistry = class {
262
264
  this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
263
265
  }
264
266
  }
265
- /**
266
- * Remove a connection from every index. Returns the removed record, if any.
267
- *
268
- * @internal Transport bookkeeping: applications must not call it.
269
- */
270
267
  unregister(connectionId) {
271
268
  const record = this.byId.get(connectionId);
272
269
  if (!record) return void 0;
@@ -277,27 +274,21 @@ var ConnectionRegistry = class {
277
274
  }
278
275
  return record;
279
276
  }
280
- /** Look up a single connection by id. */
281
277
  get(connectionId) {
282
278
  return this.byId.get(connectionId);
283
279
  }
284
- /** All connections of a user, optionally filtered by transport. */
285
280
  byUser(userId, transport) {
286
281
  return this.resolve(this.byUserId.get(userId), transport);
287
282
  }
288
- /** All connections of a tenant, optionally filtered by transport. */
289
283
  byTenant(tenantId, transport) {
290
284
  return this.resolve(this.byTenantId.get(tenantId), transport);
291
285
  }
292
- /** All connections of a given transport. */
293
286
  allByTransport(transport) {
294
287
  return Array.from(this.byId.values()).filter((record) => record.transport === transport);
295
288
  }
296
- /** Total number of active connections. */
297
289
  count() {
298
290
  return this.byId.size;
299
291
  }
300
- /** Number of distinct users currently connected. */
301
292
  countUsers() {
302
293
  return this.byUserId.size;
303
294
  }
@@ -331,7 +322,6 @@ var COUNTER_WIDTH = 6;
331
322
  var EventIdGenerator = class {
332
323
  lastMs = 0;
333
324
  counter = 0;
334
- /** Produce the next monotonic event id. */
335
325
  next() {
336
326
  const now = Date.now();
337
327
  if (now === this.lastMs) {
@@ -349,7 +339,6 @@ EventIdGenerator = __decorateClass([
349
339
  var RoomRegistry = class {
350
340
  rooms = /* @__PURE__ */ new Map();
351
341
  connectionRooms = /* @__PURE__ */ new Map();
352
- /** Join a connection to a room (idempotent). */
353
342
  join(connectionId, roomId) {
354
343
  const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
355
344
  room.add(connectionId);
@@ -358,7 +347,6 @@ var RoomRegistry = class {
358
347
  conn.add(roomId);
359
348
  this.connectionRooms.set(connectionId, conn);
360
349
  }
361
- /** Remove a connection from a room (idempotent); prunes empty entries. */
362
350
  leave(connectionId, roomId) {
363
351
  const room = this.rooms.get(roomId);
364
352
  if (room) {
@@ -371,17 +359,14 @@ var RoomRegistry = class {
371
359
  if (conn.size === 0) this.connectionRooms.delete(connectionId);
372
360
  }
373
361
  }
374
- /** Snapshot of a room's members — safe to iterate while membership mutates. */
375
362
  members(roomId) {
376
363
  const set = this.rooms.get(roomId);
377
364
  return set ? Array.from(set) : [];
378
365
  }
379
- /** Snapshot of the rooms a connection currently belongs to. */
380
366
  roomsOf(connectionId) {
381
367
  const set = this.connectionRooms.get(connectionId);
382
368
  return set ? Array.from(set) : [];
383
369
  }
384
- /** Remove a connection from every room (called on disconnect). */
385
370
  leaveAll(connectionId) {
386
371
  const rooms = this.connectionRooms.get(connectionId);
387
372
  if (!rooms) return;
@@ -394,7 +379,6 @@ var RoomRegistry = class {
394
379
  }
395
380
  this.connectionRooms.delete(connectionId);
396
381
  }
397
- /** Total number of distinct rooms. */
398
382
  countRooms() {
399
383
  return this.rooms.size;
400
384
  }
@@ -414,6 +398,32 @@ var ROOM_PREFIXES = {
414
398
  function composeRoomId(prefix, ...parts) {
415
399
  return [ROOM_PREFIXES[prefix], ...parts].join(":");
416
400
  }
401
+
402
+ // src/server/utils/unavailable-error.ts
403
+ function unavailableError(code, who, what, cause) {
404
+ return new Error(`[${who}] ${code}: ${what} (${describeError(cause)})`, { cause });
405
+ }
406
+ var InMemoryPubSub = class {
407
+ handlers = /* @__PURE__ */ new Set();
408
+ async publish(message) {
409
+ await Promise.resolve();
410
+ for (const handler of this.handlers) {
411
+ try {
412
+ handler(message);
413
+ } catch {
414
+ }
415
+ }
416
+ }
417
+ async subscribe(handler) {
418
+ this.handlers.add(handler);
419
+ return async () => {
420
+ this.handlers.delete(handler);
421
+ };
422
+ }
423
+ };
424
+ InMemoryPubSub = __decorateClass([
425
+ Injectable()
426
+ ], InMemoryPubSub);
417
427
  var DEFAULT_REPLAY_BUFFER_SIZE = 100;
418
428
  var EventReplayBuffer = class {
419
429
  constructor(opts) {
@@ -421,7 +431,6 @@ var EventReplayBuffer = class {
421
431
  }
422
432
  opts;
423
433
  buffers = /* @__PURE__ */ new Map();
424
- /** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
425
434
  append(userId, event) {
426
435
  const buf = this.buffers.get(userId) ?? [];
427
436
  buf.push(event);
@@ -429,12 +438,6 @@ var EventReplayBuffer = class {
429
438
  if (buf.length > cap) buf.shift();
430
439
  this.buffers.set(userId, buf);
431
440
  }
432
- /**
433
- * Return the events emitted after `lastEventId`.
434
- *
435
- * Returns an empty array when the user has no buffer, or when `lastEventId` is
436
- * not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
437
- */
438
441
  since(userId, lastEventId) {
439
442
  const buf = this.buffers.get(userId);
440
443
  if (!buf) return [];
@@ -442,7 +445,6 @@ var EventReplayBuffer = class {
442
445
  if (idx === -1) return [];
443
446
  return buf.slice(idx + 1);
444
447
  }
445
- /** Number of events currently buffered for a user (diagnostics). */
446
448
  size(userId) {
447
449
  return this.buffers.get(userId)?.length ?? 0;
448
450
  }
@@ -452,19 +454,8 @@ EventReplayBuffer = __decorateClass([
452
454
  __decorateParam(0, Inject(REALTIME_OPTIONS_TOKEN))
453
455
  ], EventReplayBuffer);
454
456
  var KEEPALIVE_COMMENT = ": keepalive\n\n";
455
- var HEARTBEAT_MIN_MS = 5e3;
456
- var HEARTBEAT_MAX_MS = 9e4;
457
457
  var HeartbeatService = class {
458
458
  timers = /* @__PURE__ */ new Map();
459
- /**
460
- * Start writing keepalives for a connection every `intervalMs`.
461
- *
462
- * @param connectionId - Unique connection identifier used to track the timer.
463
- * @param res - The writable response stream (or any object with a `write` method).
464
- * @param intervalMs - Keepalive interval in milliseconds; must be within
465
- * `[5_000, 90_000]`.
466
- * @throws {Error} When `intervalMs` is outside the valid range.
467
- */
468
459
  start(connectionId, res, intervalMs) {
469
460
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
470
461
  throw new Error(
@@ -482,7 +473,6 @@ var HeartbeatService = class {
482
473
  timer.unref();
483
474
  this.timers.set(connectionId, timer);
484
475
  }
485
- /** Stop and clear the keepalive timer for a connection (idempotent). */
486
476
  stop(connectionId) {
487
477
  const timer = this.timers.get(connectionId);
488
478
  if (timer) {
@@ -490,7 +480,6 @@ var HeartbeatService = class {
490
480
  this.timers.delete(connectionId);
491
481
  }
492
482
  }
493
- /** Stop every keepalive timer (used on shutdown). */
494
483
  stopAll() {
495
484
  for (const timer of this.timers.values()) clearInterval(timer);
496
485
  this.timers.clear();
@@ -528,32 +517,21 @@ var SseTransport = class {
528
517
  offlineQueue;
529
518
  kind = "sse";
530
519
  logger = new Logger(SseTransport.name);
531
- /** Tear down every SSE connection and stop heartbeat on process shutdown. */
532
520
  async onApplicationShutdown() {
533
521
  this.heartbeat.stopAll();
534
522
  for (const conn of this.connections.allByTransport("sse")) {
535
523
  await this.disconnectLocal(conn.connectionId);
536
524
  }
537
525
  }
538
- /** The resolved heartbeat interval for this transport. */
539
526
  get heartbeatMs() {
540
527
  return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
541
528
  }
542
- /** Whether the `connection:established` event should be emitted on connect. */
543
529
  get emitConnectionEvent() {
544
530
  return this.options.sse?.emitConnectionEvent !== false;
545
531
  }
546
- /** Authenticate a connection through the consumer-provided authenticator. */
547
532
  authenticate(context) {
548
533
  return this.auth.authenticate(context);
549
534
  }
550
- /**
551
- * Register an authenticated SSE connection and auto-join its user/tenant rooms.
552
- *
553
- * Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
554
- * lifecycle hook is fired by the subscription handler after this returns, so that the
555
- * handler can carry a consistent connection record reference.
556
- */
557
535
  async registerConnection(params) {
558
536
  const record = {
559
537
  connectionId: params.connectionId,
@@ -579,7 +557,6 @@ var SseTransport = class {
579
557
  }
580
558
  await this.evictBeyondLimit(params.auth.userId);
581
559
  }
582
- /** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
583
560
  async unregisterConnection(connectionId, reason) {
584
561
  const record = this.connections.unregister(connectionId);
585
562
  if (!record) return;
@@ -603,38 +580,56 @@ var SseTransport = class {
603
580
  this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
604
581
  }
605
582
  }
606
- /** Replay the events a user missed after `lastEventId`. */
607
583
  getReplayEvents(userId, lastEventId) {
608
584
  return this.replayBuffer.since(userId, lastEventId);
609
585
  }
610
- /**
611
- * All SSE connections for a user — public accessor so external callers can
612
- * inspect or iterate without reaching into a private registry field.
613
- *
614
- * @param userId - The user whose active connections are returned.
615
- * @returns A snapshot of the user's current SSE `ConnectionRecord` list.
616
- */
617
586
  connectionsForUser(userId) {
618
587
  return this.connections.byUser(userId, "sse");
619
588
  }
620
- /**
621
- * Look up a single connection by id.
622
- *
623
- * @param connectionId - The unique connection identifier.
624
- * @returns The `ConnectionRecord`, or `undefined` when not found.
625
- */
626
589
  getConnection(connectionId) {
627
590
  return this.connections.get(connectionId);
628
591
  }
629
592
  async emitToUser(userId, event, data) {
630
593
  const id = this.idGen.next();
631
594
  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)}`)
595
+ const queue = this.offlineQueue;
596
+ const offline = queue !== void 0 && this.connections.byUser(userId, "sse").length === 0;
597
+ const [queueFailure, publishFailure] = await Promise.all([
598
+ offline ? this.tryAppend(queue, userId, { id, event, data, emittedAt: /* @__PURE__ */ new Date() }) : void 0,
599
+ this.tryPublish({ op: "emitToUser", args: { userId, event, data, id } })
600
+ ]);
601
+ if (queueFailure !== void 0 && (publishFailure !== void 0 || !this.busReachesOtherInstances())) {
602
+ throw unavailableError(
603
+ REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
604
+ SseTransport.name,
605
+ `${event} for ${userId} has no delivery path: the user is offline here and the offline queue failed`,
606
+ queueFailure.error
607
+ );
608
+ }
609
+ if (publishFailure !== void 0) this.reportPublishFailure("emitToUser", publishFailure);
610
+ if (queueFailure !== void 0) {
611
+ reportDeliveryFailure(
612
+ this.logger,
613
+ this.hooks,
614
+ {
615
+ code: REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
616
+ op: "offlineAppend",
617
+ error: queueFailure.error
618
+ },
619
+ "Offline queue append failed"
635
620
  );
636
621
  }
637
- await this.publish({ op: "emitToUser", args: { userId, event, data, id } });
622
+ }
623
+ async tryAppend(queue, userId, event) {
624
+ try {
625
+ await queue.append(userId, event);
626
+ return void 0;
627
+ } catch (error) {
628
+ return { error };
629
+ }
630
+ }
631
+ busReachesOtherInstances() {
632
+ return !(this.pubsub instanceof InMemoryPubSub);
638
633
  }
639
634
  async emitToTenant(tenantId, event, data) {
640
635
  const id = this.idGen.next();
@@ -652,51 +647,43 @@ var SseTransport = class {
652
647
  await this.publish({ op: "broadcast", args: { event, data, id } });
653
648
  }
654
649
  async joinRoom(connectionId, roomId) {
655
- this.rooms.join(connectionId, roomId);
650
+ if (this.connections.get(connectionId)?.transport === "sse")
651
+ this.rooms.join(connectionId, roomId);
656
652
  }
657
653
  async leaveRoom(connectionId, roomId) {
658
- this.rooms.leave(connectionId, roomId);
654
+ if (this.connections.get(connectionId)?.transport === "sse")
655
+ this.rooms.leave(connectionId, roomId);
659
656
  }
660
- /** Disconnect a connection locally if owned here, otherwise revoke cross-instance. */
661
657
  async disconnect(connectionId, reason) {
662
658
  const record = this.connections.get(connectionId);
663
- if (record && record.transport === "sse") {
659
+ if (record) {
664
660
  await this.disconnectLocal(connectionId, reason);
665
661
  return;
666
662
  }
667
- await this.publish({ op: "disconnect", args: { connectionId, reason } });
668
- }
669
- /**
670
- * Deliver an event to a user's local SSE connections and update the replay buffer.
671
- *
672
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
673
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
674
- */
663
+ try {
664
+ await this.pubsub.publish({
665
+ op: "disconnect",
666
+ args: { connectionId, reason },
667
+ origin: this.instanceId
668
+ });
669
+ } catch (error) {
670
+ throw unavailableError(
671
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
672
+ SseTransport.name,
673
+ `the revocation of ${connectionId} could not be published`,
674
+ error
675
+ );
676
+ }
677
+ }
675
678
  emitToUserLocal(userId, event, data, id) {
676
679
  const message = this.buildMessage(id, event, data);
677
680
  this.replayBuffer.append(userId, message);
678
681
  for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
679
682
  }
680
- /**
681
- * Deliver an event to all local SSE connections for a tenant.
682
- *
683
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
684
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
685
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
686
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
687
- */
688
683
  emitToTenantLocal(tenantId, event, data, id) {
689
684
  const message = this.buildMessage(id, event, data);
690
685
  for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
691
686
  }
692
- /**
693
- * Deliver an event to all local SSE connections that joined the given room.
694
- *
695
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
696
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
697
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
698
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
699
- */
700
687
  emitToRoomLocal(roomId, event, data, id) {
701
688
  const message = this.buildMessage(id, event, data);
702
689
  for (const connectionId of this.rooms.members(roomId)) {
@@ -704,24 +691,10 @@ var SseTransport = class {
704
691
  if (conn && conn.transport === "sse") this.deliver(conn, message);
705
692
  }
706
693
  }
707
- /**
708
- * Deliver an event to all local SSE connections.
709
- *
710
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
711
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
712
- * @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
713
- * buffer or offline queue — only emitToUser populates per-user replay/offline state.
714
- */
715
694
  broadcastLocal(event, data, id) {
716
695
  const message = this.buildMessage(id, event, data);
717
696
  for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
718
697
  }
719
- /**
720
- * Tear down a locally-owned SSE stream, then clean up (no re-publish).
721
- *
722
- * @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
723
- * must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
724
- */
725
698
  async disconnectLocal(connectionId, reason) {
726
699
  const record = this.connections.get(connectionId);
727
700
  if (!record || record.transport !== "sse") return;
@@ -732,7 +705,6 @@ var SseTransport = class {
732
705
  buildMessage(id, event, data) {
733
706
  return { id, type: event, data };
734
707
  }
735
- /** Deliver to one connection, isolating failures so others still receive the event. */
736
708
  deliver(conn, message) {
737
709
  try {
738
710
  conn.subject?.next(message);
@@ -740,15 +712,26 @@ var SseTransport = class {
740
712
  this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
741
713
  }
742
714
  }
743
- /** Publish once to the bus; pub/sub failures never affect the live emit path. */
744
- async publish(message) {
715
+ async tryPublish(message) {
745
716
  try {
746
717
  await this.pubsub.publish({ ...message, origin: this.instanceId });
718
+ return void 0;
747
719
  } catch (error) {
748
- this.logger.warn(`pubsub.publish failed: ${describeError(error)}`);
720
+ return { error };
749
721
  }
750
722
  }
751
- /** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
723
+ async publish(message) {
724
+ const failure = await this.tryPublish(message);
725
+ if (failure !== void 0) this.reportPublishFailure(message.op, failure);
726
+ }
727
+ reportPublishFailure(op, { error }) {
728
+ reportDeliveryFailure(
729
+ this.logger,
730
+ this.hooks,
731
+ { code: REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE, op, error },
732
+ "pubsub.publish failed"
733
+ );
734
+ }
752
735
  async evictBeyondLimit(userId) {
753
736
  const max = this.options.sse?.maxConnectionsPerUser;
754
737
  if (max === void 0 || max <= 0) return;
@@ -847,29 +830,6 @@ var SseSubscriptionHandler = class {
847
830
  offlineDelivery;
848
831
  logger = new Logger(SseSubscriptionHandler.name);
849
832
  authenticated = /* @__PURE__ */ new WeakMap();
850
- /**
851
- * Resolve the tenant this connection routes on, and refuse a blank identity.
852
- *
853
- * Both transports resolve the routing tenant through this one function, so a
854
- * connection carries the same tenant whichever one opened it. The check runs on
855
- * the resolved value rather than the raw one — validating what the server does not
856
- * use would validate nothing.
857
- *
858
- * A blank identity is the consumer's configuration rather than the client's
859
- * credentials, so it is deliberately not a 401: a 401 would tell a client its
860
- * credentials were rejected when they were accepted, inviting a retry that cannot
861
- * succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
862
- * once, not an unhandled crash logging a stack on every reconnect.
863
- *
864
- * The reason names the operator's fix, so it goes to the server log and the client
865
- * receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
866
- * without a message.
867
- *
868
- * @param auth - The result the consumer's authenticator returned.
869
- * @returns The same result with the routing tenant resolved.
870
- * @throws InternalServerErrorException with the generic body when a trait is present
871
- * but blank.
872
- */
873
833
  resolveAndValidateIdentity(auth) {
874
834
  const resolvedAuth = resolveAuthTenant(this.options, auth);
875
835
  try {
@@ -880,27 +840,6 @@ var SseSubscriptionHandler = class {
880
840
  }
881
841
  return resolvedAuth;
882
842
  }
883
- /**
884
- * Handle an incoming SSE connection request end-to-end.
885
- *
886
- * Sets anti-buffering headers, authenticates the request, captures the offline-gap
887
- * before exposing the connection, then returns an Observable whose subscriber callback
888
- * wires the downstream listener BEFORE calling `registerConnection` — so a plain
889
- * `Subject` suffices and the replay buffer cannot grow unboundedly.
890
- *
891
- * @param req - The incoming request (SSE GET).
892
- * @param res - The response (passthrough for header mutations and heartbeat writes).
893
- * @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
894
- * @throws UnauthorizedException when authentication returns null — the client's
895
- * credentials were rejected, which is a 401.
896
- * @throws InternalServerErrorException when the authenticator, or the configured
897
- * `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
898
- * a 401: the credentials were accepted and the fault is the consumer's
899
- * configuration, so it surfaces as a 500 rather than telling a client to retry
900
- * something that cannot succeed. The exception carries no message, so the client
901
- * gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
902
- * written to the server log.
903
- */
904
843
  async handle(req, res) {
905
844
  res.setHeader("Cache-Control", "no-cache, no-transform");
906
845
  res.setHeader("X-Accel-Buffering", "no");
@@ -942,10 +881,6 @@ var SseSubscriptionHandler = class {
942
881
  queueEvents
943
882
  });
944
883
  }
945
- /**
946
- * Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
947
- * `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
948
- */
949
884
  async authenticateBeforeCommit(req) {
950
885
  try {
951
886
  this.authenticated.set(req, await this.authenticateRequest(req));
@@ -953,7 +888,6 @@ var SseSubscriptionHandler = class {
953
888
  throw this.toClientError(err, "SSE authentication failed");
954
889
  }
955
890
  }
956
- // Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
957
891
  toClientError(err, what) {
958
892
  return err instanceof HttpException ? err : this.serverError(err, what);
959
893
  }
@@ -967,15 +901,6 @@ var SseSubscriptionHandler = class {
967
901
  if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
968
902
  return { context, auth: this.resolveAndValidateIdentity(auth) };
969
903
  }
970
- /**
971
- * Build the live Observable using a subscribe-before-register pattern.
972
- *
973
- * The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
974
- * already has a listener when `registerConnection` runs. Any `subject.next()` that
975
- * occurs during or after registration goes directly to the subscriber — nothing is
976
- * buffered or retained, nothing is dropped, and ordering (established → replay →
977
- * queue → live) is preserved.
978
- */
979
904
  buildStream(p) {
980
905
  return new Observable((subscriber) => {
981
906
  const inner = this.subscribePipeline(p, subscriber);
@@ -986,12 +911,6 @@ var SseSubscriptionHandler = class {
986
911
  return () => inner.unsubscribe();
987
912
  });
988
913
  }
989
- /**
990
- * Wire the merged pipeline to the downstream subscriber with teardown.
991
- *
992
- * Subscribing first guarantees `subject` has a listener before registration can emit,
993
- * so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
994
- */
995
914
  subscribePipeline(p, subscriber) {
996
915
  const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
997
916
  const queueReplay$ = queueEvents.length > 0 ? of(...queueEvents.map(toMessageEvent)) : EMPTY;
@@ -1009,12 +928,6 @@ var SseSubscriptionHandler = class {
1009
928
  })
1010
929
  ).subscribe(subscriber);
1011
930
  }
1012
- /**
1013
- * Register the connection (after the subscriber is wired) and activate it on resolution.
1014
- *
1015
- * A registration failure routes to `onError` and errors the stream; a failure that
1016
- * arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
1017
- */
1018
931
  activateConnection(p, subscriber) {
1019
932
  const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
1020
933
  this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
@@ -1024,15 +937,6 @@ var SseSubscriptionHandler = class {
1024
937
  subscriber.error(this.serverError(err, "SSE registration failed"));
1025
938
  });
1026
939
  }
1027
- /**
1028
- * Complete the connection handshake once registration resolves.
1029
- *
1030
- * Registration is async and can resolve AFTER the downstream subscriber has already
1031
- * torn down (client disconnected mid-handshake). When that happens `finalize` has
1032
- * already stopped the heartbeat and unregistered, so re-firing onConnect or starting
1033
- * a fresh heartbeat would leak the connection and write after close. Guard on
1034
- * `subscriber.closed`: if closed, undo the late registration idempotently and return.
1035
- */
1036
940
  onRegistered(p, subscriber) {
1037
941
  const { connectionId, res } = p;
1038
942
  if (subscriber.closed) {
@@ -1047,12 +951,6 @@ var SseSubscriptionHandler = class {
1047
951
  const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
1048
952
  this.heartbeat.start(connectionId, res, heartbeatMs);
1049
953
  }
1050
- /**
1051
- * Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
1052
- * so it never disrupts the connection lifecycle or live event delivery.
1053
- *
1054
- * @param invoke - A zero-arg function that calls the hook (handles optionality).
1055
- */
1056
954
  fireHook(invoke) {
1057
955
  void Promise.resolve(invoke()).catch((err) => {
1058
956
  this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
@@ -1093,9 +991,6 @@ function createSseController(endpoint) {
1093
991
  __decorateParam(0, Inject(SseSubscriptionHandler))
1094
992
  ], SseAuthGuard);
1095
993
  let DynamicSseController = class {
1096
- // Explicit @Inject: the published bundle is built by esbuild/tsup, which does
1097
- // not emit `design:paramtypes` decorator metadata, so constructor params must
1098
- // be resolved by token rather than by reflected type.
1099
994
  constructor(handler) {
1100
995
  this.handler = handler;
1101
996
  }
@@ -1116,94 +1011,44 @@ function createSseController(endpoint) {
1116
1011
  ], DynamicSseController);
1117
1012
  return DynamicSseController;
1118
1013
  }
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
- }
1137
- }
1138
- /**
1139
- * Subscribe to pub/sub messages.
1140
- *
1141
- * @param handler - Called for every published message.
1142
- * @returns An async unsubscribe function that removes this handler.
1143
- */
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
1014
  var RealtimeService = class {
1155
- constructor(transport) {
1015
+ constructor(transport, pubsub) {
1156
1016
  this.transport = transport;
1017
+ this.pubsub = pubsub;
1157
1018
  }
1158
1019
  transport;
1159
- /**
1160
- * Send to all of a user's connections (across devices/tabs).
1161
- *
1162
- * @example
1163
- * ```ts
1164
- * await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
1165
- * ```
1166
- */
1020
+ pubsub;
1021
+ isPubSubReady() {
1022
+ if (this.transport.kind === "websocket") return true;
1023
+ return this.pubsub?.isSubscribed?.() ?? true;
1024
+ }
1167
1025
  emitToUser(userId, event, data) {
1168
1026
  return this.transport.emitToUser(userId, event, data);
1169
1027
  }
1170
- /** Send to every connection in a tenant. */
1171
1028
  emitToTenant(tenantId, event, data) {
1172
1029
  return this.transport.emitToTenant(tenantId, event, data);
1173
1030
  }
1174
- /**
1175
- * Send to a logical room. Use the prefix convention (`user:{id}`,
1176
- * `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
1177
- */
1178
1031
  emitToRoom(roomId, event, data) {
1179
1032
  return this.transport.emitToRoom(roomId, event, data);
1180
1033
  }
1181
- /** Send to every connected client. Use sparingly. */
1182
1034
  broadcast(event, data) {
1183
1035
  return this.transport.broadcast(event, data);
1184
1036
  }
1185
- /**
1186
- * Add a specific connection to a room.
1187
- *
1188
- * The room id is not checked. Never pass client-supplied input that could start
1189
- * with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
1190
- * receives that tenant's events.
1191
- */
1192
1037
  joinRoom(connectionId, roomId) {
1193
1038
  return this.transport.joinRoom(connectionId, roomId);
1194
1039
  }
1195
- /** Remove a specific connection from a room. */
1196
1040
  leaveRoom(connectionId, roomId) {
1197
1041
  return this.transport.leaveRoom(connectionId, roomId);
1198
1042
  }
1199
- /** Force-disconnect a specific connection (e.g. on auth revocation). */
1200
1043
  disconnect(connectionId, reason) {
1201
1044
  return this.transport.disconnect(connectionId, reason);
1202
1045
  }
1203
1046
  };
1204
1047
  RealtimeService = __decorateClass([
1205
1048
  Injectable(),
1206
- __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN))
1049
+ __decorateParam(0, Inject(REALTIME_TRANSPORT_TOKEN)),
1050
+ __decorateParam(1, Optional()),
1051
+ __decorateParam(1, Inject(REALTIME_PUBSUB_TOKEN))
1207
1052
  ], RealtimeService);
1208
1053
  function resolvePolicy(raw) {
1209
1054
  return {
@@ -1226,30 +1071,21 @@ var ReauthenticationService = class {
1226
1071
  hooks;
1227
1072
  logger = new Logger(ReauthenticationService.name);
1228
1073
  timer = null;
1229
- /** connectionId → epoch-ms timestamp of last successful revalidation. */
1230
1074
  positiveCache = /* @__PURE__ */ new Map();
1231
1075
  policy;
1232
- /**
1233
- * Schedule the periodic revalidation cycle.
1234
- *
1235
- * The timer is unref'd so it never keeps the process alive on its own.
1236
- * When the authenticator does not implement `revalidate`, the service stays
1237
- * idle and emits an informative log.
1238
- */
1239
1076
  onModuleInit() {
1240
1077
  if (!this.auth.revalidate) {
1241
1078
  this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
1242
1079
  return;
1243
1080
  }
1244
- this.timer = setInterval(() => void this.runCycle(), this.policy.intervalSeconds * 1e3);
1081
+ this.timer = setInterval(() => {
1082
+ this.runCycle().catch((err) => {
1083
+ this.logger.warn(`Reauthentication cycle failed: ${describeError(err)}`);
1084
+ });
1085
+ }, this.policy.intervalSeconds * 1e3);
1245
1086
  this.timer.unref();
1246
1087
  this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
1247
1088
  }
1248
- /**
1249
- * Clear the timer and the positive cache.
1250
- *
1251
- * Called by NestJS on graceful shutdown to prevent leaks.
1252
- */
1253
1089
  onApplicationShutdown() {
1254
1090
  if (this.timer) {
1255
1091
  clearInterval(this.timer);
@@ -1257,15 +1093,6 @@ var ReauthenticationService = class {
1257
1093
  }
1258
1094
  this.positiveCache.clear();
1259
1095
  }
1260
- /**
1261
- * Run one revalidation cycle over every active connection, SSE and WebSocket alike.
1262
- *
1263
- * A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
1264
- * refreshes the cache. A negative result (or a thrown error) invokes the configured
1265
- * `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
1266
- *
1267
- * Exposed as public for test access.
1268
- */
1269
1096
  async runCycle() {
1270
1097
  const now = Date.now();
1271
1098
  const connections = [
@@ -1287,14 +1114,22 @@ var ReauthenticationService = class {
1287
1114
  this.positiveCache.set(conn.connectionId, now);
1288
1115
  continue;
1289
1116
  }
1290
- await this.handleFailure(conn);
1117
+ await this.revoke(conn);
1291
1118
  } catch (err) {
1292
1119
  this.logger.warn(`Reauthentication errored for ${conn.connectionId}: ${describeError(err)}`);
1293
- await this.handleFailure(conn);
1120
+ await this.revoke(conn);
1294
1121
  }
1295
1122
  }
1296
1123
  }
1297
- /** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
1124
+ async revoke(conn) {
1125
+ try {
1126
+ await this.handleFailure(conn);
1127
+ } catch (err) {
1128
+ this.logger.warn(
1129
+ `Revocation of ${conn.connectionId} failed, retrying next cycle: ${describeError(err)}`
1130
+ );
1131
+ }
1132
+ }
1298
1133
  async handleFailure(conn) {
1299
1134
  this.positiveCache.delete(conn.connectionId);
1300
1135
  if (this.policy.onFailure === "event") {
@@ -1506,13 +1341,7 @@ var RealtimePubSubSubscriber = class {
1506
1341
  logger = new Logger(RealtimePubSubSubscriber.name);
1507
1342
  unsubscribe = null;
1508
1343
  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
- }
1344
+ this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
1516
1345
  }
1517
1346
  async onApplicationShutdown() {
1518
1347
  if (this.unsubscribe) {
@@ -1550,7 +1379,13 @@ var RealtimePubSubSubscriber = class {
1550
1379
  }
1551
1380
  case "disconnect": {
1552
1381
  const a = msg.args;
1553
- void this.sse.disconnectLocal(a.connectionId, a.reason);
1382
+ Promise.resolve(this.sse.disconnectLocal(a.connectionId, a.reason)).catch(
1383
+ (err) => {
1384
+ this.logger.warn(
1385
+ `Remote disconnect of ${a.connectionId} failed: ${describeError(err)}`
1386
+ );
1387
+ }
1388
+ );
1554
1389
  break;
1555
1390
  }
1556
1391
  default: {
@@ -1598,52 +1433,9 @@ var sseWiring = {
1598
1433
  }
1599
1434
  };
1600
1435
  var BymaxRealtimeModule = class {
1601
- /**
1602
- * Configure the module synchronously.
1603
- *
1604
- * @throws when the options are invalid.
1605
- * @example
1606
- * ```ts
1607
- * BymaxRealtimeModule.forRoot({
1608
- * transport: 'sse',
1609
- * authenticator: new MyAuthenticator(),
1610
- * })
1611
- * ```
1612
- */
1613
1436
  static forRoot(options) {
1614
1437
  return composeForRoot(BymaxRealtimeModule, sseWiring, BymaxRealtimeModule.logger, options);
1615
1438
  }
1616
- /**
1617
- * Configure the module asynchronously so options — and the authenticator —
1618
- * can be resolved through DI: `ConfigService`, a Redis client, and so on.
1619
- *
1620
- * Options are validated inside the resolving factory, so a malformed
1621
- * configuration rejects at bootstrap and the application fails to start with
1622
- * a clear error.
1623
- *
1624
- * Controllers are registered at decoration time, so the SSE route comes from
1625
- * `sseEndpoint` on the registration rather than from the `sse.endpoint` the
1626
- * factory resolves — the factory has not run yet when the controller is
1627
- * built. It defaults to `/events`, and a factory that resolves a disagreeing
1628
- * `sse.endpoint` is rejected at bootstrap rather than silently served on
1629
- * another path.
1630
- *
1631
- * @throws when no factory pattern is given, more than one is, or the factory
1632
- * resolves a transport other than `'sse'`.
1633
- * @example
1634
- * ```ts
1635
- * BymaxRealtimeModule.forRootAsync({
1636
- * transport: 'sse',
1637
- * sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
1638
- * imports: [ConfigModule],
1639
- * inject: [ConfigService],
1640
- * useFactory: (cfg: ConfigService) => ({
1641
- * transport: 'sse' as const,
1642
- * authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
1643
- * }),
1644
- * })
1645
- * ```
1646
- */
1647
1439
  static forRootAsync(asyncOptions) {
1648
1440
  return composeForRootAsync(
1649
1441
  BymaxRealtimeModule,
@@ -1658,40 +1450,42 @@ BymaxRealtimeModule = __decorateClass([
1658
1450
  Global(),
1659
1451
  Module({})
1660
1452
  ], BymaxRealtimeModule);
1661
-
1662
- // src/server/pubsub/redis-realtime-pubsub.ts
1663
- var RedisRealtimePubSub = class {
1664
- /**
1665
- * The publishing Redis client.
1666
- *
1667
- * An ECMAScript private field for the same reason as the subscriber below: an
1668
- * ioredis instance carries `options.password` as a plain field, and a
1669
- * TypeScript `private` one is erased at runtime, leaving it enumerable to
1670
- * anything that serializes this pubsub adapter.
1671
- */
1453
+ var MALFORMED_REPORT_INTERVAL_MS = 6e4;
1454
+ function connectionReason(err) {
1455
+ const code = err?.code;
1456
+ const text = describeError(err);
1457
+ return [typeof code === "string" ? code : "", text].filter(Boolean).join(" ") || String(err);
1458
+ }
1459
+ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1672
1460
  #pub;
1673
1461
  channel;
1674
- /** The lazily created subscriber connection, which carries the same credentials. */
1675
1462
  #subInit = null;
1676
1463
  handlers = /* @__PURE__ */ new Set();
1464
+ logger = new Logger(_RedisRealtimePubSub.name);
1465
+ malformedDropped = 0;
1466
+ malformedReportedAt = 0;
1467
+ #subscribed = false;
1468
+ #outageLogged = false;
1469
+ #retired = /* @__PURE__ */ new WeakSet();
1677
1470
  constructor(options) {
1678
1471
  this.#pub = options.client;
1679
1472
  this.channel = options.channel ?? "bymax:realtime";
1680
1473
  }
1681
- /** JSON-encodes the message and PUBLISHes it to the configured channel. */
1474
+ isSubscribed() {
1475
+ return this.#subscribed;
1476
+ }
1682
1477
  async publish(message) {
1478
+ const status = this.#pub.status;
1479
+ if (status === "reconnecting" || status === "close" || status === "end") {
1480
+ throw unavailableError(
1481
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1482
+ _RedisRealtimePubSub.name,
1483
+ `cannot publish to "${this.channel}"`,
1484
+ new Error(`the Redis client is ${status}`)
1485
+ );
1486
+ }
1683
1487
  await this.#pub.publish(this.channel, JSON.stringify(message));
1684
1488
  }
1685
- /**
1686
- * Lazily creates the single shared subscribe client on first call; returns an async
1687
- * unsubscribe that quits the client when the last handler is removed. Concurrent
1688
- * subscribe calls are idempotent — only one client is ever created. Malformed
1689
- * payloads are dropped silently.
1690
- *
1691
- * If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
1692
- * the handler registration is rolled back and the cached init promise is cleared so
1693
- * the next call retries from scratch.
1694
- */
1695
1489
  async subscribe(handler) {
1696
1490
  this.handlers.add(handler);
1697
1491
  let sub;
@@ -1706,29 +1500,116 @@ var RedisRealtimePubSub = class {
1706
1500
  this.handlers.delete(handler);
1707
1501
  if (this.handlers.size === 0) {
1708
1502
  this.#subInit = null;
1503
+ this.#retired.add(sub);
1504
+ const connected = this.#subscribed;
1505
+ this.#subscribed = false;
1709
1506
  try {
1710
- await sub.quit();
1507
+ if (connected) await sub.quit();
1508
+ else sub.disconnect();
1711
1509
  } catch {
1712
1510
  }
1713
1511
  }
1714
1512
  };
1715
1513
  }
1716
- /** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
1717
1514
  ensureSubscriber() {
1718
1515
  if (!this.#subInit) this.#subInit = this.createSubscriber();
1719
1516
  return this.#subInit;
1720
1517
  }
1721
1518
  async createSubscriber() {
1722
- const sub = this.#pub.duplicate();
1723
- await sub.subscribe(this.channel);
1519
+ this.#outageLogged = false;
1520
+ const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
1521
+ let attached = false;
1724
1522
  sub.on("message", (_ch, payload) => this.dispatch(payload));
1523
+ const unreachableFirst = new Promise((resolve) => {
1524
+ sub.on("error", (err) => {
1525
+ if (err.name !== "ReplyError") resolve({ unreachable: err });
1526
+ });
1527
+ sub.on("close", () => {
1528
+ resolve({ unreachable: new Error() });
1529
+ if (!this.#retired.has(sub)) this.markDown("connection closed");
1530
+ });
1531
+ });
1532
+ sub.on("ready", () => {
1533
+ if (attached) this.confirm(sub);
1534
+ });
1535
+ await this.negotiate(sub, sub.subscribe(this.channel), unreachableFirst);
1536
+ attached = true;
1725
1537
  return sub;
1726
1538
  }
1539
+ async negotiate(sub, first, unreachableFirst) {
1540
+ try {
1541
+ const outcome = await Promise.race([
1542
+ first.then(
1543
+ () => "subscribed",
1544
+ (err) => {
1545
+ if (err.name === "ReplyError") throw err;
1546
+ return { unreachable: err };
1547
+ }
1548
+ ),
1549
+ unreachableFirst
1550
+ ]);
1551
+ if (outcome === "subscribed") {
1552
+ this.markUp();
1553
+ } else {
1554
+ this.markDown(connectionReason(outcome.unreachable));
1555
+ first.catch((err) => this.refused(err));
1556
+ }
1557
+ } catch (err) {
1558
+ this.#retired.add(sub);
1559
+ sub.disconnect();
1560
+ throw unavailableError(
1561
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1562
+ _RedisRealtimePubSub.name,
1563
+ `could not subscribe to "${this.channel}"`,
1564
+ err
1565
+ );
1566
+ }
1567
+ }
1568
+ confirm(sub) {
1569
+ sub.subscribe(this.channel).then(
1570
+ () => this.markUp(),
1571
+ (err) => this.refused(err)
1572
+ );
1573
+ }
1574
+ refused(err) {
1575
+ if (err?.name !== "ReplyError") return;
1576
+ this.#subscribed = false;
1577
+ this.logger.warn(
1578
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${describeError(err)}`
1579
+ );
1580
+ }
1581
+ markUp() {
1582
+ if (this.#subscribed) return;
1583
+ this.#subscribed = true;
1584
+ this.#outageLogged = false;
1585
+ this.logger.log(
1586
+ `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
1587
+ );
1588
+ }
1589
+ markDown(reason) {
1590
+ this.#subscribed = false;
1591
+ if (this.#outageLogged) return;
1592
+ this.#outageLogged = true;
1593
+ this.logger.warn(
1594
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: not subscribed to "${this.channel}": ${reason}. Remote events and revocations will not reach this instance until it subscribes again`
1595
+ );
1596
+ }
1597
+ reportMalformed() {
1598
+ this.malformedDropped++;
1599
+ const now = Date.now();
1600
+ if (now - this.malformedReportedAt < MALFORMED_REPORT_INTERVAL_MS) return;
1601
+ this.logger.warn(
1602
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: dropped ${this.malformedDropped} malformed payload(s) on "${this.channel}" since the last report`
1603
+ );
1604
+ this.malformedDropped = 0;
1605
+ this.malformedReportedAt = now;
1606
+ }
1727
1607
  dispatch(payload) {
1728
1608
  let msg;
1729
1609
  try {
1730
1610
  msg = JSON.parse(payload);
1731
1611
  } catch {
1612
+ this.reportMalformed();
1732
1613
  return;
1733
1614
  }
1734
1615
  for (const h of this.handlers) {
@@ -1742,21 +1623,10 @@ var RedisRealtimePubSub = class {
1742
1623
 
1743
1624
  // src/server/offline-queue/redis-offline-queue.ts
1744
1625
  var RedisOfflineQueue = class _RedisOfflineQueue {
1745
- /**
1746
- * The Redis client.
1747
- *
1748
- * An ECMAScript private field rather than a TypeScript `private` one, which
1749
- * is erased at runtime: an ioredis instance carries `options.password` as a
1750
- * plain field, so leaving this enumerable would let anything that serializes
1751
- * this queue — or the module options that reference it — reach the Redis
1752
- * credentials.
1753
- */
1754
1626
  #client;
1755
1627
  maxPerUser;
1756
1628
  ttlSeconds;
1757
- /** Zero-pad width for the epoch-millisecond component of the sort key. */
1758
1629
  static MS_PAD = 16;
1759
- /** Zero-pad width for the intra-millisecond counter component of the sort key. */
1760
1630
  static COUNTER_PAD = 6;
1761
1631
  constructor(options) {
1762
1632
  this.#client = options.client;
@@ -1766,23 +1636,12 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1766
1636
  key(userId) {
1767
1637
  return `bymax:oq:${userId}`;
1768
1638
  }
1769
- /**
1770
- * Build the fixed-width lexicographic sort key for an event id.
1771
- *
1772
- * Handles two id formats:
1773
- * - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
1774
- * - Legacy plain numeric strings: `1700000000000`
1775
- */
1776
1639
  lexKey(id) {
1777
1640
  const dashIdx = id.indexOf("-");
1778
1641
  const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
1779
1642
  const counter = dashIdx === -1 ? 0 : Number(id.slice(dashIdx + 1));
1780
1643
  return String(ms).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(counter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
1781
1644
  }
1782
- /**
1783
- * Return the lexicographically next sort key after `id`, used as an
1784
- * inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
1785
- */
1786
1645
  lexKeyNext(id) {
1787
1646
  const dashIdx = id.indexOf("-");
1788
1647
  const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
@@ -1792,7 +1651,6 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1792
1651
  const nextCounter = counter < counterMax ? counter + 1 : 0;
1793
1652
  return String(nextMs).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(nextCounter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
1794
1653
  }
1795
- /** Encode an event into a lexicographically sortable ZSET member string. */
1796
1654
  encodeMember(event) {
1797
1655
  return `${this.lexKey(event.id)}|${JSON.stringify(event)}`;
1798
1656
  }
@@ -1826,4 +1684,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1826
1684
  }
1827
1685
  };
1828
1686
 
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 };
1687
+ 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 };