@bymax-one/nest-realtime 1.2.7 → 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.
- package/CHANGELOG.md +57 -1
- package/README.md +3 -1
- package/dist/internal/index.cjs +40 -458
- package/dist/internal/index.d.cts +13 -2
- package/dist/internal/index.d.ts +13 -2
- package/dist/internal/index.mjs +40 -458
- package/dist/react/index.cjs +0 -2
- package/dist/react/index.d.cts +2 -1
- package/dist/react/index.d.ts +2 -1
- package/dist/react/index.mjs +0 -2
- package/dist/shared/index.d.cts +2 -1
- package/dist/shared/index.d.ts +2 -1
- package/dist/websocket/index.cjs +0 -275
- package/dist/websocket/index.mjs +0 -275
- package/package.json +3 -3
package/dist/internal/index.mjs
CHANGED
|
@@ -47,6 +47,21 @@ function applyDefaults(options) {
|
|
|
47
47
|
sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
|
|
48
48
|
});
|
|
49
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
|
|
50
65
|
var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
|
|
51
66
|
function validateOptions(options) {
|
|
52
67
|
if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
|
|
@@ -78,9 +93,10 @@ function validateReauthPolicy(options) {
|
|
|
78
93
|
}
|
|
79
94
|
function validateSseOptions(options) {
|
|
80
95
|
const sse = options.sse;
|
|
81
|
-
|
|
96
|
+
const heartbeatMs = sse?.heartbeatMs;
|
|
97
|
+
if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
|
|
82
98
|
throw new Error(
|
|
83
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be
|
|
99
|
+
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`
|
|
84
100
|
);
|
|
85
101
|
}
|
|
86
102
|
if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
|
|
@@ -95,17 +111,6 @@ function validateSseOptions(options) {
|
|
|
95
111
|
}
|
|
96
112
|
}
|
|
97
113
|
|
|
98
|
-
// src/server/constants/injection-tokens.constants.ts
|
|
99
|
-
var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
|
|
100
|
-
var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
|
|
101
|
-
var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
|
|
102
|
-
var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
|
|
103
|
-
var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
|
|
104
|
-
var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
|
|
105
|
-
var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
|
|
106
|
-
var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
|
|
107
|
-
var DEFAULT_HEARTBEAT_MS = 3e4;
|
|
108
|
-
|
|
109
114
|
// src/server/utils/describe-error.ts
|
|
110
115
|
function describeError(reason) {
|
|
111
116
|
try {
|
|
@@ -138,19 +143,6 @@ var OfflineQueueDeliveryService = class {
|
|
|
138
143
|
storage;
|
|
139
144
|
hooks;
|
|
140
145
|
logger = new Logger(OfflineQueueDeliveryService.name);
|
|
141
|
-
/**
|
|
142
|
-
* Return events for `userId` that arrived after `lastEventId` and are NOT
|
|
143
|
-
* already covered by `ringBufferIds` (already replayed from in-memory buffer).
|
|
144
|
-
*
|
|
145
|
-
* Retrieval does NOT acknowledge: the durable queue is pruned only after the events
|
|
146
|
-
* have been emitted to a live subscriber via {@link acknowledge}. This guarantees
|
|
147
|
-
* at-least-once delivery — events that never reach the client are never lost.
|
|
148
|
-
*
|
|
149
|
-
* @param userId - The reconnecting user.
|
|
150
|
-
* @param lastEventId - The `Last-Event-ID` header value.
|
|
151
|
-
* @param ringBufferIds - Set of event ids already replayed from the ring buffer.
|
|
152
|
-
* @returns Gap events, or an empty array when no offline queue is configured.
|
|
153
|
-
*/
|
|
154
146
|
async retrieve(userId, lastEventId, ringBufferIds) {
|
|
155
147
|
if (!this.storage) return [];
|
|
156
148
|
let events;
|
|
@@ -176,17 +168,6 @@ var OfflineQueueDeliveryService = class {
|
|
|
176
168
|
}
|
|
177
169
|
return events.filter((e) => !ringBufferIds.has(e.id));
|
|
178
170
|
}
|
|
179
|
-
/**
|
|
180
|
-
* Acknowledge delivered offline events so the storage backend can prune them.
|
|
181
|
-
*
|
|
182
|
-
* At-least-once contract: call this ONLY after the events have been emitted to a
|
|
183
|
-
* still-open subscriber. Acknowledging before emission would permanently drop events
|
|
184
|
-
* that never reached the client. A failure is swallowed (logged) so a transient
|
|
185
|
-
* storage error never disrupts delivery; the events simply redeliver on reconnect.
|
|
186
|
-
*
|
|
187
|
-
* @param userId - The user whose queue is acknowledged.
|
|
188
|
-
* @param events - The delivered gap events; the last id is the prune watermark.
|
|
189
|
-
*/
|
|
190
171
|
async acknowledge(userId, events) {
|
|
191
172
|
if (!this.storage || events.length === 0) return;
|
|
192
173
|
const lastId = events[events.length - 1].id;
|
|
@@ -276,11 +257,6 @@ var ConnectionRegistry = class {
|
|
|
276
257
|
byId = /* @__PURE__ */ new Map();
|
|
277
258
|
byUserId = /* @__PURE__ */ new Map();
|
|
278
259
|
byTenantId = /* @__PURE__ */ new Map();
|
|
279
|
-
/**
|
|
280
|
-
* Register a connection and index it by user and tenant.
|
|
281
|
-
*
|
|
282
|
-
* @internal Transport bookkeeping: applications must not call it.
|
|
283
|
-
*/
|
|
284
260
|
register(record) {
|
|
285
261
|
this.byId.set(record.connectionId, record);
|
|
286
262
|
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
@@ -288,11 +264,6 @@ var ConnectionRegistry = class {
|
|
|
288
264
|
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
289
265
|
}
|
|
290
266
|
}
|
|
291
|
-
/**
|
|
292
|
-
* Remove a connection from every index. Returns the removed record, if any.
|
|
293
|
-
*
|
|
294
|
-
* @internal Transport bookkeeping: applications must not call it.
|
|
295
|
-
*/
|
|
296
267
|
unregister(connectionId) {
|
|
297
268
|
const record = this.byId.get(connectionId);
|
|
298
269
|
if (!record) return void 0;
|
|
@@ -303,27 +274,21 @@ var ConnectionRegistry = class {
|
|
|
303
274
|
}
|
|
304
275
|
return record;
|
|
305
276
|
}
|
|
306
|
-
/** Look up a single connection by id. */
|
|
307
277
|
get(connectionId) {
|
|
308
278
|
return this.byId.get(connectionId);
|
|
309
279
|
}
|
|
310
|
-
/** All connections of a user, optionally filtered by transport. */
|
|
311
280
|
byUser(userId, transport) {
|
|
312
281
|
return this.resolve(this.byUserId.get(userId), transport);
|
|
313
282
|
}
|
|
314
|
-
/** All connections of a tenant, optionally filtered by transport. */
|
|
315
283
|
byTenant(tenantId, transport) {
|
|
316
284
|
return this.resolve(this.byTenantId.get(tenantId), transport);
|
|
317
285
|
}
|
|
318
|
-
/** All connections of a given transport. */
|
|
319
286
|
allByTransport(transport) {
|
|
320
287
|
return Array.from(this.byId.values()).filter((record) => record.transport === transport);
|
|
321
288
|
}
|
|
322
|
-
/** Total number of active connections. */
|
|
323
289
|
count() {
|
|
324
290
|
return this.byId.size;
|
|
325
291
|
}
|
|
326
|
-
/** Number of distinct users currently connected. */
|
|
327
292
|
countUsers() {
|
|
328
293
|
return this.byUserId.size;
|
|
329
294
|
}
|
|
@@ -357,7 +322,6 @@ var COUNTER_WIDTH = 6;
|
|
|
357
322
|
var EventIdGenerator = class {
|
|
358
323
|
lastMs = 0;
|
|
359
324
|
counter = 0;
|
|
360
|
-
/** Produce the next monotonic event id. */
|
|
361
325
|
next() {
|
|
362
326
|
const now = Date.now();
|
|
363
327
|
if (now === this.lastMs) {
|
|
@@ -375,7 +339,6 @@ EventIdGenerator = __decorateClass([
|
|
|
375
339
|
var RoomRegistry = class {
|
|
376
340
|
rooms = /* @__PURE__ */ new Map();
|
|
377
341
|
connectionRooms = /* @__PURE__ */ new Map();
|
|
378
|
-
/** Join a connection to a room (idempotent). */
|
|
379
342
|
join(connectionId, roomId) {
|
|
380
343
|
const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
|
|
381
344
|
room.add(connectionId);
|
|
@@ -384,7 +347,6 @@ var RoomRegistry = class {
|
|
|
384
347
|
conn.add(roomId);
|
|
385
348
|
this.connectionRooms.set(connectionId, conn);
|
|
386
349
|
}
|
|
387
|
-
/** Remove a connection from a room (idempotent); prunes empty entries. */
|
|
388
350
|
leave(connectionId, roomId) {
|
|
389
351
|
const room = this.rooms.get(roomId);
|
|
390
352
|
if (room) {
|
|
@@ -397,17 +359,14 @@ var RoomRegistry = class {
|
|
|
397
359
|
if (conn.size === 0) this.connectionRooms.delete(connectionId);
|
|
398
360
|
}
|
|
399
361
|
}
|
|
400
|
-
/** Snapshot of a room's members — safe to iterate while membership mutates. */
|
|
401
362
|
members(roomId) {
|
|
402
363
|
const set = this.rooms.get(roomId);
|
|
403
364
|
return set ? Array.from(set) : [];
|
|
404
365
|
}
|
|
405
|
-
/** Snapshot of the rooms a connection currently belongs to. */
|
|
406
366
|
roomsOf(connectionId) {
|
|
407
367
|
const set = this.connectionRooms.get(connectionId);
|
|
408
368
|
return set ? Array.from(set) : [];
|
|
409
369
|
}
|
|
410
|
-
/** Remove a connection from every room (called on disconnect). */
|
|
411
370
|
leaveAll(connectionId) {
|
|
412
371
|
const rooms = this.connectionRooms.get(connectionId);
|
|
413
372
|
if (!rooms) return;
|
|
@@ -420,7 +379,6 @@ var RoomRegistry = class {
|
|
|
420
379
|
}
|
|
421
380
|
this.connectionRooms.delete(connectionId);
|
|
422
381
|
}
|
|
423
|
-
/** Total number of distinct rooms. */
|
|
424
382
|
countRooms() {
|
|
425
383
|
return this.rooms.size;
|
|
426
384
|
}
|
|
@@ -447,14 +405,6 @@ function unavailableError(code, who, what, cause) {
|
|
|
447
405
|
}
|
|
448
406
|
var InMemoryPubSub = class {
|
|
449
407
|
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
408
|
async publish(message) {
|
|
459
409
|
await Promise.resolve();
|
|
460
410
|
for (const handler of this.handlers) {
|
|
@@ -464,12 +414,6 @@ var InMemoryPubSub = class {
|
|
|
464
414
|
}
|
|
465
415
|
}
|
|
466
416
|
}
|
|
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
417
|
async subscribe(handler) {
|
|
474
418
|
this.handlers.add(handler);
|
|
475
419
|
return async () => {
|
|
@@ -487,7 +431,6 @@ var EventReplayBuffer = class {
|
|
|
487
431
|
}
|
|
488
432
|
opts;
|
|
489
433
|
buffers = /* @__PURE__ */ new Map();
|
|
490
|
-
/** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
|
|
491
434
|
append(userId, event) {
|
|
492
435
|
const buf = this.buffers.get(userId) ?? [];
|
|
493
436
|
buf.push(event);
|
|
@@ -495,12 +438,6 @@ var EventReplayBuffer = class {
|
|
|
495
438
|
if (buf.length > cap) buf.shift();
|
|
496
439
|
this.buffers.set(userId, buf);
|
|
497
440
|
}
|
|
498
|
-
/**
|
|
499
|
-
* Return the events emitted after `lastEventId`.
|
|
500
|
-
*
|
|
501
|
-
* Returns an empty array when the user has no buffer, or when `lastEventId` is
|
|
502
|
-
* not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
|
|
503
|
-
*/
|
|
504
441
|
since(userId, lastEventId) {
|
|
505
442
|
const buf = this.buffers.get(userId);
|
|
506
443
|
if (!buf) return [];
|
|
@@ -508,7 +445,6 @@ var EventReplayBuffer = class {
|
|
|
508
445
|
if (idx === -1) return [];
|
|
509
446
|
return buf.slice(idx + 1);
|
|
510
447
|
}
|
|
511
|
-
/** Number of events currently buffered for a user (diagnostics). */
|
|
512
448
|
size(userId) {
|
|
513
449
|
return this.buffers.get(userId)?.length ?? 0;
|
|
514
450
|
}
|
|
@@ -518,19 +454,8 @@ EventReplayBuffer = __decorateClass([
|
|
|
518
454
|
__decorateParam(0, Inject(REALTIME_OPTIONS_TOKEN))
|
|
519
455
|
], EventReplayBuffer);
|
|
520
456
|
var KEEPALIVE_COMMENT = ": keepalive\n\n";
|
|
521
|
-
var HEARTBEAT_MIN_MS = 5e3;
|
|
522
|
-
var HEARTBEAT_MAX_MS = 9e4;
|
|
523
457
|
var HeartbeatService = class {
|
|
524
458
|
timers = /* @__PURE__ */ new Map();
|
|
525
|
-
/**
|
|
526
|
-
* Start writing keepalives for a connection every `intervalMs`.
|
|
527
|
-
*
|
|
528
|
-
* @param connectionId - Unique connection identifier used to track the timer.
|
|
529
|
-
* @param res - The writable response stream (or any object with a `write` method).
|
|
530
|
-
* @param intervalMs - Keepalive interval in milliseconds; must be within
|
|
531
|
-
* `[5_000, 90_000]`.
|
|
532
|
-
* @throws {Error} When `intervalMs` is outside the valid range.
|
|
533
|
-
*/
|
|
534
459
|
start(connectionId, res, intervalMs) {
|
|
535
460
|
if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
|
|
536
461
|
throw new Error(
|
|
@@ -548,7 +473,6 @@ var HeartbeatService = class {
|
|
|
548
473
|
timer.unref();
|
|
549
474
|
this.timers.set(connectionId, timer);
|
|
550
475
|
}
|
|
551
|
-
/** Stop and clear the keepalive timer for a connection (idempotent). */
|
|
552
476
|
stop(connectionId) {
|
|
553
477
|
const timer = this.timers.get(connectionId);
|
|
554
478
|
if (timer) {
|
|
@@ -556,7 +480,6 @@ var HeartbeatService = class {
|
|
|
556
480
|
this.timers.delete(connectionId);
|
|
557
481
|
}
|
|
558
482
|
}
|
|
559
|
-
/** Stop every keepalive timer (used on shutdown). */
|
|
560
483
|
stopAll() {
|
|
561
484
|
for (const timer of this.timers.values()) clearInterval(timer);
|
|
562
485
|
this.timers.clear();
|
|
@@ -594,32 +517,21 @@ var SseTransport = class {
|
|
|
594
517
|
offlineQueue;
|
|
595
518
|
kind = "sse";
|
|
596
519
|
logger = new Logger(SseTransport.name);
|
|
597
|
-
/** Tear down every SSE connection and stop heartbeat on process shutdown. */
|
|
598
520
|
async onApplicationShutdown() {
|
|
599
521
|
this.heartbeat.stopAll();
|
|
600
522
|
for (const conn of this.connections.allByTransport("sse")) {
|
|
601
523
|
await this.disconnectLocal(conn.connectionId);
|
|
602
524
|
}
|
|
603
525
|
}
|
|
604
|
-
/** The resolved heartbeat interval for this transport. */
|
|
605
526
|
get heartbeatMs() {
|
|
606
527
|
return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
607
528
|
}
|
|
608
|
-
/** Whether the `connection:established` event should be emitted on connect. */
|
|
609
529
|
get emitConnectionEvent() {
|
|
610
530
|
return this.options.sse?.emitConnectionEvent !== false;
|
|
611
531
|
}
|
|
612
|
-
/** Authenticate a connection through the consumer-provided authenticator. */
|
|
613
532
|
authenticate(context) {
|
|
614
533
|
return this.auth.authenticate(context);
|
|
615
534
|
}
|
|
616
|
-
/**
|
|
617
|
-
* Register an authenticated SSE connection and auto-join its user/tenant rooms.
|
|
618
|
-
*
|
|
619
|
-
* Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
|
|
620
|
-
* lifecycle hook is fired by the subscription handler after this returns, so that the
|
|
621
|
-
* handler can carry a consistent connection record reference.
|
|
622
|
-
*/
|
|
623
535
|
async registerConnection(params) {
|
|
624
536
|
const record = {
|
|
625
537
|
connectionId: params.connectionId,
|
|
@@ -645,7 +557,6 @@ var SseTransport = class {
|
|
|
645
557
|
}
|
|
646
558
|
await this.evictBeyondLimit(params.auth.userId);
|
|
647
559
|
}
|
|
648
|
-
/** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
|
|
649
560
|
async unregisterConnection(connectionId, reason) {
|
|
650
561
|
const record = this.connections.unregister(connectionId);
|
|
651
562
|
if (!record) return;
|
|
@@ -669,39 +580,15 @@ var SseTransport = class {
|
|
|
669
580
|
this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
|
|
670
581
|
}
|
|
671
582
|
}
|
|
672
|
-
/** Replay the events a user missed after `lastEventId`. */
|
|
673
583
|
getReplayEvents(userId, lastEventId) {
|
|
674
584
|
return this.replayBuffer.since(userId, lastEventId);
|
|
675
585
|
}
|
|
676
|
-
/**
|
|
677
|
-
* All SSE connections for a user — public accessor so external callers can
|
|
678
|
-
* inspect or iterate without reaching into a private registry field.
|
|
679
|
-
*
|
|
680
|
-
* @param userId - The user whose active connections are returned.
|
|
681
|
-
* @returns A snapshot of the user's current SSE `ConnectionRecord` list.
|
|
682
|
-
*/
|
|
683
586
|
connectionsForUser(userId) {
|
|
684
587
|
return this.connections.byUser(userId, "sse");
|
|
685
588
|
}
|
|
686
|
-
/**
|
|
687
|
-
* Look up a single connection by id.
|
|
688
|
-
*
|
|
689
|
-
* @param connectionId - The unique connection identifier.
|
|
690
|
-
* @returns The `ConnectionRecord`, or `undefined` when not found.
|
|
691
|
-
*/
|
|
692
589
|
getConnection(connectionId) {
|
|
693
590
|
return this.connections.get(connectionId);
|
|
694
591
|
}
|
|
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
|
-
*/
|
|
705
592
|
async emitToUser(userId, event, data) {
|
|
706
593
|
const id = this.idGen.next();
|
|
707
594
|
this.emitToUserLocal(userId, event, data, id);
|
|
@@ -733,7 +620,6 @@ var SseTransport = class {
|
|
|
733
620
|
);
|
|
734
621
|
}
|
|
735
622
|
}
|
|
736
|
-
/** Append to the offline queue; resolves with the failure, or `undefined` once it is kept. */
|
|
737
623
|
async tryAppend(queue, userId, event) {
|
|
738
624
|
try {
|
|
739
625
|
await queue.append(userId, event);
|
|
@@ -742,7 +628,6 @@ var SseTransport = class {
|
|
|
742
628
|
return { error };
|
|
743
629
|
}
|
|
744
630
|
}
|
|
745
|
-
/** Whether the bus can carry an event to another instance (the in-memory bus cannot). */
|
|
746
631
|
busReachesOtherInstances() {
|
|
747
632
|
return !(this.pubsub instanceof InMemoryPubSub);
|
|
748
633
|
}
|
|
@@ -761,24 +646,14 @@ var SseTransport = class {
|
|
|
761
646
|
this.broadcastLocal(event, data, id);
|
|
762
647
|
await this.publish({ op: "broadcast", args: { event, data, id } });
|
|
763
648
|
}
|
|
764
|
-
/** Join a connection this instance holds to a room; any other id is left alone. */
|
|
765
649
|
async joinRoom(connectionId, roomId) {
|
|
766
650
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
767
651
|
this.rooms.join(connectionId, roomId);
|
|
768
652
|
}
|
|
769
|
-
/** Remove a connection this instance holds from a room; any other id is left alone. */
|
|
770
653
|
async leaveRoom(connectionId, roomId) {
|
|
771
654
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
772
655
|
this.rooms.leave(connectionId, roomId);
|
|
773
656
|
}
|
|
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
|
-
*/
|
|
782
657
|
async disconnect(connectionId, reason) {
|
|
783
658
|
const record = this.connections.get(connectionId);
|
|
784
659
|
if (record) {
|
|
@@ -800,37 +675,15 @@ var SseTransport = class {
|
|
|
800
675
|
);
|
|
801
676
|
}
|
|
802
677
|
}
|
|
803
|
-
/**
|
|
804
|
-
* Deliver an event to a user's local SSE connections and update the replay buffer.
|
|
805
|
-
*
|
|
806
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
807
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
808
|
-
*/
|
|
809
678
|
emitToUserLocal(userId, event, data, id) {
|
|
810
679
|
const message = this.buildMessage(id, event, data);
|
|
811
680
|
this.replayBuffer.append(userId, message);
|
|
812
681
|
for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
|
|
813
682
|
}
|
|
814
|
-
/**
|
|
815
|
-
* Deliver an event to all local SSE connections for a tenant.
|
|
816
|
-
*
|
|
817
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
818
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
819
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
820
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
821
|
-
*/
|
|
822
683
|
emitToTenantLocal(tenantId, event, data, id) {
|
|
823
684
|
const message = this.buildMessage(id, event, data);
|
|
824
685
|
for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
|
|
825
686
|
}
|
|
826
|
-
/**
|
|
827
|
-
* Deliver an event to all local SSE connections that joined the given room.
|
|
828
|
-
*
|
|
829
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
830
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
831
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
832
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
833
|
-
*/
|
|
834
687
|
emitToRoomLocal(roomId, event, data, id) {
|
|
835
688
|
const message = this.buildMessage(id, event, data);
|
|
836
689
|
for (const connectionId of this.rooms.members(roomId)) {
|
|
@@ -838,24 +691,10 @@ var SseTransport = class {
|
|
|
838
691
|
if (conn && conn.transport === "sse") this.deliver(conn, message);
|
|
839
692
|
}
|
|
840
693
|
}
|
|
841
|
-
/**
|
|
842
|
-
* Deliver an event to all local SSE connections.
|
|
843
|
-
*
|
|
844
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
845
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
846
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
847
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
848
|
-
*/
|
|
849
694
|
broadcastLocal(event, data, id) {
|
|
850
695
|
const message = this.buildMessage(id, event, data);
|
|
851
696
|
for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
|
|
852
697
|
}
|
|
853
|
-
/**
|
|
854
|
-
* Tear down a locally-owned SSE stream, then clean up (no re-publish).
|
|
855
|
-
*
|
|
856
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
857
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
858
|
-
*/
|
|
859
698
|
async disconnectLocal(connectionId, reason) {
|
|
860
699
|
const record = this.connections.get(connectionId);
|
|
861
700
|
if (!record || record.transport !== "sse") return;
|
|
@@ -866,7 +705,6 @@ var SseTransport = class {
|
|
|
866
705
|
buildMessage(id, event, data) {
|
|
867
706
|
return { id, type: event, data };
|
|
868
707
|
}
|
|
869
|
-
/** Deliver to one connection, isolating failures so others still receive the event. */
|
|
870
708
|
deliver(conn, message) {
|
|
871
709
|
try {
|
|
872
710
|
conn.subject?.next(message);
|
|
@@ -874,7 +712,6 @@ var SseTransport = class {
|
|
|
874
712
|
this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
|
|
875
713
|
}
|
|
876
714
|
}
|
|
877
|
-
/** Publish once to the bus; resolves with the failure, or `undefined` once the bus accepted it. */
|
|
878
715
|
async tryPublish(message) {
|
|
879
716
|
try {
|
|
880
717
|
await this.pubsub.publish({ ...message, origin: this.instanceId });
|
|
@@ -883,7 +720,6 @@ var SseTransport = class {
|
|
|
883
720
|
return { error };
|
|
884
721
|
}
|
|
885
722
|
}
|
|
886
|
-
/** Publish once to the bus. A failure is reported and never fails the live emit path. */
|
|
887
723
|
async publish(message) {
|
|
888
724
|
const failure = await this.tryPublish(message);
|
|
889
725
|
if (failure !== void 0) this.reportPublishFailure(message.op, failure);
|
|
@@ -896,7 +732,6 @@ var SseTransport = class {
|
|
|
896
732
|
"pubsub.publish failed"
|
|
897
733
|
);
|
|
898
734
|
}
|
|
899
|
-
/** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
|
|
900
735
|
async evictBeyondLimit(userId) {
|
|
901
736
|
const max = this.options.sse?.maxConnectionsPerUser;
|
|
902
737
|
if (max === void 0 || max <= 0) return;
|
|
@@ -995,29 +830,6 @@ var SseSubscriptionHandler = class {
|
|
|
995
830
|
offlineDelivery;
|
|
996
831
|
logger = new Logger(SseSubscriptionHandler.name);
|
|
997
832
|
authenticated = /* @__PURE__ */ new WeakMap();
|
|
998
|
-
/**
|
|
999
|
-
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
1000
|
-
*
|
|
1001
|
-
* Both transports resolve the routing tenant through this one function, so a
|
|
1002
|
-
* connection carries the same tenant whichever one opened it. The check runs on
|
|
1003
|
-
* the resolved value rather than the raw one — validating what the server does not
|
|
1004
|
-
* use would validate nothing.
|
|
1005
|
-
*
|
|
1006
|
-
* A blank identity is the consumer's configuration rather than the client's
|
|
1007
|
-
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
1008
|
-
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
1009
|
-
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
1010
|
-
* once, not an unhandled crash logging a stack on every reconnect.
|
|
1011
|
-
*
|
|
1012
|
-
* The reason names the operator's fix, so it goes to the server log and the client
|
|
1013
|
-
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
1014
|
-
* without a message.
|
|
1015
|
-
*
|
|
1016
|
-
* @param auth - The result the consumer's authenticator returned.
|
|
1017
|
-
* @returns The same result with the routing tenant resolved.
|
|
1018
|
-
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
1019
|
-
* but blank.
|
|
1020
|
-
*/
|
|
1021
833
|
resolveAndValidateIdentity(auth) {
|
|
1022
834
|
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
1023
835
|
try {
|
|
@@ -1028,27 +840,6 @@ var SseSubscriptionHandler = class {
|
|
|
1028
840
|
}
|
|
1029
841
|
return resolvedAuth;
|
|
1030
842
|
}
|
|
1031
|
-
/**
|
|
1032
|
-
* Handle an incoming SSE connection request end-to-end.
|
|
1033
|
-
*
|
|
1034
|
-
* Sets anti-buffering headers, authenticates the request, captures the offline-gap
|
|
1035
|
-
* before exposing the connection, then returns an Observable whose subscriber callback
|
|
1036
|
-
* wires the downstream listener BEFORE calling `registerConnection` — so a plain
|
|
1037
|
-
* `Subject` suffices and the replay buffer cannot grow unboundedly.
|
|
1038
|
-
*
|
|
1039
|
-
* @param req - The incoming request (SSE GET).
|
|
1040
|
-
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
1041
|
-
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
1042
|
-
* @throws UnauthorizedException when authentication returns null — the client's
|
|
1043
|
-
* credentials were rejected, which is a 401.
|
|
1044
|
-
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
1045
|
-
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
1046
|
-
* a 401: the credentials were accepted and the fault is the consumer's
|
|
1047
|
-
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
1048
|
-
* something that cannot succeed. The exception carries no message, so the client
|
|
1049
|
-
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
1050
|
-
* written to the server log.
|
|
1051
|
-
*/
|
|
1052
843
|
async handle(req, res) {
|
|
1053
844
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
1054
845
|
res.setHeader("X-Accel-Buffering", "no");
|
|
@@ -1090,10 +881,6 @@ var SseSubscriptionHandler = class {
|
|
|
1090
881
|
queueEvents
|
|
1091
882
|
});
|
|
1092
883
|
}
|
|
1093
|
-
/**
|
|
1094
|
-
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
1095
|
-
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
1096
|
-
*/
|
|
1097
884
|
async authenticateBeforeCommit(req) {
|
|
1098
885
|
try {
|
|
1099
886
|
this.authenticated.set(req, await this.authenticateRequest(req));
|
|
@@ -1101,7 +888,6 @@ var SseSubscriptionHandler = class {
|
|
|
1101
888
|
throw this.toClientError(err, "SSE authentication failed");
|
|
1102
889
|
}
|
|
1103
890
|
}
|
|
1104
|
-
// Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
|
|
1105
891
|
toClientError(err, what) {
|
|
1106
892
|
return err instanceof HttpException ? err : this.serverError(err, what);
|
|
1107
893
|
}
|
|
@@ -1115,15 +901,6 @@ var SseSubscriptionHandler = class {
|
|
|
1115
901
|
if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
1116
902
|
return { context, auth: this.resolveAndValidateIdentity(auth) };
|
|
1117
903
|
}
|
|
1118
|
-
/**
|
|
1119
|
-
* Build the live Observable using a subscribe-before-register pattern.
|
|
1120
|
-
*
|
|
1121
|
-
* The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
|
|
1122
|
-
* already has a listener when `registerConnection` runs. Any `subject.next()` that
|
|
1123
|
-
* occurs during or after registration goes directly to the subscriber — nothing is
|
|
1124
|
-
* buffered or retained, nothing is dropped, and ordering (established → replay →
|
|
1125
|
-
* queue → live) is preserved.
|
|
1126
|
-
*/
|
|
1127
904
|
buildStream(p) {
|
|
1128
905
|
return new Observable((subscriber) => {
|
|
1129
906
|
const inner = this.subscribePipeline(p, subscriber);
|
|
@@ -1134,12 +911,6 @@ var SseSubscriptionHandler = class {
|
|
|
1134
911
|
return () => inner.unsubscribe();
|
|
1135
912
|
});
|
|
1136
913
|
}
|
|
1137
|
-
/**
|
|
1138
|
-
* Wire the merged pipeline to the downstream subscriber with teardown.
|
|
1139
|
-
*
|
|
1140
|
-
* Subscribing first guarantees `subject` has a listener before registration can emit,
|
|
1141
|
-
* so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
|
|
1142
|
-
*/
|
|
1143
914
|
subscribePipeline(p, subscriber) {
|
|
1144
915
|
const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
|
|
1145
916
|
const queueReplay$ = queueEvents.length > 0 ? of(...queueEvents.map(toMessageEvent)) : EMPTY;
|
|
@@ -1157,12 +928,6 @@ var SseSubscriptionHandler = class {
|
|
|
1157
928
|
})
|
|
1158
929
|
).subscribe(subscriber);
|
|
1159
930
|
}
|
|
1160
|
-
/**
|
|
1161
|
-
* Register the connection (after the subscriber is wired) and activate it on resolution.
|
|
1162
|
-
*
|
|
1163
|
-
* A registration failure routes to `onError` and errors the stream; a failure that
|
|
1164
|
-
* arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
|
|
1165
|
-
*/
|
|
1166
931
|
activateConnection(p, subscriber) {
|
|
1167
932
|
const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
|
|
1168
933
|
this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
|
|
@@ -1172,15 +937,6 @@ var SseSubscriptionHandler = class {
|
|
|
1172
937
|
subscriber.error(this.serverError(err, "SSE registration failed"));
|
|
1173
938
|
});
|
|
1174
939
|
}
|
|
1175
|
-
/**
|
|
1176
|
-
* Complete the connection handshake once registration resolves.
|
|
1177
|
-
*
|
|
1178
|
-
* Registration is async and can resolve AFTER the downstream subscriber has already
|
|
1179
|
-
* torn down (client disconnected mid-handshake). When that happens `finalize` has
|
|
1180
|
-
* already stopped the heartbeat and unregistered, so re-firing onConnect or starting
|
|
1181
|
-
* a fresh heartbeat would leak the connection and write after close. Guard on
|
|
1182
|
-
* `subscriber.closed`: if closed, undo the late registration idempotently and return.
|
|
1183
|
-
*/
|
|
1184
940
|
onRegistered(p, subscriber) {
|
|
1185
941
|
const { connectionId, res } = p;
|
|
1186
942
|
if (subscriber.closed) {
|
|
@@ -1195,12 +951,6 @@ var SseSubscriptionHandler = class {
|
|
|
1195
951
|
const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
1196
952
|
this.heartbeat.start(connectionId, res, heartbeatMs);
|
|
1197
953
|
}
|
|
1198
|
-
/**
|
|
1199
|
-
* Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
|
|
1200
|
-
* so it never disrupts the connection lifecycle or live event delivery.
|
|
1201
|
-
*
|
|
1202
|
-
* @param invoke - A zero-arg function that calls the hook (handles optionality).
|
|
1203
|
-
*/
|
|
1204
954
|
fireHook(invoke) {
|
|
1205
955
|
void Promise.resolve(invoke()).catch((err) => {
|
|
1206
956
|
this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
|
|
@@ -1241,9 +991,6 @@ function createSseController(endpoint) {
|
|
|
1241
991
|
__decorateParam(0, Inject(SseSubscriptionHandler))
|
|
1242
992
|
], SseAuthGuard);
|
|
1243
993
|
let DynamicSseController = class {
|
|
1244
|
-
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
1245
|
-
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
1246
|
-
// be resolved by token rather than by reflected type.
|
|
1247
994
|
constructor(handler) {
|
|
1248
995
|
this.handler = handler;
|
|
1249
996
|
}
|
|
@@ -1271,80 +1018,28 @@ var RealtimeService = class {
|
|
|
1271
1018
|
}
|
|
1272
1019
|
transport;
|
|
1273
1020
|
pubsub;
|
|
1274
|
-
/**
|
|
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.
|
|
1279
|
-
*
|
|
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
|
-
* ```
|
|
1285
|
-
*/
|
|
1286
1021
|
isPubSubReady() {
|
|
1287
1022
|
if (this.transport.kind === "websocket") return true;
|
|
1288
1023
|
return this.pubsub?.isSubscribed?.() ?? true;
|
|
1289
1024
|
}
|
|
1290
|
-
/**
|
|
1291
|
-
* Send to all of a user's connections (across devices/tabs).
|
|
1292
|
-
*
|
|
1293
|
-
* @example
|
|
1294
|
-
* ```ts
|
|
1295
|
-
* await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
|
|
1296
|
-
* ```
|
|
1297
|
-
*/
|
|
1298
1025
|
emitToUser(userId, event, data) {
|
|
1299
1026
|
return this.transport.emitToUser(userId, event, data);
|
|
1300
1027
|
}
|
|
1301
|
-
/** Send to every connection in a tenant. */
|
|
1302
1028
|
emitToTenant(tenantId, event, data) {
|
|
1303
1029
|
return this.transport.emitToTenant(tenantId, event, data);
|
|
1304
1030
|
}
|
|
1305
|
-
/**
|
|
1306
|
-
* Send to a logical room. Use the prefix convention (`user:{id}`,
|
|
1307
|
-
* `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
|
|
1308
|
-
*/
|
|
1309
1031
|
emitToRoom(roomId, event, data) {
|
|
1310
1032
|
return this.transport.emitToRoom(roomId, event, data);
|
|
1311
1033
|
}
|
|
1312
|
-
/** Send to every connected client. Use sparingly. */
|
|
1313
1034
|
broadcast(event, data) {
|
|
1314
1035
|
return this.transport.broadcast(event, data);
|
|
1315
1036
|
}
|
|
1316
|
-
/**
|
|
1317
|
-
* Add a specific connection to a room.
|
|
1318
|
-
*
|
|
1319
|
-
* The room id is not checked. Never pass client-supplied input that could start
|
|
1320
|
-
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
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.
|
|
1325
|
-
*/
|
|
1326
1037
|
joinRoom(connectionId, roomId) {
|
|
1327
1038
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1328
1039
|
}
|
|
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
|
-
*/
|
|
1335
1040
|
leaveRoom(connectionId, roomId) {
|
|
1336
1041
|
return this.transport.leaveRoom(connectionId, roomId);
|
|
1337
1042
|
}
|
|
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
|
-
*/
|
|
1348
1043
|
disconnect(connectionId, reason) {
|
|
1349
1044
|
return this.transport.disconnect(connectionId, reason);
|
|
1350
1045
|
}
|
|
@@ -1376,16 +1071,8 @@ var ReauthenticationService = class {
|
|
|
1376
1071
|
hooks;
|
|
1377
1072
|
logger = new Logger(ReauthenticationService.name);
|
|
1378
1073
|
timer = null;
|
|
1379
|
-
/** connectionId → epoch-ms timestamp of last successful revalidation. */
|
|
1380
1074
|
positiveCache = /* @__PURE__ */ new Map();
|
|
1381
1075
|
policy;
|
|
1382
|
-
/**
|
|
1383
|
-
* Schedule the periodic revalidation cycle.
|
|
1384
|
-
*
|
|
1385
|
-
* The timer is unref'd so it never keeps the process alive on its own.
|
|
1386
|
-
* When the authenticator does not implement `revalidate`, the service stays
|
|
1387
|
-
* idle and emits an informative log.
|
|
1388
|
-
*/
|
|
1389
1076
|
onModuleInit() {
|
|
1390
1077
|
if (!this.auth.revalidate) {
|
|
1391
1078
|
this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
|
|
@@ -1399,11 +1086,6 @@ var ReauthenticationService = class {
|
|
|
1399
1086
|
this.timer.unref();
|
|
1400
1087
|
this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
|
|
1401
1088
|
}
|
|
1402
|
-
/**
|
|
1403
|
-
* Clear the timer and the positive cache.
|
|
1404
|
-
*
|
|
1405
|
-
* Called by NestJS on graceful shutdown to prevent leaks.
|
|
1406
|
-
*/
|
|
1407
1089
|
onApplicationShutdown() {
|
|
1408
1090
|
if (this.timer) {
|
|
1409
1091
|
clearInterval(this.timer);
|
|
@@ -1411,15 +1093,6 @@ var ReauthenticationService = class {
|
|
|
1411
1093
|
}
|
|
1412
1094
|
this.positiveCache.clear();
|
|
1413
1095
|
}
|
|
1414
|
-
/**
|
|
1415
|
-
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
1416
|
-
*
|
|
1417
|
-
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1418
|
-
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
1419
|
-
* `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
|
|
1420
|
-
*
|
|
1421
|
-
* Exposed as public for test access.
|
|
1422
|
-
*/
|
|
1423
1096
|
async runCycle() {
|
|
1424
1097
|
const now = Date.now();
|
|
1425
1098
|
const connections = [
|
|
@@ -1448,11 +1121,6 @@ var ReauthenticationService = class {
|
|
|
1448
1121
|
}
|
|
1449
1122
|
}
|
|
1450
1123
|
}
|
|
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
1124
|
async revoke(conn) {
|
|
1457
1125
|
try {
|
|
1458
1126
|
await this.handleFailure(conn);
|
|
@@ -1462,7 +1130,6 @@ var ReauthenticationService = class {
|
|
|
1462
1130
|
);
|
|
1463
1131
|
}
|
|
1464
1132
|
}
|
|
1465
|
-
/** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
|
|
1466
1133
|
async handleFailure(conn) {
|
|
1467
1134
|
this.positiveCache.delete(conn.connectionId);
|
|
1468
1135
|
if (this.policy.onFailure === "event") {
|
|
@@ -1766,52 +1433,9 @@ var sseWiring = {
|
|
|
1766
1433
|
}
|
|
1767
1434
|
};
|
|
1768
1435
|
var BymaxRealtimeModule = class {
|
|
1769
|
-
/**
|
|
1770
|
-
* Configure the module synchronously.
|
|
1771
|
-
*
|
|
1772
|
-
* @throws when the options are invalid.
|
|
1773
|
-
* @example
|
|
1774
|
-
* ```ts
|
|
1775
|
-
* BymaxRealtimeModule.forRoot({
|
|
1776
|
-
* transport: 'sse',
|
|
1777
|
-
* authenticator: new MyAuthenticator(),
|
|
1778
|
-
* })
|
|
1779
|
-
* ```
|
|
1780
|
-
*/
|
|
1781
1436
|
static forRoot(options) {
|
|
1782
1437
|
return composeForRoot(BymaxRealtimeModule, sseWiring, BymaxRealtimeModule.logger, options);
|
|
1783
1438
|
}
|
|
1784
|
-
/**
|
|
1785
|
-
* Configure the module asynchronously so options — and the authenticator —
|
|
1786
|
-
* can be resolved through DI: `ConfigService`, a Redis client, and so on.
|
|
1787
|
-
*
|
|
1788
|
-
* Options are validated inside the resolving factory, so a malformed
|
|
1789
|
-
* configuration rejects at bootstrap and the application fails to start with
|
|
1790
|
-
* a clear error.
|
|
1791
|
-
*
|
|
1792
|
-
* Controllers are registered at decoration time, so the SSE route comes from
|
|
1793
|
-
* `sseEndpoint` on the registration rather than from the `sse.endpoint` the
|
|
1794
|
-
* factory resolves — the factory has not run yet when the controller is
|
|
1795
|
-
* built. It defaults to `/events`, and a factory that resolves a disagreeing
|
|
1796
|
-
* `sse.endpoint` is rejected at bootstrap rather than silently served on
|
|
1797
|
-
* another path.
|
|
1798
|
-
*
|
|
1799
|
-
* @throws when no factory pattern is given, more than one is, or the factory
|
|
1800
|
-
* resolves a transport other than `'sse'`.
|
|
1801
|
-
* @example
|
|
1802
|
-
* ```ts
|
|
1803
|
-
* BymaxRealtimeModule.forRootAsync({
|
|
1804
|
-
* transport: 'sse',
|
|
1805
|
-
* sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
|
|
1806
|
-
* imports: [ConfigModule],
|
|
1807
|
-
* inject: [ConfigService],
|
|
1808
|
-
* useFactory: (cfg: ConfigService) => ({
|
|
1809
|
-
* transport: 'sse' as const,
|
|
1810
|
-
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
1811
|
-
* }),
|
|
1812
|
-
* })
|
|
1813
|
-
* ```
|
|
1814
|
-
*/
|
|
1815
1439
|
static forRootAsync(asyncOptions) {
|
|
1816
1440
|
return composeForRootAsync(
|
|
1817
1441
|
BymaxRealtimeModule,
|
|
@@ -1833,56 +1457,35 @@ function connectionReason(err) {
|
|
|
1833
1457
|
return [typeof code === "string" ? code : "", text].filter(Boolean).join(" ") || String(err);
|
|
1834
1458
|
}
|
|
1835
1459
|
var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
1836
|
-
/**
|
|
1837
|
-
* The publishing Redis client.
|
|
1838
|
-
*
|
|
1839
|
-
* An ECMAScript private field for the same reason as the subscriber below: an
|
|
1840
|
-
* ioredis instance carries `options.password` as a plain field, and a
|
|
1841
|
-
* TypeScript `private` one is erased at runtime, leaving it enumerable to
|
|
1842
|
-
* anything that serializes this pubsub adapter.
|
|
1843
|
-
*/
|
|
1844
1460
|
#pub;
|
|
1845
1461
|
channel;
|
|
1846
|
-
/** The lazily created subscriber connection, which carries the same credentials. */
|
|
1847
1462
|
#subInit = null;
|
|
1848
1463
|
handlers = /* @__PURE__ */ new Set();
|
|
1849
1464
|
logger = new Logger(_RedisRealtimePubSub.name);
|
|
1850
|
-
/** Payloads dropped as unparsable since the last report, and when that report was made. */
|
|
1851
1465
|
malformedDropped = 0;
|
|
1852
1466
|
malformedReportedAt = 0;
|
|
1853
|
-
/** Whether the subscriber connection holds a confirmed SUBSCRIBE right now. */
|
|
1854
1467
|
#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
1468
|
#outageLogged = false;
|
|
1858
|
-
/** Connections closed on purpose, whose `close` is not an outage and says nothing of a successor. */
|
|
1859
1469
|
#retired = /* @__PURE__ */ new WeakSet();
|
|
1860
1470
|
constructor(options) {
|
|
1861
1471
|
this.#pub = options.client;
|
|
1862
1472
|
this.channel = options.channel ?? "bymax:realtime";
|
|
1863
1473
|
}
|
|
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
1474
|
isSubscribed() {
|
|
1870
1475
|
return this.#subscribed;
|
|
1871
1476
|
}
|
|
1872
|
-
/** JSON-encodes the message and PUBLISHes it to the configured channel. */
|
|
1873
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
|
+
}
|
|
1874
1487
|
await this.#pub.publish(this.channel, JSON.stringify(message));
|
|
1875
1488
|
}
|
|
1876
|
-
/**
|
|
1877
|
-
* Lazily creates the single shared subscribe client on first call; returns an async
|
|
1878
|
-
* unsubscribe that quits the client when the last handler is removed. Concurrent
|
|
1879
|
-
* subscribe calls are idempotent — only one client is ever created. Malformed
|
|
1880
|
-
* payloads are dropped, and reported at most once a minute with their count.
|
|
1881
|
-
*
|
|
1882
|
-
* If the subscriber client cannot be created (e.g. Redis temporarily unavailable),
|
|
1883
|
-
* the handler registration is rolled back and the cached init promise is cleared so
|
|
1884
|
-
* the next call retries from scratch.
|
|
1885
|
-
*/
|
|
1886
1489
|
async subscribe(handler) {
|
|
1887
1490
|
this.handlers.add(handler);
|
|
1888
1491
|
let sub;
|
|
@@ -1908,14 +1511,13 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1908
1511
|
}
|
|
1909
1512
|
};
|
|
1910
1513
|
}
|
|
1911
|
-
/** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
|
|
1912
1514
|
ensureSubscriber() {
|
|
1913
1515
|
if (!this.#subInit) this.#subInit = this.createSubscriber();
|
|
1914
1516
|
return this.#subInit;
|
|
1915
1517
|
}
|
|
1916
1518
|
async createSubscriber() {
|
|
1917
1519
|
this.#outageLogged = false;
|
|
1918
|
-
const sub = this.#pub.duplicate({ autoResubscribe: false });
|
|
1520
|
+
const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
|
|
1919
1521
|
let attached = false;
|
|
1920
1522
|
sub.on("message", (_ch, payload) => this.dispatch(payload));
|
|
1921
1523
|
const unreachableFirst = new Promise((resolve) => {
|
|
@@ -1930,10 +1532,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1930
1532
|
sub.on("ready", () => {
|
|
1931
1533
|
if (attached) this.confirm(sub);
|
|
1932
1534
|
});
|
|
1933
|
-
|
|
1535
|
+
await this.negotiate(sub, sub.subscribe(this.channel), unreachableFirst);
|
|
1536
|
+
attached = true;
|
|
1537
|
+
return sub;
|
|
1538
|
+
}
|
|
1539
|
+
async negotiate(sub, first, unreachableFirst) {
|
|
1934
1540
|
try {
|
|
1935
1541
|
const outcome = await Promise.race([
|
|
1936
|
-
first.then(
|
|
1542
|
+
first.then(
|
|
1543
|
+
() => "subscribed",
|
|
1544
|
+
(err) => {
|
|
1545
|
+
if (err.name === "ReplyError") throw err;
|
|
1546
|
+
return { unreachable: err };
|
|
1547
|
+
}
|
|
1548
|
+
),
|
|
1937
1549
|
unreachableFirst
|
|
1938
1550
|
]);
|
|
1939
1551
|
if (outcome === "subscribed") {
|
|
@@ -1952,8 +1564,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1952
1564
|
err
|
|
1953
1565
|
);
|
|
1954
1566
|
}
|
|
1955
|
-
attached = true;
|
|
1956
|
-
return sub;
|
|
1957
1567
|
}
|
|
1958
1568
|
confirm(sub) {
|
|
1959
1569
|
sub.subscribe(this.channel).then(
|
|
@@ -1961,7 +1571,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1961
1571
|
(err) => this.refused(err)
|
|
1962
1572
|
);
|
|
1963
1573
|
}
|
|
1964
|
-
/** A server that was reached and refused the SUBSCRIBE after boot: it stays unsubscribed. */
|
|
1965
1574
|
refused(err) {
|
|
1966
1575
|
if (err?.name !== "ReplyError") return;
|
|
1967
1576
|
this.#subscribed = false;
|
|
@@ -1985,10 +1594,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1985
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`
|
|
1986
1595
|
);
|
|
1987
1596
|
}
|
|
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
1597
|
reportMalformed() {
|
|
1993
1598
|
this.malformedDropped++;
|
|
1994
1599
|
const now = Date.now();
|
|
@@ -2018,21 +1623,10 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2018
1623
|
|
|
2019
1624
|
// src/server/offline-queue/redis-offline-queue.ts
|
|
2020
1625
|
var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
2021
|
-
/**
|
|
2022
|
-
* The Redis client.
|
|
2023
|
-
*
|
|
2024
|
-
* An ECMAScript private field rather than a TypeScript `private` one, which
|
|
2025
|
-
* is erased at runtime: an ioredis instance carries `options.password` as a
|
|
2026
|
-
* plain field, so leaving this enumerable would let anything that serializes
|
|
2027
|
-
* this queue — or the module options that reference it — reach the Redis
|
|
2028
|
-
* credentials.
|
|
2029
|
-
*/
|
|
2030
1626
|
#client;
|
|
2031
1627
|
maxPerUser;
|
|
2032
1628
|
ttlSeconds;
|
|
2033
|
-
/** Zero-pad width for the epoch-millisecond component of the sort key. */
|
|
2034
1629
|
static MS_PAD = 16;
|
|
2035
|
-
/** Zero-pad width for the intra-millisecond counter component of the sort key. */
|
|
2036
1630
|
static COUNTER_PAD = 6;
|
|
2037
1631
|
constructor(options) {
|
|
2038
1632
|
this.#client = options.client;
|
|
@@ -2042,23 +1636,12 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2042
1636
|
key(userId) {
|
|
2043
1637
|
return `bymax:oq:${userId}`;
|
|
2044
1638
|
}
|
|
2045
|
-
/**
|
|
2046
|
-
* Build the fixed-width lexicographic sort key for an event id.
|
|
2047
|
-
*
|
|
2048
|
-
* Handles two id formats:
|
|
2049
|
-
* - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
|
|
2050
|
-
* - Legacy plain numeric strings: `1700000000000`
|
|
2051
|
-
*/
|
|
2052
1639
|
lexKey(id) {
|
|
2053
1640
|
const dashIdx = id.indexOf("-");
|
|
2054
1641
|
const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
|
|
2055
1642
|
const counter = dashIdx === -1 ? 0 : Number(id.slice(dashIdx + 1));
|
|
2056
1643
|
return String(ms).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(counter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
|
|
2057
1644
|
}
|
|
2058
|
-
/**
|
|
2059
|
-
* Return the lexicographically next sort key after `id`, used as an
|
|
2060
|
-
* inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
|
|
2061
|
-
*/
|
|
2062
1645
|
lexKeyNext(id) {
|
|
2063
1646
|
const dashIdx = id.indexOf("-");
|
|
2064
1647
|
const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
|
|
@@ -2068,7 +1651,6 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2068
1651
|
const nextCounter = counter < counterMax ? counter + 1 : 0;
|
|
2069
1652
|
return String(nextMs).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(nextCounter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
|
|
2070
1653
|
}
|
|
2071
|
-
/** Encode an event into a lexicographically sortable ZSET member string. */
|
|
2072
1654
|
encodeMember(event) {
|
|
2073
1655
|
return `${this.lexKey(event.id)}|${JSON.stringify(event)}`;
|
|
2074
1656
|
}
|