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