@bymax-one/nest-realtime 1.2.7 → 1.2.9
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 +150 -1
- package/README.md +5 -3
- package/dist/internal/index.cjs +194 -499
- package/dist/internal/index.d.cts +83 -6
- package/dist/internal/index.d.ts +83 -6
- package/dist/internal/index.mjs +195 -501
- 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 +17 -288
- package/dist/websocket/index.d.cts +6 -3
- package/dist/websocket/index.d.ts +6 -3
- package/dist/websocket/index.mjs +18 -289
- package/package.json +5 -4
package/dist/internal/index.cjs
CHANGED
|
@@ -8,6 +8,9 @@ var net = require('net');
|
|
|
8
8
|
|
|
9
9
|
var __defProp = Object.defineProperty;
|
|
10
10
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
11
|
+
var __typeError = (msg) => {
|
|
12
|
+
throw TypeError(msg);
|
|
13
|
+
};
|
|
11
14
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
12
15
|
var __decorateClass = (decorators, target, key, kind) => {
|
|
13
16
|
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
@@ -18,7 +21,11 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
18
21
|
return result;
|
|
19
22
|
};
|
|
20
23
|
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
21
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
|
|
24
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
25
|
+
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
|
|
26
|
+
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
27
|
+
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
28
|
+
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
22
29
|
|
|
23
30
|
// src/shared/constants/error-codes.constants.ts
|
|
24
31
|
var REALTIME_ERROR_CODES = {
|
|
@@ -49,21 +56,50 @@ function applyDefaults(options) {
|
|
|
49
56
|
sse: { ...DEFAULT_SSE, ...options.sse ?? {} }
|
|
50
57
|
});
|
|
51
58
|
}
|
|
59
|
+
|
|
60
|
+
// src/server/constants/injection-tokens.constants.ts
|
|
61
|
+
var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
|
|
62
|
+
var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
|
|
63
|
+
var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
|
|
64
|
+
var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
|
|
65
|
+
var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
|
|
66
|
+
var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
|
|
67
|
+
var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
|
|
68
|
+
var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
|
|
69
|
+
var DEFAULT_HEARTBEAT_MS = 3e4;
|
|
70
|
+
var HEARTBEAT_MIN_MS = 5e3;
|
|
71
|
+
var HEARTBEAT_MAX_MS = 9e4;
|
|
72
|
+
|
|
73
|
+
// src/server/utils/realtime-error.ts
|
|
74
|
+
function realtimeError(code, detail, options = {}) {
|
|
75
|
+
const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
|
|
76
|
+
const message = `${lead}: ${detail}`;
|
|
77
|
+
const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
|
|
78
|
+
return Object.assign(error, { code });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/server/config/validate-options.ts
|
|
52
82
|
var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
|
|
53
83
|
function validateOptions(options) {
|
|
54
84
|
if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
|
|
55
|
-
throw
|
|
56
|
-
|
|
85
|
+
throw realtimeError(
|
|
86
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
87
|
+
`options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`,
|
|
88
|
+
{ who: "BymaxRealtimeModule" }
|
|
57
89
|
);
|
|
58
90
|
}
|
|
59
91
|
if (!options.authenticator) {
|
|
60
|
-
throw
|
|
61
|
-
|
|
92
|
+
throw realtimeError(
|
|
93
|
+
REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
|
|
94
|
+
`options.authenticator is required \u2014 the library never ships a default authenticator`,
|
|
95
|
+
{ who: "BymaxRealtimeModule" }
|
|
62
96
|
);
|
|
63
97
|
}
|
|
64
98
|
if (typeof options.authenticator.authenticate !== "function") {
|
|
65
|
-
throw
|
|
66
|
-
|
|
99
|
+
throw realtimeError(
|
|
100
|
+
REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
|
|
101
|
+
`options.authenticator must implement IConnectionAuthenticator.authenticate(context)`,
|
|
102
|
+
{ who: "BymaxRealtimeModule" }
|
|
67
103
|
);
|
|
68
104
|
}
|
|
69
105
|
validateSseOptions(options);
|
|
@@ -80,34 +116,30 @@ function validateReauthPolicy(options) {
|
|
|
80
116
|
}
|
|
81
117
|
function validateSseOptions(options) {
|
|
82
118
|
const sse = options.sse;
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
119
|
+
const heartbeatMs = sse?.heartbeatMs;
|
|
120
|
+
if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
|
|
121
|
+
throw realtimeError(
|
|
122
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
123
|
+
`options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`,
|
|
124
|
+
{ who: "BymaxRealtimeModule" }
|
|
86
125
|
);
|
|
87
126
|
}
|
|
88
127
|
if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
|
|
89
|
-
throw
|
|
90
|
-
|
|
128
|
+
throw realtimeError(
|
|
129
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
130
|
+
`options.sse.replayBufferSize must be >= 0`,
|
|
131
|
+
{ who: "BymaxRealtimeModule" }
|
|
91
132
|
);
|
|
92
133
|
}
|
|
93
134
|
if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
|
|
94
|
-
throw
|
|
95
|
-
|
|
135
|
+
throw realtimeError(
|
|
136
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
137
|
+
`options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
|
|
138
|
+
{ who: "BymaxRealtimeModule" }
|
|
96
139
|
);
|
|
97
140
|
}
|
|
98
141
|
}
|
|
99
142
|
|
|
100
|
-
// src/server/constants/injection-tokens.constants.ts
|
|
101
|
-
var REALTIME_OPTIONS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OPTIONS");
|
|
102
|
-
var REALTIME_TRANSPORT_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_TRANSPORT");
|
|
103
|
-
var REALTIME_AUTHENTICATOR_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_AUTHENTICATOR");
|
|
104
|
-
var REALTIME_PUBSUB_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PUBSUB");
|
|
105
|
-
var REALTIME_OFFLINE_QUEUE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_OFFLINE_QUEUE");
|
|
106
|
-
var REALTIME_PRESENCE_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_PRESENCE");
|
|
107
|
-
var REALTIME_HOOKS_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_HOOKS");
|
|
108
|
-
var REALTIME_INSTANCE_ID_TOKEN = /* @__PURE__ */ Symbol("BYMAX_REALTIME_INSTANCE_ID");
|
|
109
|
-
var DEFAULT_HEARTBEAT_MS = 3e4;
|
|
110
|
-
|
|
111
143
|
// src/server/utils/describe-error.ts
|
|
112
144
|
function describeError(reason) {
|
|
113
145
|
try {
|
|
@@ -140,19 +172,6 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
|
|
|
140
172
|
storage;
|
|
141
173
|
hooks;
|
|
142
174
|
logger = new common.Logger(exports.OfflineQueueDeliveryService.name);
|
|
143
|
-
/**
|
|
144
|
-
* Return events for `userId` that arrived after `lastEventId` and are NOT
|
|
145
|
-
* already covered by `ringBufferIds` (already replayed from in-memory buffer).
|
|
146
|
-
*
|
|
147
|
-
* Retrieval does NOT acknowledge: the durable queue is pruned only after the events
|
|
148
|
-
* have been emitted to a live subscriber via {@link acknowledge}. This guarantees
|
|
149
|
-
* at-least-once delivery — events that never reach the client are never lost.
|
|
150
|
-
*
|
|
151
|
-
* @param userId - The reconnecting user.
|
|
152
|
-
* @param lastEventId - The `Last-Event-ID` header value.
|
|
153
|
-
* @param ringBufferIds - Set of event ids already replayed from the ring buffer.
|
|
154
|
-
* @returns Gap events, or an empty array when no offline queue is configured.
|
|
155
|
-
*/
|
|
156
175
|
async retrieve(userId, lastEventId, ringBufferIds) {
|
|
157
176
|
if (!this.storage) return [];
|
|
158
177
|
let events;
|
|
@@ -178,17 +197,6 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
|
|
|
178
197
|
}
|
|
179
198
|
return events.filter((e) => !ringBufferIds.has(e.id));
|
|
180
199
|
}
|
|
181
|
-
/**
|
|
182
|
-
* Acknowledge delivered offline events so the storage backend can prune them.
|
|
183
|
-
*
|
|
184
|
-
* At-least-once contract: call this ONLY after the events have been emitted to a
|
|
185
|
-
* still-open subscriber. Acknowledging before emission would permanently drop events
|
|
186
|
-
* that never reached the client. A failure is swallowed (logged) so a transient
|
|
187
|
-
* storage error never disrupts delivery; the events simply redeliver on reconnect.
|
|
188
|
-
*
|
|
189
|
-
* @param userId - The user whose queue is acknowledged.
|
|
190
|
-
* @param events - The delivered gap events; the last id is the prune watermark.
|
|
191
|
-
*/
|
|
192
200
|
async acknowledge(userId, events) {
|
|
193
201
|
if (!this.storage || events.length === 0) return;
|
|
194
202
|
const lastId = events[events.length - 1].id;
|
|
@@ -231,13 +239,15 @@ function resolveAuthTenant(options, auth) {
|
|
|
231
239
|
}
|
|
232
240
|
function assertIdentityIsNotBlank(auth) {
|
|
233
241
|
if (isBlank(auth.userId)) {
|
|
234
|
-
throw
|
|
235
|
-
|
|
242
|
+
throw realtimeError(
|
|
243
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
244
|
+
`the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
|
|
236
245
|
);
|
|
237
246
|
}
|
|
238
247
|
if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
|
|
239
|
-
throw
|
|
240
|
-
|
|
248
|
+
throw realtimeError(
|
|
249
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
250
|
+
`the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
|
|
241
251
|
);
|
|
242
252
|
}
|
|
243
253
|
}
|
|
@@ -278,11 +288,6 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
278
288
|
byId = /* @__PURE__ */ new Map();
|
|
279
289
|
byUserId = /* @__PURE__ */ new Map();
|
|
280
290
|
byTenantId = /* @__PURE__ */ new Map();
|
|
281
|
-
/**
|
|
282
|
-
* Register a connection and index it by user and tenant.
|
|
283
|
-
*
|
|
284
|
-
* @internal Transport bookkeeping: applications must not call it.
|
|
285
|
-
*/
|
|
286
291
|
register(record) {
|
|
287
292
|
this.byId.set(record.connectionId, record);
|
|
288
293
|
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
@@ -290,11 +295,6 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
290
295
|
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
291
296
|
}
|
|
292
297
|
}
|
|
293
|
-
/**
|
|
294
|
-
* Remove a connection from every index. Returns the removed record, if any.
|
|
295
|
-
*
|
|
296
|
-
* @internal Transport bookkeeping: applications must not call it.
|
|
297
|
-
*/
|
|
298
298
|
unregister(connectionId) {
|
|
299
299
|
const record = this.byId.get(connectionId);
|
|
300
300
|
if (!record) return void 0;
|
|
@@ -305,27 +305,21 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
305
305
|
}
|
|
306
306
|
return record;
|
|
307
307
|
}
|
|
308
|
-
/** Look up a single connection by id. */
|
|
309
308
|
get(connectionId) {
|
|
310
309
|
return this.byId.get(connectionId);
|
|
311
310
|
}
|
|
312
|
-
/** All connections of a user, optionally filtered by transport. */
|
|
313
311
|
byUser(userId, transport) {
|
|
314
312
|
return this.resolve(this.byUserId.get(userId), transport);
|
|
315
313
|
}
|
|
316
|
-
/** All connections of a tenant, optionally filtered by transport. */
|
|
317
314
|
byTenant(tenantId, transport) {
|
|
318
315
|
return this.resolve(this.byTenantId.get(tenantId), transport);
|
|
319
316
|
}
|
|
320
|
-
/** All connections of a given transport. */
|
|
321
317
|
allByTransport(transport) {
|
|
322
318
|
return Array.from(this.byId.values()).filter((record) => record.transport === transport);
|
|
323
319
|
}
|
|
324
|
-
/** Total number of active connections. */
|
|
325
320
|
count() {
|
|
326
321
|
return this.byId.size;
|
|
327
322
|
}
|
|
328
|
-
/** Number of distinct users currently connected. */
|
|
329
323
|
countUsers() {
|
|
330
324
|
return this.byUserId.size;
|
|
331
325
|
}
|
|
@@ -359,7 +353,6 @@ var COUNTER_WIDTH = 6;
|
|
|
359
353
|
exports.EventIdGenerator = class EventIdGenerator {
|
|
360
354
|
lastMs = 0;
|
|
361
355
|
counter = 0;
|
|
362
|
-
/** Produce the next monotonic event id. */
|
|
363
356
|
next() {
|
|
364
357
|
const now = Date.now();
|
|
365
358
|
if (now === this.lastMs) {
|
|
@@ -377,7 +370,6 @@ exports.EventIdGenerator = __decorateClass([
|
|
|
377
370
|
exports.RoomRegistry = class RoomRegistry {
|
|
378
371
|
rooms = /* @__PURE__ */ new Map();
|
|
379
372
|
connectionRooms = /* @__PURE__ */ new Map();
|
|
380
|
-
/** Join a connection to a room (idempotent). */
|
|
381
373
|
join(connectionId, roomId) {
|
|
382
374
|
const room = this.rooms.get(roomId) ?? /* @__PURE__ */ new Set();
|
|
383
375
|
room.add(connectionId);
|
|
@@ -386,7 +378,6 @@ exports.RoomRegistry = class RoomRegistry {
|
|
|
386
378
|
conn.add(roomId);
|
|
387
379
|
this.connectionRooms.set(connectionId, conn);
|
|
388
380
|
}
|
|
389
|
-
/** Remove a connection from a room (idempotent); prunes empty entries. */
|
|
390
381
|
leave(connectionId, roomId) {
|
|
391
382
|
const room = this.rooms.get(roomId);
|
|
392
383
|
if (room) {
|
|
@@ -399,17 +390,14 @@ exports.RoomRegistry = class RoomRegistry {
|
|
|
399
390
|
if (conn.size === 0) this.connectionRooms.delete(connectionId);
|
|
400
391
|
}
|
|
401
392
|
}
|
|
402
|
-
/** Snapshot of a room's members — safe to iterate while membership mutates. */
|
|
403
393
|
members(roomId) {
|
|
404
394
|
const set = this.rooms.get(roomId);
|
|
405
395
|
return set ? Array.from(set) : [];
|
|
406
396
|
}
|
|
407
|
-
/** Snapshot of the rooms a connection currently belongs to. */
|
|
408
397
|
roomsOf(connectionId) {
|
|
409
398
|
const set = this.connectionRooms.get(connectionId);
|
|
410
399
|
return set ? Array.from(set) : [];
|
|
411
400
|
}
|
|
412
|
-
/** Remove a connection from every room (called on disconnect). */
|
|
413
401
|
leaveAll(connectionId) {
|
|
414
402
|
const rooms = this.connectionRooms.get(connectionId);
|
|
415
403
|
if (!rooms) return;
|
|
@@ -422,7 +410,6 @@ exports.RoomRegistry = class RoomRegistry {
|
|
|
422
410
|
}
|
|
423
411
|
this.connectionRooms.delete(connectionId);
|
|
424
412
|
}
|
|
425
|
-
/** Total number of distinct rooms. */
|
|
426
413
|
countRooms() {
|
|
427
414
|
return this.rooms.size;
|
|
428
415
|
}
|
|
@@ -445,18 +432,10 @@ function composeRoomId(prefix, ...parts) {
|
|
|
445
432
|
|
|
446
433
|
// src/server/utils/unavailable-error.ts
|
|
447
434
|
function unavailableError(code, who, what, cause) {
|
|
448
|
-
return
|
|
435
|
+
return realtimeError(code, `${what} (${describeError(cause)})`, { who, cause });
|
|
449
436
|
}
|
|
450
437
|
exports.InMemoryPubSub = class InMemoryPubSub {
|
|
451
438
|
handlers = /* @__PURE__ */ new Set();
|
|
452
|
-
/**
|
|
453
|
-
* Publish a message to all subscribed handlers.
|
|
454
|
-
*
|
|
455
|
-
* Delivery is deferred one microtask so a handler that enqueues further publishes
|
|
456
|
-
* does not deepen the current call stack. One handler's failure does not block others.
|
|
457
|
-
*
|
|
458
|
-
* @param message - The pub/sub message to fan out.
|
|
459
|
-
*/
|
|
460
439
|
async publish(message) {
|
|
461
440
|
await Promise.resolve();
|
|
462
441
|
for (const handler of this.handlers) {
|
|
@@ -466,12 +445,6 @@ exports.InMemoryPubSub = class InMemoryPubSub {
|
|
|
466
445
|
}
|
|
467
446
|
}
|
|
468
447
|
}
|
|
469
|
-
/**
|
|
470
|
-
* Subscribe to pub/sub messages.
|
|
471
|
-
*
|
|
472
|
-
* @param handler - Called for every published message.
|
|
473
|
-
* @returns An async unsubscribe function that removes this handler.
|
|
474
|
-
*/
|
|
475
448
|
async subscribe(handler) {
|
|
476
449
|
this.handlers.add(handler);
|
|
477
450
|
return async () => {
|
|
@@ -489,7 +462,6 @@ exports.EventReplayBuffer = class EventReplayBuffer {
|
|
|
489
462
|
}
|
|
490
463
|
opts;
|
|
491
464
|
buffers = /* @__PURE__ */ new Map();
|
|
492
|
-
/** Append an event to a user's ring buffer, evicting the oldest beyond the cap. */
|
|
493
465
|
append(userId, event) {
|
|
494
466
|
const buf = this.buffers.get(userId) ?? [];
|
|
495
467
|
buf.push(event);
|
|
@@ -497,12 +469,6 @@ exports.EventReplayBuffer = class EventReplayBuffer {
|
|
|
497
469
|
if (buf.length > cap) buf.shift();
|
|
498
470
|
this.buffers.set(userId, buf);
|
|
499
471
|
}
|
|
500
|
-
/**
|
|
501
|
-
* Return the events emitted after `lastEventId`.
|
|
502
|
-
*
|
|
503
|
-
* Returns an empty array when the user has no buffer, or when `lastEventId` is
|
|
504
|
-
* not present (a gap — the caller should fall back to `IOfflineQueueStorage`).
|
|
505
|
-
*/
|
|
506
472
|
since(userId, lastEventId) {
|
|
507
473
|
const buf = this.buffers.get(userId);
|
|
508
474
|
if (!buf) return [];
|
|
@@ -510,7 +476,6 @@ exports.EventReplayBuffer = class EventReplayBuffer {
|
|
|
510
476
|
if (idx === -1) return [];
|
|
511
477
|
return buf.slice(idx + 1);
|
|
512
478
|
}
|
|
513
|
-
/** Number of events currently buffered for a user (diagnostics). */
|
|
514
479
|
size(userId) {
|
|
515
480
|
return this.buffers.get(userId)?.length ?? 0;
|
|
516
481
|
}
|
|
@@ -520,23 +485,13 @@ exports.EventReplayBuffer = __decorateClass([
|
|
|
520
485
|
__decorateParam(0, common.Inject(REALTIME_OPTIONS_TOKEN))
|
|
521
486
|
], exports.EventReplayBuffer);
|
|
522
487
|
var KEEPALIVE_COMMENT = ": keepalive\n\n";
|
|
523
|
-
var HEARTBEAT_MIN_MS = 5e3;
|
|
524
|
-
var HEARTBEAT_MAX_MS = 9e4;
|
|
525
488
|
exports.HeartbeatService = class HeartbeatService {
|
|
526
489
|
timers = /* @__PURE__ */ new Map();
|
|
527
|
-
/**
|
|
528
|
-
* Start writing keepalives for a connection every `intervalMs`.
|
|
529
|
-
*
|
|
530
|
-
* @param connectionId - Unique connection identifier used to track the timer.
|
|
531
|
-
* @param res - The writable response stream (or any object with a `write` method).
|
|
532
|
-
* @param intervalMs - Keepalive interval in milliseconds; must be within
|
|
533
|
-
* `[5_000, 90_000]`.
|
|
534
|
-
* @throws {Error} When `intervalMs` is outside the valid range.
|
|
535
|
-
*/
|
|
536
490
|
start(connectionId, res, intervalMs) {
|
|
537
491
|
if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
|
|
538
|
-
throw
|
|
539
|
-
|
|
492
|
+
throw realtimeError(
|
|
493
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
494
|
+
`heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
|
|
540
495
|
);
|
|
541
496
|
}
|
|
542
497
|
this.stop(connectionId);
|
|
@@ -550,7 +505,6 @@ exports.HeartbeatService = class HeartbeatService {
|
|
|
550
505
|
timer.unref();
|
|
551
506
|
this.timers.set(connectionId, timer);
|
|
552
507
|
}
|
|
553
|
-
/** Stop and clear the keepalive timer for a connection (idempotent). */
|
|
554
508
|
stop(connectionId) {
|
|
555
509
|
const timer = this.timers.get(connectionId);
|
|
556
510
|
if (timer) {
|
|
@@ -558,7 +512,6 @@ exports.HeartbeatService = class HeartbeatService {
|
|
|
558
512
|
this.timers.delete(connectionId);
|
|
559
513
|
}
|
|
560
514
|
}
|
|
561
|
-
/** Stop every keepalive timer (used on shutdown). */
|
|
562
515
|
stopAll() {
|
|
563
516
|
for (const timer of this.timers.values()) clearInterval(timer);
|
|
564
517
|
this.timers.clear();
|
|
@@ -569,6 +522,7 @@ exports.HeartbeatService = __decorateClass([
|
|
|
569
522
|
], exports.HeartbeatService);
|
|
570
523
|
|
|
571
524
|
// src/server/transports/sse/sse.transport.ts
|
|
525
|
+
var _shuttingDown;
|
|
572
526
|
exports.SseTransport = class SseTransport {
|
|
573
527
|
constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
|
|
574
528
|
this.connections = connections;
|
|
@@ -582,6 +536,9 @@ exports.SseTransport = class SseTransport {
|
|
|
582
536
|
this.options = options;
|
|
583
537
|
this.instanceId = instanceId;
|
|
584
538
|
this.offlineQueue = offlineQueue;
|
|
539
|
+
__publicField(this, "kind", "sse");
|
|
540
|
+
__publicField(this, "logger", new common.Logger(exports.SseTransport.name));
|
|
541
|
+
__privateAdd(this, _shuttingDown, false);
|
|
585
542
|
}
|
|
586
543
|
connections;
|
|
587
544
|
rooms;
|
|
@@ -594,34 +551,28 @@ exports.SseTransport = class SseTransport {
|
|
|
594
551
|
options;
|
|
595
552
|
instanceId;
|
|
596
553
|
offlineQueue;
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
/** Tear down every SSE connection and stop heartbeat on process shutdown. */
|
|
600
|
-
async onApplicationShutdown() {
|
|
554
|
+
async beforeApplicationShutdown() {
|
|
555
|
+
__privateSet(this, _shuttingDown, true);
|
|
601
556
|
this.heartbeat.stopAll();
|
|
602
557
|
for (const conn of this.connections.allByTransport("sse")) {
|
|
603
558
|
await this.disconnectLocal(conn.connectionId);
|
|
604
559
|
}
|
|
605
560
|
}
|
|
606
|
-
|
|
561
|
+
async onApplicationShutdown() {
|
|
562
|
+
await this.beforeApplicationShutdown();
|
|
563
|
+
}
|
|
564
|
+
get shuttingDown() {
|
|
565
|
+
return __privateGet(this, _shuttingDown);
|
|
566
|
+
}
|
|
607
567
|
get heartbeatMs() {
|
|
608
568
|
return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
609
569
|
}
|
|
610
|
-
/** Whether the `connection:established` event should be emitted on connect. */
|
|
611
570
|
get emitConnectionEvent() {
|
|
612
571
|
return this.options.sse?.emitConnectionEvent !== false;
|
|
613
572
|
}
|
|
614
|
-
/** Authenticate a connection through the consumer-provided authenticator. */
|
|
615
573
|
authenticate(context) {
|
|
616
574
|
return this.auth.authenticate(context);
|
|
617
575
|
}
|
|
618
|
-
/**
|
|
619
|
-
* Register an authenticated SSE connection and auto-join its user/tenant rooms.
|
|
620
|
-
*
|
|
621
|
-
* Fires FIFO eviction if the user exceeds `maxConnectionsPerUser`. The `onConnect`
|
|
622
|
-
* lifecycle hook is fired by the subscription handler after this returns, so that the
|
|
623
|
-
* handler can carry a consistent connection record reference.
|
|
624
|
-
*/
|
|
625
576
|
async registerConnection(params) {
|
|
626
577
|
const record = {
|
|
627
578
|
connectionId: params.connectionId,
|
|
@@ -647,7 +598,6 @@ exports.SseTransport = class SseTransport {
|
|
|
647
598
|
}
|
|
648
599
|
await this.evictBeyondLimit(params.auth.userId);
|
|
649
600
|
}
|
|
650
|
-
/** Idempotent cleanup for a connection — runs the disconnect hook exactly once. */
|
|
651
601
|
async unregisterConnection(connectionId, reason) {
|
|
652
602
|
const record = this.connections.unregister(connectionId);
|
|
653
603
|
if (!record) return;
|
|
@@ -671,39 +621,15 @@ exports.SseTransport = class SseTransport {
|
|
|
671
621
|
this.logger.error(`onDisconnect hook failed: ${describeError(error)}`);
|
|
672
622
|
}
|
|
673
623
|
}
|
|
674
|
-
/** Replay the events a user missed after `lastEventId`. */
|
|
675
624
|
getReplayEvents(userId, lastEventId) {
|
|
676
625
|
return this.replayBuffer.since(userId, lastEventId);
|
|
677
626
|
}
|
|
678
|
-
/**
|
|
679
|
-
* All SSE connections for a user — public accessor so external callers can
|
|
680
|
-
* inspect or iterate without reaching into a private registry field.
|
|
681
|
-
*
|
|
682
|
-
* @param userId - The user whose active connections are returned.
|
|
683
|
-
* @returns A snapshot of the user's current SSE `ConnectionRecord` list.
|
|
684
|
-
*/
|
|
685
627
|
connectionsForUser(userId) {
|
|
686
628
|
return this.connections.byUser(userId, "sse");
|
|
687
629
|
}
|
|
688
|
-
/**
|
|
689
|
-
* Look up a single connection by id.
|
|
690
|
-
*
|
|
691
|
-
* @param connectionId - The unique connection identifier.
|
|
692
|
-
* @returns The `ConnectionRecord`, or `undefined` when not found.
|
|
693
|
-
*/
|
|
694
630
|
getConnection(connectionId) {
|
|
695
631
|
return this.connections.get(connectionId);
|
|
696
632
|
}
|
|
697
|
-
/**
|
|
698
|
-
* Emit to a user: live here, to the other instances over the bus, and into the offline queue
|
|
699
|
-
* when the user has no live connection on this instance.
|
|
700
|
-
*
|
|
701
|
-
* A failed publish or a failed append is reported (log and `onDeliveryFailure`) and the call
|
|
702
|
-
* still resolves, since delivery to the other instances is at-most-once. It rejects only when
|
|
703
|
-
* the event has no delivery path left: the user is offline here, the queue could not keep it,
|
|
704
|
-
* and the bus either failed or cannot reach another instance (the in-memory bus). A rejection
|
|
705
|
-
* carries the queue failure as its cause and is not also reported to the hook.
|
|
706
|
-
*/
|
|
707
633
|
async emitToUser(userId, event, data) {
|
|
708
634
|
const id = this.idGen.next();
|
|
709
635
|
this.emitToUserLocal(userId, event, data, id);
|
|
@@ -735,7 +661,6 @@ exports.SseTransport = class SseTransport {
|
|
|
735
661
|
);
|
|
736
662
|
}
|
|
737
663
|
}
|
|
738
|
-
/** Append to the offline queue; resolves with the failure, or `undefined` once it is kept. */
|
|
739
664
|
async tryAppend(queue, userId, event) {
|
|
740
665
|
try {
|
|
741
666
|
await queue.append(userId, event);
|
|
@@ -744,7 +669,6 @@ exports.SseTransport = class SseTransport {
|
|
|
744
669
|
return { error };
|
|
745
670
|
}
|
|
746
671
|
}
|
|
747
|
-
/** Whether the bus can carry an event to another instance (the in-memory bus cannot). */
|
|
748
672
|
busReachesOtherInstances() {
|
|
749
673
|
return !(this.pubsub instanceof exports.InMemoryPubSub);
|
|
750
674
|
}
|
|
@@ -763,24 +687,14 @@ exports.SseTransport = class SseTransport {
|
|
|
763
687
|
this.broadcastLocal(event, data, id);
|
|
764
688
|
await this.publish({ op: "broadcast", args: { event, data, id } });
|
|
765
689
|
}
|
|
766
|
-
/** Join a connection this instance holds to a room; any other id is left alone. */
|
|
767
690
|
async joinRoom(connectionId, roomId) {
|
|
768
691
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
769
692
|
this.rooms.join(connectionId, roomId);
|
|
770
693
|
}
|
|
771
|
-
/** Remove a connection this instance holds from a room; any other id is left alone. */
|
|
772
694
|
async leaveRoom(connectionId, roomId) {
|
|
773
695
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
774
696
|
this.rooms.leave(connectionId, roomId);
|
|
775
697
|
}
|
|
776
|
-
/**
|
|
777
|
-
* Disconnect a connection locally if owned here, otherwise revoke cross-instance.
|
|
778
|
-
*
|
|
779
|
-
* Resolves once the connection is closed here or the revocation has been handed to the bus. A
|
|
780
|
-
* connection held here as a WebSocket is left to the WebSocket transport and nothing is
|
|
781
|
-
* published. It rejects with `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses it: nothing has reached
|
|
782
|
-
* the connection, so the caller must not read the resolution as a revocation.
|
|
783
|
-
*/
|
|
784
698
|
async disconnect(connectionId, reason) {
|
|
785
699
|
const record = this.connections.get(connectionId);
|
|
786
700
|
if (record) {
|
|
@@ -802,37 +716,15 @@ exports.SseTransport = class SseTransport {
|
|
|
802
716
|
);
|
|
803
717
|
}
|
|
804
718
|
}
|
|
805
|
-
/**
|
|
806
|
-
* Deliver an event to a user's local SSE connections and update the replay buffer.
|
|
807
|
-
*
|
|
808
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
809
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
810
|
-
*/
|
|
811
719
|
emitToUserLocal(userId, event, data, id) {
|
|
812
720
|
const message = this.buildMessage(id, event, data);
|
|
813
721
|
this.replayBuffer.append(userId, message);
|
|
814
722
|
for (const conn of this.connections.byUser(userId, "sse")) this.deliver(conn, message);
|
|
815
723
|
}
|
|
816
|
-
/**
|
|
817
|
-
* Deliver an event to all local SSE connections for a tenant.
|
|
818
|
-
*
|
|
819
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
820
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
821
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
822
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
823
|
-
*/
|
|
824
724
|
emitToTenantLocal(tenantId, event, data, id) {
|
|
825
725
|
const message = this.buildMessage(id, event, data);
|
|
826
726
|
for (const conn of this.connections.byTenant(tenantId, "sse")) this.deliver(conn, message);
|
|
827
727
|
}
|
|
828
|
-
/**
|
|
829
|
-
* Deliver an event to all local SSE connections that joined the given room.
|
|
830
|
-
*
|
|
831
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
832
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
833
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
834
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
835
|
-
*/
|
|
836
728
|
emitToRoomLocal(roomId, event, data, id) {
|
|
837
729
|
const message = this.buildMessage(id, event, data);
|
|
838
730
|
for (const connectionId of this.rooms.members(roomId)) {
|
|
@@ -840,24 +732,10 @@ exports.SseTransport = class SseTransport {
|
|
|
840
732
|
if (conn && conn.transport === "sse") this.deliver(conn, message);
|
|
841
733
|
}
|
|
842
734
|
}
|
|
843
|
-
/**
|
|
844
|
-
* Deliver an event to all local SSE connections.
|
|
845
|
-
*
|
|
846
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
847
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
848
|
-
* @remarks Events sent via tenant/room/broadcast are NOT written to the per-user replay
|
|
849
|
-
* buffer or offline queue — only emitToUser populates per-user replay/offline state.
|
|
850
|
-
*/
|
|
851
735
|
broadcastLocal(event, data, id) {
|
|
852
736
|
const message = this.buildMessage(id, event, data);
|
|
853
737
|
for (const conn of this.connections.allByTransport("sse")) this.deliver(conn, message);
|
|
854
738
|
}
|
|
855
|
-
/**
|
|
856
|
-
* Tear down a locally-owned SSE stream, then clean up (no re-publish).
|
|
857
|
-
*
|
|
858
|
-
* @internal Invoked only by RealtimePubSubSubscriber for remote re-emit; application code
|
|
859
|
-
* must call the public emitToUser/emitToTenant/emitToRoom/broadcast/disconnect to preserve cross-instance delivery.
|
|
860
|
-
*/
|
|
861
739
|
async disconnectLocal(connectionId, reason) {
|
|
862
740
|
const record = this.connections.get(connectionId);
|
|
863
741
|
if (!record || record.transport !== "sse") return;
|
|
@@ -868,7 +746,6 @@ exports.SseTransport = class SseTransport {
|
|
|
868
746
|
buildMessage(id, event, data) {
|
|
869
747
|
return { id, type: event, data };
|
|
870
748
|
}
|
|
871
|
-
/** Deliver to one connection, isolating failures so others still receive the event. */
|
|
872
749
|
deliver(conn, message) {
|
|
873
750
|
try {
|
|
874
751
|
conn.subject?.next(message);
|
|
@@ -876,7 +753,6 @@ exports.SseTransport = class SseTransport {
|
|
|
876
753
|
this.logger.warn(`SSE delivery failed for ${conn.connectionId}: ${describeError(error)}`);
|
|
877
754
|
}
|
|
878
755
|
}
|
|
879
|
-
/** Publish once to the bus; resolves with the failure, or `undefined` once the bus accepted it. */
|
|
880
756
|
async tryPublish(message) {
|
|
881
757
|
try {
|
|
882
758
|
await this.pubsub.publish({ ...message, origin: this.instanceId });
|
|
@@ -885,7 +761,6 @@ exports.SseTransport = class SseTransport {
|
|
|
885
761
|
return { error };
|
|
886
762
|
}
|
|
887
763
|
}
|
|
888
|
-
/** Publish once to the bus. A failure is reported and never fails the live emit path. */
|
|
889
764
|
async publish(message) {
|
|
890
765
|
const failure = await this.tryPublish(message);
|
|
891
766
|
if (failure !== void 0) this.reportPublishFailure(message.op, failure);
|
|
@@ -898,7 +773,6 @@ exports.SseTransport = class SseTransport {
|
|
|
898
773
|
"pubsub.publish failed"
|
|
899
774
|
);
|
|
900
775
|
}
|
|
901
|
-
/** Evict a user's oldest connections (FIFO) when over `maxConnectionsPerUser`. */
|
|
902
776
|
async evictBeyondLimit(userId) {
|
|
903
777
|
const max = this.options.sse?.maxConnectionsPerUser;
|
|
904
778
|
if (max === void 0 || max <= 0) return;
|
|
@@ -910,6 +784,7 @@ exports.SseTransport = class SseTransport {
|
|
|
910
784
|
}
|
|
911
785
|
}
|
|
912
786
|
};
|
|
787
|
+
_shuttingDown = new WeakMap();
|
|
913
788
|
exports.SseTransport = __decorateClass([
|
|
914
789
|
common.Injectable(),
|
|
915
790
|
__decorateParam(0, common.Inject(exports.ConnectionRegistry)),
|
|
@@ -997,29 +872,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
997
872
|
offlineDelivery;
|
|
998
873
|
logger = new common.Logger(exports.SseSubscriptionHandler.name);
|
|
999
874
|
authenticated = /* @__PURE__ */ new WeakMap();
|
|
1000
|
-
/**
|
|
1001
|
-
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
1002
|
-
*
|
|
1003
|
-
* Both transports resolve the routing tenant through this one function, so a
|
|
1004
|
-
* connection carries the same tenant whichever one opened it. The check runs on
|
|
1005
|
-
* the resolved value rather than the raw one — validating what the server does not
|
|
1006
|
-
* use would validate nothing.
|
|
1007
|
-
*
|
|
1008
|
-
* A blank identity is the consumer's configuration rather than the client's
|
|
1009
|
-
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
1010
|
-
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
1011
|
-
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
1012
|
-
* once, not an unhandled crash logging a stack on every reconnect.
|
|
1013
|
-
*
|
|
1014
|
-
* The reason names the operator's fix, so it goes to the server log and the client
|
|
1015
|
-
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
1016
|
-
* without a message.
|
|
1017
|
-
*
|
|
1018
|
-
* @param auth - The result the consumer's authenticator returned.
|
|
1019
|
-
* @returns The same result with the routing tenant resolved.
|
|
1020
|
-
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
1021
|
-
* but blank.
|
|
1022
|
-
*/
|
|
1023
875
|
resolveAndValidateIdentity(auth) {
|
|
1024
876
|
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
1025
877
|
try {
|
|
@@ -1030,30 +882,10 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1030
882
|
}
|
|
1031
883
|
return resolvedAuth;
|
|
1032
884
|
}
|
|
1033
|
-
/**
|
|
1034
|
-
* Handle an incoming SSE connection request end-to-end.
|
|
1035
|
-
*
|
|
1036
|
-
* Sets anti-buffering headers, authenticates the request, captures the offline-gap
|
|
1037
|
-
* before exposing the connection, then returns an Observable whose subscriber callback
|
|
1038
|
-
* wires the downstream listener BEFORE calling `registerConnection` — so a plain
|
|
1039
|
-
* `Subject` suffices and the replay buffer cannot grow unboundedly.
|
|
1040
|
-
*
|
|
1041
|
-
* @param req - The incoming request (SSE GET).
|
|
1042
|
-
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
1043
|
-
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
1044
|
-
* @throws UnauthorizedException when authentication returns null — the client's
|
|
1045
|
-
* credentials were rejected, which is a 401.
|
|
1046
|
-
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
1047
|
-
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
1048
|
-
* a 401: the credentials were accepted and the fault is the consumer's
|
|
1049
|
-
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
1050
|
-
* something that cannot succeed. The exception carries no message, so the client
|
|
1051
|
-
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
1052
|
-
* written to the server log.
|
|
1053
|
-
*/
|
|
1054
885
|
async handle(req, res) {
|
|
1055
886
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
1056
887
|
res.setHeader("X-Accel-Buffering", "no");
|
|
888
|
+
this.refuseDuringShutdown();
|
|
1057
889
|
const done = this.authenticated.get(req);
|
|
1058
890
|
this.authenticated.delete(req);
|
|
1059
891
|
let authenticated;
|
|
@@ -1062,11 +894,19 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1062
894
|
} catch (err) {
|
|
1063
895
|
throw this.toClientError(err, "SSE authentication failed");
|
|
1064
896
|
}
|
|
897
|
+
let stream;
|
|
1065
898
|
try {
|
|
1066
|
-
|
|
899
|
+
stream = await this.openStream(req, res, authenticated);
|
|
1067
900
|
} catch (err) {
|
|
1068
901
|
throw this.serverError(err, "SSE handshake failed");
|
|
1069
902
|
}
|
|
903
|
+
this.refuseDuringShutdown();
|
|
904
|
+
return stream;
|
|
905
|
+
}
|
|
906
|
+
refuseDuringShutdown() {
|
|
907
|
+
if (this.transport.shuttingDown) {
|
|
908
|
+
throw new common.ServiceUnavailableException(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
|
|
909
|
+
}
|
|
1070
910
|
}
|
|
1071
911
|
async openStream(req, res, authenticated) {
|
|
1072
912
|
const { context, auth: resolvedAuth } = authenticated;
|
|
@@ -1092,10 +932,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1092
932
|
queueEvents
|
|
1093
933
|
});
|
|
1094
934
|
}
|
|
1095
|
-
/**
|
|
1096
|
-
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
1097
|
-
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
1098
|
-
*/
|
|
1099
935
|
async authenticateBeforeCommit(req) {
|
|
1100
936
|
try {
|
|
1101
937
|
this.authenticated.set(req, await this.authenticateRequest(req));
|
|
@@ -1103,7 +939,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1103
939
|
throw this.toClientError(err, "SSE authentication failed");
|
|
1104
940
|
}
|
|
1105
941
|
}
|
|
1106
|
-
// Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
|
|
1107
942
|
toClientError(err, what) {
|
|
1108
943
|
return err instanceof common.HttpException ? err : this.serverError(err, what);
|
|
1109
944
|
}
|
|
@@ -1117,17 +952,12 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1117
952
|
if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
1118
953
|
return { context, auth: this.resolveAndValidateIdentity(auth) };
|
|
1119
954
|
}
|
|
1120
|
-
/**
|
|
1121
|
-
* Build the live Observable using a subscribe-before-register pattern.
|
|
1122
|
-
*
|
|
1123
|
-
* The downstream subscriber is wired to the merged pipeline FIRST, so `subject`
|
|
1124
|
-
* already has a listener when `registerConnection` runs. Any `subject.next()` that
|
|
1125
|
-
* occurs during or after registration goes directly to the subscriber — nothing is
|
|
1126
|
-
* buffered or retained, nothing is dropped, and ordering (established → replay →
|
|
1127
|
-
* queue → live) is preserved.
|
|
1128
|
-
*/
|
|
1129
955
|
buildStream(p) {
|
|
1130
956
|
return new rxjs.Observable((subscriber) => {
|
|
957
|
+
if (this.transport.shuttingDown) {
|
|
958
|
+
subscriber.complete();
|
|
959
|
+
return void 0;
|
|
960
|
+
}
|
|
1131
961
|
const inner = this.subscribePipeline(p, subscriber);
|
|
1132
962
|
if (!subscriber.closed && p.queueEvents.length > 0) {
|
|
1133
963
|
void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
|
|
@@ -1136,12 +966,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1136
966
|
return () => inner.unsubscribe();
|
|
1137
967
|
});
|
|
1138
968
|
}
|
|
1139
|
-
/**
|
|
1140
|
-
* Wire the merged pipeline to the downstream subscriber with teardown.
|
|
1141
|
-
*
|
|
1142
|
-
* Subscribing first guarantees `subject` has a listener before registration can emit,
|
|
1143
|
-
* so a plain `Subject` suffices and ordering (established → replay → queue → live) holds.
|
|
1144
|
-
*/
|
|
1145
969
|
subscribePipeline(p, subscriber) {
|
|
1146
970
|
const { connectionId, subject, close$, established$, replay$, queueEvents } = p;
|
|
1147
971
|
const queueReplay$ = queueEvents.length > 0 ? rxjs.of(...queueEvents.map(toMessageEvent)) : rxjs.EMPTY;
|
|
@@ -1159,12 +983,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1159
983
|
})
|
|
1160
984
|
).subscribe(subscriber);
|
|
1161
985
|
}
|
|
1162
|
-
/**
|
|
1163
|
-
* Register the connection (after the subscriber is wired) and activate it on resolution.
|
|
1164
|
-
*
|
|
1165
|
-
* A registration failure routes to `onError` and errors the stream; a failure that
|
|
1166
|
-
* arrives after teardown is a no-op since `subscriber.error` is ignored once closed.
|
|
1167
|
-
*/
|
|
1168
986
|
activateConnection(p, subscriber) {
|
|
1169
987
|
const { connectionId, resolvedAuth, ip, userAgent, subject, close$ } = p;
|
|
1170
988
|
this.transport.registerConnection({ connectionId, auth: resolvedAuth, subject, close$, ip, userAgent }).then(() => this.onRegistered(p, subscriber)).catch((err) => {
|
|
@@ -1174,15 +992,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1174
992
|
subscriber.error(this.serverError(err, "SSE registration failed"));
|
|
1175
993
|
});
|
|
1176
994
|
}
|
|
1177
|
-
/**
|
|
1178
|
-
* Complete the connection handshake once registration resolves.
|
|
1179
|
-
*
|
|
1180
|
-
* Registration is async and can resolve AFTER the downstream subscriber has already
|
|
1181
|
-
* torn down (client disconnected mid-handshake). When that happens `finalize` has
|
|
1182
|
-
* already stopped the heartbeat and unregistered, so re-firing onConnect or starting
|
|
1183
|
-
* a fresh heartbeat would leak the connection and write after close. Guard on
|
|
1184
|
-
* `subscriber.closed`: if closed, undo the late registration idempotently and return.
|
|
1185
|
-
*/
|
|
1186
995
|
onRegistered(p, subscriber) {
|
|
1187
996
|
const { connectionId, res } = p;
|
|
1188
997
|
if (subscriber.closed) {
|
|
@@ -1197,12 +1006,6 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1197
1006
|
const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
1198
1007
|
this.heartbeat.start(connectionId, res, heartbeatMs);
|
|
1199
1008
|
}
|
|
1200
|
-
/**
|
|
1201
|
-
* Invoke a lifecycle hook best-effort — a throwing hook is logged and swallowed
|
|
1202
|
-
* so it never disrupts the connection lifecycle or live event delivery.
|
|
1203
|
-
*
|
|
1204
|
-
* @param invoke - A zero-arg function that calls the hook (handles optionality).
|
|
1205
|
-
*/
|
|
1206
1009
|
fireHook(invoke) {
|
|
1207
1010
|
void Promise.resolve(invoke()).catch((err) => {
|
|
1208
1011
|
this.logger.warn(`Lifecycle hook failed: ${describeError(err)}`);
|
|
@@ -1243,9 +1046,6 @@ function createSseController(endpoint) {
|
|
|
1243
1046
|
__decorateParam(0, common.Inject(exports.SseSubscriptionHandler))
|
|
1244
1047
|
], SseAuthGuard);
|
|
1245
1048
|
let DynamicSseController = class {
|
|
1246
|
-
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
1247
|
-
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
1248
|
-
// be resolved by token rather than by reflected type.
|
|
1249
1049
|
constructor(handler) {
|
|
1250
1050
|
this.handler = handler;
|
|
1251
1051
|
}
|
|
@@ -1273,80 +1073,28 @@ exports.RealtimeService = class RealtimeService {
|
|
|
1273
1073
|
}
|
|
1274
1074
|
transport;
|
|
1275
1075
|
pubsub;
|
|
1276
|
-
/**
|
|
1277
|
-
* Whether this instance hears the events and revocations other instances publish. False while
|
|
1278
|
-
* the bus is unreachable or its subscriber connection is down, so a readiness probe can take a
|
|
1279
|
-
* deaf instance out of rotation. True for a bus that does not report a state, and with
|
|
1280
|
-
* `transport: 'websocket'`, which does not subscribe to the bus.
|
|
1281
|
-
*
|
|
1282
|
-
* @example
|
|
1283
|
-
* ```ts
|
|
1284
|
-
* // In a health indicator: `isHealthy` is false while the instance cannot hear the others.
|
|
1285
|
-
* return indicator.check('realtime', realtime.isPubSubReady())
|
|
1286
|
-
* ```
|
|
1287
|
-
*/
|
|
1288
1076
|
isPubSubReady() {
|
|
1289
1077
|
if (this.transport.kind === "websocket") return true;
|
|
1290
1078
|
return this.pubsub?.isSubscribed?.() ?? true;
|
|
1291
1079
|
}
|
|
1292
|
-
/**
|
|
1293
|
-
* Send to all of a user's connections (across devices/tabs).
|
|
1294
|
-
*
|
|
1295
|
-
* @example
|
|
1296
|
-
* ```ts
|
|
1297
|
-
* await realtime.emitToUser('u_abc', 'invoice.paid', { id: 'inv_123' })
|
|
1298
|
-
* ```
|
|
1299
|
-
*/
|
|
1300
1080
|
emitToUser(userId, event, data) {
|
|
1301
1081
|
return this.transport.emitToUser(userId, event, data);
|
|
1302
1082
|
}
|
|
1303
|
-
/** Send to every connection in a tenant. */
|
|
1304
1083
|
emitToTenant(tenantId, event, data) {
|
|
1305
1084
|
return this.transport.emitToTenant(tenantId, event, data);
|
|
1306
1085
|
}
|
|
1307
|
-
/**
|
|
1308
|
-
* Send to a logical room. Use the prefix convention (`user:{id}`,
|
|
1309
|
-
* `tenant:{id}`, `resource:{type}:{id}`) or a custom non-colliding id.
|
|
1310
|
-
*/
|
|
1311
1086
|
emitToRoom(roomId, event, data) {
|
|
1312
1087
|
return this.transport.emitToRoom(roomId, event, data);
|
|
1313
1088
|
}
|
|
1314
|
-
/** Send to every connected client. Use sparingly. */
|
|
1315
1089
|
broadcast(event, data) {
|
|
1316
1090
|
return this.transport.broadcast(event, data);
|
|
1317
1091
|
}
|
|
1318
|
-
/**
|
|
1319
|
-
* Add a specific connection to a room.
|
|
1320
|
-
*
|
|
1321
|
-
* The room id is not checked. Never pass client-supplied input that could start
|
|
1322
|
-
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
1323
|
-
* receives that tenant's events.
|
|
1324
|
-
*
|
|
1325
|
-
* Acts on a connection this instance holds; for any other id it resolves and changes
|
|
1326
|
-
* nothing. A failure of the transport that holds the connection rejects the call.
|
|
1327
|
-
*/
|
|
1328
1092
|
joinRoom(connectionId, roomId) {
|
|
1329
1093
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1330
1094
|
}
|
|
1331
|
-
/**
|
|
1332
|
-
* Remove a specific connection from a room.
|
|
1333
|
-
*
|
|
1334
|
-
* Acts on a connection this instance holds; for any other id it resolves and changes
|
|
1335
|
-
* nothing. A failure of the transport that holds the connection rejects the call.
|
|
1336
|
-
*/
|
|
1337
1095
|
leaveRoom(connectionId, roomId) {
|
|
1338
1096
|
return this.transport.leaveRoom(connectionId, roomId);
|
|
1339
1097
|
}
|
|
1340
|
-
/**
|
|
1341
|
-
* Force-disconnect a specific connection (e.g. on auth revocation).
|
|
1342
|
-
*
|
|
1343
|
-
* Resolves once the connection is closed on this instance or the revocation has been handed
|
|
1344
|
-
* to the bus for the instance that holds it.
|
|
1345
|
-
*
|
|
1346
|
-
* @throws {Error} `REALTIME_PUBSUB_UNAVAILABLE` when the bus refuses the revocation, or
|
|
1347
|
-
* `REALTIME_TRANSPORT_UNAVAILABLE` when the transport that holds the connection fails.
|
|
1348
|
-
* The connection may still be connected: retry.
|
|
1349
|
-
*/
|
|
1350
1098
|
disconnect(connectionId, reason) {
|
|
1351
1099
|
return this.transport.disconnect(connectionId, reason);
|
|
1352
1100
|
}
|
|
@@ -1378,16 +1126,8 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1378
1126
|
hooks;
|
|
1379
1127
|
logger = new common.Logger(exports.ReauthenticationService.name);
|
|
1380
1128
|
timer = null;
|
|
1381
|
-
/** connectionId → epoch-ms timestamp of last successful revalidation. */
|
|
1382
1129
|
positiveCache = /* @__PURE__ */ new Map();
|
|
1383
1130
|
policy;
|
|
1384
|
-
/**
|
|
1385
|
-
* Schedule the periodic revalidation cycle.
|
|
1386
|
-
*
|
|
1387
|
-
* The timer is unref'd so it never keeps the process alive on its own.
|
|
1388
|
-
* When the authenticator does not implement `revalidate`, the service stays
|
|
1389
|
-
* idle and emits an informative log.
|
|
1390
|
-
*/
|
|
1391
1131
|
onModuleInit() {
|
|
1392
1132
|
if (!this.auth.revalidate) {
|
|
1393
1133
|
this.logger.log("Authenticator does not implement revalidate() \u2014 reauthentication disabled");
|
|
@@ -1401,11 +1141,6 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1401
1141
|
this.timer.unref();
|
|
1402
1142
|
this.logger.log(`Reauthentication scheduled every ${this.policy.intervalSeconds}s`);
|
|
1403
1143
|
}
|
|
1404
|
-
/**
|
|
1405
|
-
* Clear the timer and the positive cache.
|
|
1406
|
-
*
|
|
1407
|
-
* Called by NestJS on graceful shutdown to prevent leaks.
|
|
1408
|
-
*/
|
|
1409
1144
|
onApplicationShutdown() {
|
|
1410
1145
|
if (this.timer) {
|
|
1411
1146
|
clearInterval(this.timer);
|
|
@@ -1413,15 +1148,6 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1413
1148
|
}
|
|
1414
1149
|
this.positiveCache.clear();
|
|
1415
1150
|
}
|
|
1416
|
-
/**
|
|
1417
|
-
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
1418
|
-
*
|
|
1419
|
-
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1420
|
-
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
1421
|
-
* `onFailure` policy and fires the `onReauthenticationFailed` hook best-effort.
|
|
1422
|
-
*
|
|
1423
|
-
* Exposed as public for test access.
|
|
1424
|
-
*/
|
|
1425
1151
|
async runCycle() {
|
|
1426
1152
|
const now = Date.now();
|
|
1427
1153
|
const connections = [
|
|
@@ -1450,11 +1176,6 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1450
1176
|
}
|
|
1451
1177
|
}
|
|
1452
1178
|
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Revoke a connection whose revalidation failed, and keep the cycle going when the
|
|
1455
|
-
* revocation itself is rejected. The positive-cache entry is already gone, so the next
|
|
1456
|
-
* cycle revalidates the connection and tries again.
|
|
1457
|
-
*/
|
|
1458
1179
|
async revoke(conn) {
|
|
1459
1180
|
try {
|
|
1460
1181
|
await this.handleFailure(conn);
|
|
@@ -1464,14 +1185,9 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1464
1185
|
);
|
|
1465
1186
|
}
|
|
1466
1187
|
}
|
|
1467
|
-
/** Evict the positive-cache entry, optionally emit the failure event, then disconnect. */
|
|
1468
1188
|
async handleFailure(conn) {
|
|
1469
1189
|
this.positiveCache.delete(conn.connectionId);
|
|
1470
|
-
if (this.policy.onFailure === "event")
|
|
1471
|
-
await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
|
|
1472
|
-
reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
|
|
1473
|
-
});
|
|
1474
|
-
}
|
|
1190
|
+
if (this.policy.onFailure === "event") this.notify(conn);
|
|
1475
1191
|
void Promise.resolve(
|
|
1476
1192
|
this.hooks?.onReauthenticationFailed?.({
|
|
1477
1193
|
connectionId: conn.connectionId,
|
|
@@ -1489,6 +1205,20 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1489
1205
|
});
|
|
1490
1206
|
await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
|
|
1491
1207
|
}
|
|
1208
|
+
notify(conn) {
|
|
1209
|
+
const failed = (err) => {
|
|
1210
|
+
this.logger.warn(
|
|
1211
|
+
`Reauthentication notification for ${conn.connectionId} failed, disconnecting anyway: ${describeError(err)}`
|
|
1212
|
+
);
|
|
1213
|
+
};
|
|
1214
|
+
try {
|
|
1215
|
+
this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
|
|
1216
|
+
reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
|
|
1217
|
+
}).catch(failed);
|
|
1218
|
+
} catch (err) {
|
|
1219
|
+
failed(err);
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1492
1222
|
};
|
|
1493
1223
|
exports.ReauthenticationService = __decorateClass([
|
|
1494
1224
|
common.Injectable(),
|
|
@@ -1527,8 +1257,10 @@ var SHARED_SERVICES = [
|
|
|
1527
1257
|
function assertModeSupported(wiring, mode, moduleName) {
|
|
1528
1258
|
if (wiring.modes.includes(mode)) return;
|
|
1529
1259
|
const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
|
|
1530
|
-
throw
|
|
1531
|
-
|
|
1260
|
+
throw realtimeError(
|
|
1261
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
1262
|
+
`transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`,
|
|
1263
|
+
{ who: moduleName }
|
|
1532
1264
|
);
|
|
1533
1265
|
}
|
|
1534
1266
|
function warnIfSingleInstance(pubsub, transport, logger) {
|
|
@@ -1568,26 +1300,32 @@ function composeForRoot(moduleClass, wiring, logger, options) {
|
|
|
1568
1300
|
}
|
|
1569
1301
|
function assertSseEndpointApplies(asyncOptions, moduleName) {
|
|
1570
1302
|
if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
|
|
1571
|
-
throw
|
|
1572
|
-
|
|
1303
|
+
throw realtimeError(
|
|
1304
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
1305
|
+
`sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
|
|
1306
|
+
{ who: moduleName }
|
|
1573
1307
|
);
|
|
1574
1308
|
}
|
|
1575
1309
|
function bindSseEndpoint(resolved, declared, bound, moduleName) {
|
|
1576
1310
|
if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
|
|
1577
|
-
throw
|
|
1578
|
-
|
|
1311
|
+
throw realtimeError(
|
|
1312
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
1313
|
+
`the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
|
|
1314
|
+
{ who: moduleName }
|
|
1579
1315
|
);
|
|
1580
1316
|
}
|
|
1581
1317
|
return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
|
|
1582
1318
|
}
|
|
1583
1319
|
function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
|
|
1584
1320
|
if (!raw) {
|
|
1585
|
-
throw
|
|
1321
|
+
throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
|
|
1586
1322
|
}
|
|
1587
1323
|
validateOptions(raw);
|
|
1588
1324
|
if (raw.transport !== declaredMode) {
|
|
1589
|
-
throw
|
|
1590
|
-
|
|
1325
|
+
throw realtimeError(
|
|
1326
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
1327
|
+
`forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`,
|
|
1328
|
+
{ who: moduleName }
|
|
1591
1329
|
);
|
|
1592
1330
|
}
|
|
1593
1331
|
const resolved = applyDefaults(raw);
|
|
@@ -1602,8 +1340,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
1602
1340
|
asyncOptions.useExisting
|
|
1603
1341
|
].filter((pattern) => pattern !== void 0);
|
|
1604
1342
|
if (patterns.length !== 1) {
|
|
1605
|
-
throw
|
|
1606
|
-
|
|
1343
|
+
throw realtimeError(
|
|
1344
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
1345
|
+
`forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
|
|
1346
|
+
{ who: moduleName }
|
|
1607
1347
|
);
|
|
1608
1348
|
}
|
|
1609
1349
|
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
@@ -1768,52 +1508,9 @@ var sseWiring = {
|
|
|
1768
1508
|
}
|
|
1769
1509
|
};
|
|
1770
1510
|
exports.BymaxRealtimeModule = class BymaxRealtimeModule {
|
|
1771
|
-
/**
|
|
1772
|
-
* Configure the module synchronously.
|
|
1773
|
-
*
|
|
1774
|
-
* @throws when the options are invalid.
|
|
1775
|
-
* @example
|
|
1776
|
-
* ```ts
|
|
1777
|
-
* BymaxRealtimeModule.forRoot({
|
|
1778
|
-
* transport: 'sse',
|
|
1779
|
-
* authenticator: new MyAuthenticator(),
|
|
1780
|
-
* })
|
|
1781
|
-
* ```
|
|
1782
|
-
*/
|
|
1783
1511
|
static forRoot(options) {
|
|
1784
1512
|
return composeForRoot(exports.BymaxRealtimeModule, sseWiring, exports.BymaxRealtimeModule.logger, options);
|
|
1785
1513
|
}
|
|
1786
|
-
/**
|
|
1787
|
-
* Configure the module asynchronously so options — and the authenticator —
|
|
1788
|
-
* can be resolved through DI: `ConfigService`, a Redis client, and so on.
|
|
1789
|
-
*
|
|
1790
|
-
* Options are validated inside the resolving factory, so a malformed
|
|
1791
|
-
* configuration rejects at bootstrap and the application fails to start with
|
|
1792
|
-
* a clear error.
|
|
1793
|
-
*
|
|
1794
|
-
* Controllers are registered at decoration time, so the SSE route comes from
|
|
1795
|
-
* `sseEndpoint` on the registration rather than from the `sse.endpoint` the
|
|
1796
|
-
* factory resolves — the factory has not run yet when the controller is
|
|
1797
|
-
* built. It defaults to `/events`, and a factory that resolves a disagreeing
|
|
1798
|
-
* `sse.endpoint` is rejected at bootstrap rather than silently served on
|
|
1799
|
-
* another path.
|
|
1800
|
-
*
|
|
1801
|
-
* @throws when no factory pattern is given, more than one is, or the factory
|
|
1802
|
-
* resolves a transport other than `'sse'`.
|
|
1803
|
-
* @example
|
|
1804
|
-
* ```ts
|
|
1805
|
-
* BymaxRealtimeModule.forRootAsync({
|
|
1806
|
-
* transport: 'sse',
|
|
1807
|
-
* sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
|
|
1808
|
-
* imports: [ConfigModule],
|
|
1809
|
-
* inject: [ConfigService],
|
|
1810
|
-
* useFactory: (cfg: ConfigService) => ({
|
|
1811
|
-
* transport: 'sse' as const,
|
|
1812
|
-
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
1813
|
-
* }),
|
|
1814
|
-
* })
|
|
1815
|
-
* ```
|
|
1816
|
-
*/
|
|
1817
1514
|
static forRootAsync(asyncOptions) {
|
|
1818
1515
|
return composeForRootAsync(
|
|
1819
1516
|
exports.BymaxRealtimeModule,
|
|
@@ -1829,62 +1526,73 @@ exports.BymaxRealtimeModule = __decorateClass([
|
|
|
1829
1526
|
common.Module({})
|
|
1830
1527
|
], exports.BymaxRealtimeModule);
|
|
1831
1528
|
var MALFORMED_REPORT_INTERVAL_MS = 6e4;
|
|
1529
|
+
var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
|
|
1530
|
+
"wait",
|
|
1531
|
+
"connecting",
|
|
1532
|
+
"connect",
|
|
1533
|
+
"reconnecting",
|
|
1534
|
+
"close",
|
|
1535
|
+
"end"
|
|
1536
|
+
]);
|
|
1537
|
+
var PUBLISHER_WAIT_MS = 2e3;
|
|
1538
|
+
var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
|
|
1832
1539
|
function connectionReason(err) {
|
|
1833
1540
|
const code = err?.code;
|
|
1834
1541
|
const text = describeError(err);
|
|
1835
1542
|
return [typeof code === "string" ? code : "", text].filter(Boolean).join(" ") || String(err);
|
|
1836
1543
|
}
|
|
1837
1544
|
var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
1838
|
-
/**
|
|
1839
|
-
* The publishing Redis client.
|
|
1840
|
-
*
|
|
1841
|
-
* An ECMAScript private field for the same reason as the subscriber below: an
|
|
1842
|
-
* ioredis instance carries `options.password` as a plain field, and a
|
|
1843
|
-
* TypeScript `private` one is erased at runtime, leaving it enumerable to
|
|
1844
|
-
* anything that serializes this pubsub adapter.
|
|
1845
|
-
*/
|
|
1846
1545
|
#pub;
|
|
1847
1546
|
channel;
|
|
1848
|
-
/** The lazily created subscriber connection, which carries the same credentials. */
|
|
1849
1547
|
#subInit = null;
|
|
1850
1548
|
handlers = /* @__PURE__ */ new Set();
|
|
1851
1549
|
logger = new common.Logger(_RedisRealtimePubSub.name);
|
|
1852
|
-
/** Payloads dropped as unparsable since the last report, and when that report was made. */
|
|
1853
1550
|
malformedDropped = 0;
|
|
1854
1551
|
malformedReportedAt = 0;
|
|
1855
|
-
/** Whether the subscriber connection holds a confirmed SUBSCRIBE right now. */
|
|
1856
1552
|
#subscribed = false;
|
|
1857
|
-
/** Whether the current outage has been logged, so a retry loop adds no line. */
|
|
1858
|
-
// Stryker disable next-line BooleanLiteral: equivalent — createSubscriber sets it before any use
|
|
1859
1553
|
#outageLogged = false;
|
|
1860
|
-
/** Connections closed on purpose, whose `close` is not an outage and says nothing of a successor. */
|
|
1861
1554
|
#retired = /* @__PURE__ */ new WeakSet();
|
|
1555
|
+
#lastRefusal;
|
|
1862
1556
|
constructor(options) {
|
|
1863
1557
|
this.#pub = options.client;
|
|
1864
1558
|
this.channel = options.channel ?? "bymax:realtime";
|
|
1865
1559
|
}
|
|
1866
|
-
/**
|
|
1867
|
-
* Whether this instance holds a confirmed subscription to the channel, so the events and
|
|
1868
|
-
* revocations other instances publish reach it. False before the first successful subscribe,
|
|
1869
|
-
* while the subscriber connection is down, and after the last handler has unsubscribed.
|
|
1870
|
-
*/
|
|
1871
1560
|
isSubscribed() {
|
|
1872
|
-
return this.#subscribed;
|
|
1561
|
+
return this.#subscribed && !CANNOT_PUBLISH.has(this.#pub.status);
|
|
1873
1562
|
}
|
|
1874
|
-
/** JSON-encodes the message and PUBLISHes it to the configured channel. */
|
|
1875
1563
|
async publish(message) {
|
|
1564
|
+
const status = this.#pub.status;
|
|
1565
|
+
if (CANNOT_PUBLISH.has(status)) {
|
|
1566
|
+
this.connectLazyClient();
|
|
1567
|
+
throw this.cannotPublish(`the Redis client is ${status}`);
|
|
1568
|
+
}
|
|
1876
1569
|
await this.#pub.publish(this.channel, JSON.stringify(message));
|
|
1877
1570
|
}
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1571
|
+
connectLazyClient() {
|
|
1572
|
+
if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
|
|
1573
|
+
}
|
|
1574
|
+
publisherSettled() {
|
|
1575
|
+
const pub = this.#pub;
|
|
1576
|
+
if (pub.status !== "connecting" && pub.status !== "connect") return Promise.resolve();
|
|
1577
|
+
return new Promise((resolve) => {
|
|
1578
|
+
const settle = () => {
|
|
1579
|
+
clearTimeout(deadline);
|
|
1580
|
+
for (const event of CONNECTION_OVER) pub.off(event, settle);
|
|
1581
|
+
resolve();
|
|
1582
|
+
};
|
|
1583
|
+
const deadline = setTimeout(settle, PUBLISHER_WAIT_MS);
|
|
1584
|
+
deadline.unref();
|
|
1585
|
+
for (const event of CONNECTION_OVER) pub.once(event, settle);
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
cannotPublish(reason) {
|
|
1589
|
+
return unavailableError(
|
|
1590
|
+
REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
|
|
1591
|
+
_RedisRealtimePubSub.name,
|
|
1592
|
+
`cannot publish to "${this.channel}"`,
|
|
1593
|
+
new Error(reason)
|
|
1594
|
+
);
|
|
1595
|
+
}
|
|
1888
1596
|
async subscribe(handler) {
|
|
1889
1597
|
this.handlers.add(handler);
|
|
1890
1598
|
let sub;
|
|
@@ -1895,6 +1603,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1895
1603
|
this.#subInit = null;
|
|
1896
1604
|
throw err;
|
|
1897
1605
|
}
|
|
1606
|
+
await this.publisherSettled();
|
|
1898
1607
|
return async () => {
|
|
1899
1608
|
this.handlers.delete(handler);
|
|
1900
1609
|
if (this.handlers.size === 0) {
|
|
@@ -1910,14 +1619,15 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1910
1619
|
}
|
|
1911
1620
|
};
|
|
1912
1621
|
}
|
|
1913
|
-
/** Lazily create the single shared subscribe client (idempotent under concurrent calls). */
|
|
1914
1622
|
ensureSubscriber() {
|
|
1915
1623
|
if (!this.#subInit) this.#subInit = this.createSubscriber();
|
|
1916
1624
|
return this.#subInit;
|
|
1917
1625
|
}
|
|
1918
1626
|
async createSubscriber() {
|
|
1919
1627
|
this.#outageLogged = false;
|
|
1920
|
-
|
|
1628
|
+
this.#lastRefusal = void 0;
|
|
1629
|
+
this.connectLazyClient();
|
|
1630
|
+
const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
|
|
1921
1631
|
let attached = false;
|
|
1922
1632
|
sub.on("message", (_ch, payload) => this.dispatch(payload));
|
|
1923
1633
|
const unreachableFirst = new Promise((resolve) => {
|
|
@@ -1932,10 +1642,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1932
1642
|
sub.on("ready", () => {
|
|
1933
1643
|
if (attached) this.confirm(sub);
|
|
1934
1644
|
});
|
|
1935
|
-
|
|
1645
|
+
await this.negotiate(sub, sub.subscribe(this.channel), unreachableFirst);
|
|
1646
|
+
attached = true;
|
|
1647
|
+
return sub;
|
|
1648
|
+
}
|
|
1649
|
+
async negotiate(sub, first, unreachableFirst) {
|
|
1936
1650
|
try {
|
|
1937
1651
|
const outcome = await Promise.race([
|
|
1938
|
-
first.then(
|
|
1652
|
+
first.then(
|
|
1653
|
+
() => "subscribed",
|
|
1654
|
+
(err) => {
|
|
1655
|
+
if (err.name === "ReplyError") throw err;
|
|
1656
|
+
return { unreachable: err };
|
|
1657
|
+
}
|
|
1658
|
+
),
|
|
1939
1659
|
unreachableFirst
|
|
1940
1660
|
]);
|
|
1941
1661
|
if (outcome === "subscribed") {
|
|
@@ -1954,8 +1674,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1954
1674
|
err
|
|
1955
1675
|
);
|
|
1956
1676
|
}
|
|
1957
|
-
attached = true;
|
|
1958
|
-
return sub;
|
|
1959
1677
|
}
|
|
1960
1678
|
confirm(sub) {
|
|
1961
1679
|
sub.subscribe(this.channel).then(
|
|
@@ -1963,18 +1681,21 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1963
1681
|
(err) => this.refused(err)
|
|
1964
1682
|
);
|
|
1965
1683
|
}
|
|
1966
|
-
/** A server that was reached and refused the SUBSCRIBE after boot: it stays unsubscribed. */
|
|
1967
1684
|
refused(err) {
|
|
1968
1685
|
if (err?.name !== "ReplyError") return;
|
|
1969
1686
|
this.#subscribed = false;
|
|
1687
|
+
const reason = describeError(err);
|
|
1688
|
+
if (reason === this.#lastRefusal) return;
|
|
1689
|
+
this.#lastRefusal = reason;
|
|
1970
1690
|
this.logger.warn(
|
|
1971
|
-
`${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${
|
|
1691
|
+
`${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${reason}`
|
|
1972
1692
|
);
|
|
1973
1693
|
}
|
|
1974
1694
|
markUp() {
|
|
1975
1695
|
if (this.#subscribed) return;
|
|
1976
1696
|
this.#subscribed = true;
|
|
1977
1697
|
this.#outageLogged = false;
|
|
1698
|
+
this.#lastRefusal = void 0;
|
|
1978
1699
|
this.logger.log(
|
|
1979
1700
|
`Subscribed to "${this.channel}"; remote events and revocations reach this instance`
|
|
1980
1701
|
);
|
|
@@ -1987,10 +1708,6 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
1987
1708
|
`${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: not subscribed to "${this.channel}": ${reason}. Remote events and revocations will not reach this instance until it subscribes again`
|
|
1988
1709
|
);
|
|
1989
1710
|
}
|
|
1990
|
-
/**
|
|
1991
|
-
* Count a payload dropped as unparsable and report the count at most once per minute, so a
|
|
1992
|
-
* producer on an incompatible version is visible without flooding the log.
|
|
1993
|
-
*/
|
|
1994
1711
|
reportMalformed() {
|
|
1995
1712
|
this.malformedDropped++;
|
|
1996
1713
|
const now = Date.now();
|
|
@@ -2020,21 +1737,10 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2020
1737
|
|
|
2021
1738
|
// src/server/offline-queue/redis-offline-queue.ts
|
|
2022
1739
|
var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
2023
|
-
/**
|
|
2024
|
-
* The Redis client.
|
|
2025
|
-
*
|
|
2026
|
-
* An ECMAScript private field rather than a TypeScript `private` one, which
|
|
2027
|
-
* is erased at runtime: an ioredis instance carries `options.password` as a
|
|
2028
|
-
* plain field, so leaving this enumerable would let anything that serializes
|
|
2029
|
-
* this queue — or the module options that reference it — reach the Redis
|
|
2030
|
-
* credentials.
|
|
2031
|
-
*/
|
|
2032
1740
|
#client;
|
|
2033
1741
|
maxPerUser;
|
|
2034
1742
|
ttlSeconds;
|
|
2035
|
-
/** Zero-pad width for the epoch-millisecond component of the sort key. */
|
|
2036
1743
|
static MS_PAD = 16;
|
|
2037
|
-
/** Zero-pad width for the intra-millisecond counter component of the sort key. */
|
|
2038
1744
|
static COUNTER_PAD = 6;
|
|
2039
1745
|
constructor(options) {
|
|
2040
1746
|
this.#client = options.client;
|
|
@@ -2044,23 +1750,12 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2044
1750
|
key(userId) {
|
|
2045
1751
|
return `bymax:oq:${userId}`;
|
|
2046
1752
|
}
|
|
2047
|
-
/**
|
|
2048
|
-
* Build the fixed-width lexicographic sort key for an event id.
|
|
2049
|
-
*
|
|
2050
|
-
* Handles two id formats:
|
|
2051
|
-
* - `{ms}-{counter}` from EventIdGenerator: `1717000000000-000001`
|
|
2052
|
-
* - Legacy plain numeric strings: `1700000000000`
|
|
2053
|
-
*/
|
|
2054
1753
|
lexKey(id) {
|
|
2055
1754
|
const dashIdx = id.indexOf("-");
|
|
2056
1755
|
const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
|
|
2057
1756
|
const counter = dashIdx === -1 ? 0 : Number(id.slice(dashIdx + 1));
|
|
2058
1757
|
return String(ms).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(counter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
|
|
2059
1758
|
}
|
|
2060
|
-
/**
|
|
2061
|
-
* Return the lexicographically next sort key after `id`, used as an
|
|
2062
|
-
* inclusive ZRANGEBYLEX lower bound that excludes the `id` event itself.
|
|
2063
|
-
*/
|
|
2064
1759
|
lexKeyNext(id) {
|
|
2065
1760
|
const dashIdx = id.indexOf("-");
|
|
2066
1761
|
const ms = dashIdx === -1 ? Number(id) : Number(id.slice(0, dashIdx));
|
|
@@ -2070,7 +1765,6 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2070
1765
|
const nextCounter = counter < counterMax ? counter + 1 : 0;
|
|
2071
1766
|
return String(nextMs).padStart(_RedisOfflineQueue.MS_PAD, "0") + "-" + String(nextCounter).padStart(_RedisOfflineQueue.COUNTER_PAD, "0");
|
|
2072
1767
|
}
|
|
2073
|
-
/** Encode an event into a lexicographically sortable ZSET member string. */
|
|
2074
1768
|
encodeMember(event) {
|
|
2075
1769
|
return `${this.lexKey(event.id)}|${JSON.stringify(event)}`;
|
|
2076
1770
|
}
|
|
@@ -2124,6 +1818,7 @@ exports.composeRoomId = composeRoomId;
|
|
|
2124
1818
|
exports.createSseController = createSseController;
|
|
2125
1819
|
exports.describeError = describeError;
|
|
2126
1820
|
exports.parseCookieHeader = parseCookieHeader;
|
|
1821
|
+
exports.realtimeError = realtimeError;
|
|
2127
1822
|
exports.reportDeliveryFailure = reportDeliveryFailure;
|
|
2128
1823
|
exports.resolveAuthTenant = resolveAuthTenant;
|
|
2129
1824
|
exports.sseWiring = sseWiring;
|