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