@bymax-one/nest-realtime 1.2.15 → 1.2.17
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 +50 -3
- package/README.md +76 -24
- package/dist/internal/index.cjs +222 -105
- package/dist/internal/index.d.cts +72 -14
- package/dist/internal/index.d.ts +72 -14
- package/dist/internal/index.mjs +221 -106
- package/dist/react/index.cjs +163 -101
- package/dist/react/index.mjs +164 -102
- package/dist/websocket/index.cjs +18 -3
- package/dist/websocket/index.d.cts +4 -0
- package/dist/websocket/index.d.ts +4 -0
- package/dist/websocket/index.mjs +19 -4
- package/package.json +6 -3
package/dist/internal/index.cjs
CHANGED
|
@@ -110,17 +110,30 @@ function validateOptions(options) {
|
|
|
110
110
|
);
|
|
111
111
|
}
|
|
112
112
|
validateHookTimeout(options);
|
|
113
|
+
validateOnConnectFailure(options);
|
|
113
114
|
validateSseOptions(options);
|
|
114
115
|
validateReauthPolicy(options);
|
|
115
116
|
}
|
|
116
117
|
var MAX_TIMER_MS = 2147483647;
|
|
118
|
+
var MAX_PER_USER_CONNECTIONS = 1e5;
|
|
119
|
+
var MAX_REPLAY_EVENTS = 1e5;
|
|
120
|
+
var MAX_HTTP_BUFFER_BYTES = 100 * 1024 * 1024;
|
|
117
121
|
function assertInteger(path, value, least, most) {
|
|
118
122
|
if (value === void 0) return;
|
|
119
|
-
const valid = typeof value === "number" && Number.
|
|
123
|
+
const valid = typeof value === "number" && Number.isSafeInteger(value) && value >= least && (most === void 0 || value <= most);
|
|
120
124
|
if (valid) return;
|
|
121
125
|
throw realtimeError(
|
|
122
126
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
123
|
-
`options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}`,
|
|
127
|
+
`options.${path} must be an integer >= ${least}${most === void 0 ? "" : ` and <= ${most}`}, got ${String(value)}${most === void 0 && Number.isInteger(value) && !Number.isSafeInteger(value) ? ` (the most is ${Number.MAX_SAFE_INTEGER})` : ""}`,
|
|
128
|
+
{ who: "BymaxRealtimeModule" }
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
function validateOnConnectFailure(options) {
|
|
132
|
+
const value = options.onConnectFailure;
|
|
133
|
+
if (value === void 0 || value === "ignore" || value === "close") return;
|
|
134
|
+
throw realtimeError(
|
|
135
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
136
|
+
`options.onConnectFailure must be 'ignore' or 'close', got ${String(value)}`,
|
|
124
137
|
{ who: "BymaxRealtimeModule" }
|
|
125
138
|
);
|
|
126
139
|
}
|
|
@@ -129,6 +142,18 @@ function validateHookTimeout(options) {
|
|
|
129
142
|
assertInteger("authenticateTimeoutMs", options.authenticateTimeoutMs, 1, MAX_TIMER_MS);
|
|
130
143
|
assertInteger("maxPendingHandshakes", options.maxPendingHandshakes, 1);
|
|
131
144
|
assertInteger("maxConnections", options.maxConnections, 1);
|
|
145
|
+
assertInteger(
|
|
146
|
+
"websocket.maxConnectionsPerUser",
|
|
147
|
+
options.websocket?.maxConnectionsPerUser,
|
|
148
|
+
0,
|
|
149
|
+
MAX_PER_USER_CONNECTIONS
|
|
150
|
+
);
|
|
151
|
+
assertInteger(
|
|
152
|
+
"websocket.maxHttpBufferSize",
|
|
153
|
+
options.websocket?.maxHttpBufferSize,
|
|
154
|
+
1,
|
|
155
|
+
MAX_HTTP_BUFFER_BYTES
|
|
156
|
+
);
|
|
132
157
|
assertInteger("websocket.pingIntervalMs", options.websocket?.pingIntervalMs, 1, MAX_TIMER_MS);
|
|
133
158
|
assertInteger("websocket.pingTimeoutMs", options.websocket?.pingTimeoutMs, 1, MAX_TIMER_MS);
|
|
134
159
|
}
|
|
@@ -168,18 +193,12 @@ function validateSseOptions(options) {
|
|
|
168
193
|
{ who: "BymaxRealtimeModule" }
|
|
169
194
|
);
|
|
170
195
|
}
|
|
171
|
-
|
|
172
|
-
throw realtimeError(
|
|
173
|
-
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
174
|
-
`options.sse.replayBufferSize must be >= 0`,
|
|
175
|
-
{ who: "BymaxRealtimeModule" }
|
|
176
|
-
);
|
|
177
|
-
}
|
|
196
|
+
assertInteger("sse.replayBufferSize", sse?.replayBufferSize, 0, MAX_REPLAY_EVENTS);
|
|
178
197
|
assertInteger("sse.replayTtlMs", sse?.replayTtlMs, 1, MAX_TIMER_MS);
|
|
179
198
|
assertInteger("sse.replayMaxIdleUsers", sse?.replayMaxIdleUsers, 1);
|
|
180
199
|
for (const name of ["maxQueuedBytes", "maxQueuedEvents", "stallHeartbeats"]) {
|
|
181
200
|
const value = sse?.[name];
|
|
182
|
-
if (value !== void 0 && !(typeof value === "number" && Number.
|
|
201
|
+
if (value !== void 0 && !(typeof value === "number" && Number.isSafeInteger(value) && value >= 0)) {
|
|
183
202
|
throw realtimeError(
|
|
184
203
|
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
185
204
|
`options.sse.${name} must be an integer >= 0 (0 switches the bound off), got ${String(value)}`,
|
|
@@ -187,13 +206,12 @@ function validateSseOptions(options) {
|
|
|
187
206
|
);
|
|
188
207
|
}
|
|
189
208
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
}
|
|
209
|
+
assertInteger(
|
|
210
|
+
"sse.maxConnectionsPerUser",
|
|
211
|
+
sse?.maxConnectionsPerUser,
|
|
212
|
+
0,
|
|
213
|
+
MAX_PER_USER_CONNECTIONS
|
|
214
|
+
);
|
|
197
215
|
}
|
|
198
216
|
|
|
199
217
|
// src/server/utils/describe-error.ts
|
|
@@ -218,11 +236,26 @@ function reportDeliveryFailure(logger, hooks, failure, what) {
|
|
|
218
236
|
});
|
|
219
237
|
}
|
|
220
238
|
|
|
239
|
+
// src/server/utils/windowed-report.ts
|
|
240
|
+
var REPORT_WINDOW_MS = 1e4;
|
|
241
|
+
function windowedReport(fresh, emit) {
|
|
242
|
+
let startedAt = Number.NEGATIVE_INFINITY;
|
|
243
|
+
let pending = fresh();
|
|
244
|
+
return (add) => {
|
|
245
|
+
pending = add(pending);
|
|
246
|
+
const now = performance.now();
|
|
247
|
+
if (now - startedAt < REPORT_WINDOW_MS) return;
|
|
248
|
+
startedAt = now;
|
|
249
|
+
const accumulated = pending;
|
|
250
|
+
pending = fresh();
|
|
251
|
+
emit(accumulated);
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
221
255
|
// src/server/offline-queue/offline-queue-delivery.service.ts
|
|
222
256
|
var RETRIEVE_LIMIT = 200;
|
|
223
257
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
224
258
|
var DEFAULT_MAX_PENDING = 1e3;
|
|
225
|
-
var REPORT_WINDOW_MS = 1e4;
|
|
226
259
|
var OfflineQueueTimeoutError = class extends Error {
|
|
227
260
|
constructor() {
|
|
228
261
|
super("the offline queue did not answer in time");
|
|
@@ -241,8 +274,14 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
|
|
|
241
274
|
timeoutMs;
|
|
242
275
|
maxPending;
|
|
243
276
|
pending = 0;
|
|
244
|
-
|
|
245
|
-
|
|
277
|
+
timeouts = windowedReport(
|
|
278
|
+
() => 0,
|
|
279
|
+
(count) => {
|
|
280
|
+
this.logger.warn(
|
|
281
|
+
`reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
);
|
|
246
285
|
async retrieve(userId, lastEventId, ringBufferIds) {
|
|
247
286
|
const { events } = await this.retrieveGap(userId, lastEventId);
|
|
248
287
|
return events.filter((e) => !ringBufferIds.has(e.id));
|
|
@@ -318,15 +357,7 @@ exports.OfflineQueueDeliveryService = class OfflineQueueDeliveryService {
|
|
|
318
357
|
}
|
|
319
358
|
}
|
|
320
359
|
countTimeout() {
|
|
321
|
-
this.
|
|
322
|
-
const now = performance.now();
|
|
323
|
-
if (now - this.windowStartedAt < REPORT_WINDOW_MS) return;
|
|
324
|
-
this.windowStartedAt = now;
|
|
325
|
-
const count = this.timedOut;
|
|
326
|
-
this.timedOut = 0;
|
|
327
|
-
this.logger.warn(
|
|
328
|
-
`reconnects given up on since the last report: ${count}, because the offline queue did not answer in ${this.timeoutMs} ms or already had ${this.maxPending} reads waiting`
|
|
329
|
-
);
|
|
360
|
+
this.timeouts((count) => count + 1);
|
|
330
361
|
}
|
|
331
362
|
};
|
|
332
363
|
exports.OfflineQueueDeliveryService = __decorateClass([
|
|
@@ -362,12 +393,39 @@ var ROOM_PREFIXES = {
|
|
|
362
393
|
RESOURCE: "resource"
|
|
363
394
|
};
|
|
364
395
|
|
|
365
|
-
// src/server/utils/
|
|
396
|
+
// src/server/utils/reserved-room.ts
|
|
366
397
|
var RESERVED_ROOM_PREFIXES = [
|
|
367
398
|
`${ROOM_PREFIXES.USER}:`,
|
|
368
399
|
`${ROOM_PREFIXES.TENANT}:`,
|
|
369
400
|
"connection:"
|
|
370
401
|
];
|
|
402
|
+
function reservedRoomPrefix(room) {
|
|
403
|
+
return RESERVED_ROOM_PREFIXES.find((prefix) => room.startsWith(prefix));
|
|
404
|
+
}
|
|
405
|
+
function describeShape(value) {
|
|
406
|
+
if (value === null) return "null";
|
|
407
|
+
return Array.isArray(value) ? "an array" : typeof value;
|
|
408
|
+
}
|
|
409
|
+
function requireRoomName(operation, roomId) {
|
|
410
|
+
if (typeof roomId === "string" && roomId.length > 0) return;
|
|
411
|
+
throw realtimeError(
|
|
412
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
413
|
+
`${operation}: \`roomId\` must be a non-empty string, got ${describeShape(roomId)}`,
|
|
414
|
+
{ who: "RealtimeService" }
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
function refuseReservedRoom(operation, roomId) {
|
|
418
|
+
requireRoomName(operation, roomId);
|
|
419
|
+
const prefix = reservedRoomPrefix(roomId);
|
|
420
|
+
if (prefix === void 0) return;
|
|
421
|
+
throw realtimeError(
|
|
422
|
+
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
423
|
+
`${operation}: \`roomId\` starts with the reserved prefix "${prefix}", which the library composes itself`,
|
|
424
|
+
{ who: "RealtimeService" }
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// src/server/utils/admit-rooms.ts
|
|
371
429
|
function refuse(detail) {
|
|
372
430
|
throw realtimeError(
|
|
373
431
|
REALTIME_ERROR_CODES.AUTH_FAILED,
|
|
@@ -394,7 +452,7 @@ function admitRooms(auth) {
|
|
|
394
452
|
if (room.length > ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH) {
|
|
395
453
|
refuse(`a room name is longer than ${ADMISSION_ROOM_LIMITS.MAX_ROOM_NAME_LENGTH} characters`);
|
|
396
454
|
}
|
|
397
|
-
const reserved =
|
|
455
|
+
const reserved = reservedRoomPrefix(room);
|
|
398
456
|
if (reserved !== void 0) refuse(`a room name starts with the reserved prefix "${reserved}"`);
|
|
399
457
|
}
|
|
400
458
|
return { ...auth, rooms: Object.freeze(admitted) };
|
|
@@ -459,7 +517,6 @@ function resolveClientAddress(request) {
|
|
|
459
517
|
}
|
|
460
518
|
return peerAddress(request.socket?.remoteAddress);
|
|
461
519
|
}
|
|
462
|
-
var REPORT_WINDOW_MS2 = 1e4;
|
|
463
520
|
var AuthenticationUnavailableError = class extends Error {
|
|
464
521
|
constructor(reason) {
|
|
465
522
|
super(
|
|
@@ -480,8 +537,14 @@ exports.AuthenticationGate = class AuthenticationGate {
|
|
|
480
537
|
maxPending;
|
|
481
538
|
timeoutMs;
|
|
482
539
|
pending = 0;
|
|
483
|
-
|
|
484
|
-
|
|
540
|
+
refusals = windowedReport(
|
|
541
|
+
() => ({ saturated: 0, timeout: 0 }),
|
|
542
|
+
({ saturated, timeout }) => {
|
|
543
|
+
this.logger.warn(
|
|
544
|
+
`handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
);
|
|
485
548
|
async authenticate(context) {
|
|
486
549
|
if (this.pending >= this.maxPending) {
|
|
487
550
|
this.refuse("saturated");
|
|
@@ -510,15 +573,7 @@ exports.AuthenticationGate = class AuthenticationGate {
|
|
|
510
573
|
}
|
|
511
574
|
}
|
|
512
575
|
refuse(reason) {
|
|
513
|
-
this.refused[reason]
|
|
514
|
-
const now = performance.now();
|
|
515
|
-
if (now - this.windowStartedAt < REPORT_WINDOW_MS2) return;
|
|
516
|
-
this.windowStartedAt = now;
|
|
517
|
-
const { saturated, timeout } = this.refused;
|
|
518
|
-
this.refused = { saturated: 0, timeout: 0 };
|
|
519
|
-
this.logger.warn(
|
|
520
|
-
`handshakes refused since the last report: ${saturated} because ${this.maxPending} were already waiting for the authenticator, ${timeout} because it did not answer in ${this.timeoutMs} ms`
|
|
521
|
-
);
|
|
576
|
+
this.refusals((refused) => ({ ...refused, [reason]: refused[reason] + 1 }));
|
|
522
577
|
}
|
|
523
578
|
};
|
|
524
579
|
exports.AuthenticationGate = __decorateClass([
|
|
@@ -596,7 +651,6 @@ exports.ConnectionRegistry = __decorateClass([
|
|
|
596
651
|
var DEFAULT_AUTHENTICATE_TIMEOUT_MS = 1e4;
|
|
597
652
|
var DEFAULT_MAX_CONNECTIONS = 1e4;
|
|
598
653
|
var HOLD_MARGIN_MS = 5e3;
|
|
599
|
-
var REPORT_WINDOW_MS3 = 1e4;
|
|
600
654
|
var ConnectionLimitError = class extends Error {
|
|
601
655
|
constructor(limit) {
|
|
602
656
|
super(`the instance already holds ${limit} connections`);
|
|
@@ -619,8 +673,14 @@ exports.ConnectionAdmission = class ConnectionAdmission {
|
|
|
619
673
|
max;
|
|
620
674
|
holdMs;
|
|
621
675
|
held = /* @__PURE__ */ new Map();
|
|
622
|
-
|
|
623
|
-
|
|
676
|
+
refusals = windowedReport(
|
|
677
|
+
() => 0,
|
|
678
|
+
(count) => {
|
|
679
|
+
this.logger.warn(
|
|
680
|
+
`connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
);
|
|
624
684
|
admit() {
|
|
625
685
|
const place = /* @__PURE__ */ Symbol("place");
|
|
626
686
|
this.take(place);
|
|
@@ -652,15 +712,7 @@ exports.ConnectionAdmission = class ConnectionAdmission {
|
|
|
652
712
|
}
|
|
653
713
|
}
|
|
654
714
|
refuse() {
|
|
655
|
-
this.
|
|
656
|
-
const now = performance.now();
|
|
657
|
-
if (now - this.windowStartedAt < REPORT_WINDOW_MS3) return;
|
|
658
|
-
this.windowStartedAt = now;
|
|
659
|
-
const count = this.refused;
|
|
660
|
-
this.refused = 0;
|
|
661
|
-
this.logger.warn(
|
|
662
|
-
`connections refused since the last report: ${count}, because the instance already holds ${this.max} (maxConnections)`
|
|
663
|
-
);
|
|
715
|
+
this.refusals((count) => count + 1);
|
|
664
716
|
}
|
|
665
717
|
};
|
|
666
718
|
exports.ConnectionAdmission = __decorateClass([
|
|
@@ -769,7 +821,12 @@ function composeRoomId(prefix, ...parts) {
|
|
|
769
821
|
}
|
|
770
822
|
function unavailableError(code, who, what, cause) {
|
|
771
823
|
const { message } = realtimeError(code, `${what} (${describeError(cause)})`, { who });
|
|
772
|
-
|
|
824
|
+
const error = Object.assign(new common.ServiceUnavailableException(), { code });
|
|
825
|
+
Object.defineProperties(error, {
|
|
826
|
+
message: { value: message, enumerable: false, writable: true, configurable: true },
|
|
827
|
+
cause: { value: cause, enumerable: false, writable: true, configurable: true }
|
|
828
|
+
});
|
|
829
|
+
return error;
|
|
773
830
|
}
|
|
774
831
|
exports.InMemoryPubSub = class InMemoryPubSub {
|
|
775
832
|
handlers = /* @__PURE__ */ new Set();
|
|
@@ -1179,6 +1236,7 @@ exports.SseTransport = class SseTransport {
|
|
|
1179
1236
|
await this.publish({ op: "emitToTenant", args: { tenantId, event, data, id } });
|
|
1180
1237
|
}
|
|
1181
1238
|
async emitToRoom(roomId, event, data) {
|
|
1239
|
+
requireRoomName("emitToRoom", roomId);
|
|
1182
1240
|
const id = this.idGen.next();
|
|
1183
1241
|
this.emitToRoomLocal(roomId, event, data, id);
|
|
1184
1242
|
await this.publish({ op: "emitToRoom", args: { roomId, event, data, id } });
|
|
@@ -1189,10 +1247,12 @@ exports.SseTransport = class SseTransport {
|
|
|
1189
1247
|
await this.publish({ op: "broadcast", args: { event, data, id } });
|
|
1190
1248
|
}
|
|
1191
1249
|
async joinRoom(connectionId, roomId) {
|
|
1250
|
+
refuseReservedRoom("joinRoom", roomId);
|
|
1192
1251
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
1193
1252
|
this.rooms.join(connectionId, roomId);
|
|
1194
1253
|
}
|
|
1195
1254
|
async leaveRoom(connectionId, roomId) {
|
|
1255
|
+
refuseReservedRoom("leaveRoom", roomId);
|
|
1196
1256
|
if (this.connections.get(connectionId)?.transport === "sse")
|
|
1197
1257
|
this.rooms.leave(connectionId, roomId);
|
|
1198
1258
|
}
|
|
@@ -1635,7 +1695,10 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1635
1695
|
}
|
|
1636
1696
|
const record = this.transport.getConnection(connectionId);
|
|
1637
1697
|
if (record) {
|
|
1638
|
-
this.fireHook(
|
|
1698
|
+
this.fireHook(
|
|
1699
|
+
() => this.hooks?.onConnect?.(buildMeta(record)),
|
|
1700
|
+
this.options.onConnectFailure === "close" ? () => subscriber.complete() : void 0
|
|
1701
|
+
);
|
|
1639
1702
|
}
|
|
1640
1703
|
const heartbeatMs = this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
|
|
1641
1704
|
this.heartbeat.start(
|
|
@@ -1645,9 +1708,11 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
1645
1708
|
() => this.transport.checkStall(connectionId)
|
|
1646
1709
|
);
|
|
1647
1710
|
}
|
|
1648
|
-
fireHook(invoke) {
|
|
1711
|
+
fireHook(invoke, onFailure) {
|
|
1649
1712
|
void runHook(invoke).then((failed) => {
|
|
1650
|
-
if (failed)
|
|
1713
|
+
if (!failed) return;
|
|
1714
|
+
this.logger.warn(`Lifecycle hook failed: ${describeError(failed.error)}`);
|
|
1715
|
+
onFailure?.();
|
|
1651
1716
|
});
|
|
1652
1717
|
}
|
|
1653
1718
|
};
|
|
@@ -1726,16 +1791,19 @@ exports.RealtimeService = class RealtimeService {
|
|
|
1726
1791
|
emitToTenant(tenantId, event, data) {
|
|
1727
1792
|
return this.transport.emitToTenant(tenantId, event, data);
|
|
1728
1793
|
}
|
|
1729
|
-
emitToRoom(roomId, event, data) {
|
|
1794
|
+
async emitToRoom(roomId, event, data) {
|
|
1795
|
+
requireRoomName("emitToRoom", roomId);
|
|
1730
1796
|
return this.transport.emitToRoom(roomId, event, data);
|
|
1731
1797
|
}
|
|
1732
1798
|
broadcast(event, data) {
|
|
1733
1799
|
return this.transport.broadcast(event, data);
|
|
1734
1800
|
}
|
|
1735
|
-
joinRoom(connectionId, roomId) {
|
|
1801
|
+
async joinRoom(connectionId, roomId) {
|
|
1802
|
+
refuseReservedRoom("joinRoom", roomId);
|
|
1736
1803
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1737
1804
|
}
|
|
1738
|
-
leaveRoom(connectionId, roomId) {
|
|
1805
|
+
async leaveRoom(connectionId, roomId) {
|
|
1806
|
+
refuseReservedRoom("leaveRoom", roomId);
|
|
1739
1807
|
return this.transport.leaveRoom(connectionId, roomId);
|
|
1740
1808
|
}
|
|
1741
1809
|
disconnect(connectionId, reason) {
|
|
@@ -2039,26 +2107,54 @@ function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, modu
|
|
|
2039
2107
|
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
2040
2108
|
return resolved;
|
|
2041
2109
|
}
|
|
2042
|
-
function
|
|
2043
|
-
const moduleName = moduleClass.name;
|
|
2110
|
+
function assertOneFactoryPattern(asyncOptions, moduleName) {
|
|
2044
2111
|
const patterns = [
|
|
2045
2112
|
asyncOptions.useFactory,
|
|
2046
2113
|
asyncOptions.useClass,
|
|
2047
2114
|
asyncOptions.useExisting
|
|
2048
2115
|
].filter((pattern) => pattern !== void 0);
|
|
2049
|
-
if (patterns.length
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2116
|
+
if (patterns.length === 1) return;
|
|
2117
|
+
throw realtimeError(
|
|
2118
|
+
REALTIME_ERROR_CODES.INVALID_OPTIONS,
|
|
2119
|
+
`forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
|
|
2120
|
+
{ who: moduleName }
|
|
2121
|
+
);
|
|
2122
|
+
}
|
|
2123
|
+
function buildOptionsProvider(asyncOptions, resolve, factoryToken) {
|
|
2124
|
+
if (asyncOptions.useFactory) {
|
|
2125
|
+
return {
|
|
2126
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
2127
|
+
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
2128
|
+
inject: [...asyncOptions.inject ?? []]
|
|
2129
|
+
};
|
|
2055
2130
|
}
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2131
|
+
return {
|
|
2132
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
2133
|
+
useFactory: async (factory) => resolve(
|
|
2134
|
+
await factory.createRealtimeOptions(),
|
|
2135
|
+
"createRealtimeOptions"
|
|
2136
|
+
),
|
|
2137
|
+
inject: [asyncOptions.useExisting ?? factoryToken]
|
|
2138
|
+
};
|
|
2139
|
+
}
|
|
2140
|
+
function fromOptions(token, read) {
|
|
2141
|
+
return { provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] };
|
|
2142
|
+
}
|
|
2143
|
+
function buildOptionDerivedProviders(logger, instanceId) {
|
|
2144
|
+
return [
|
|
2145
|
+
fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
|
|
2146
|
+
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
2147
|
+
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
2148
|
+
return opts.pubsub ?? new exports.InMemoryPubSub();
|
|
2149
|
+
}),
|
|
2150
|
+
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
2151
|
+
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2152
|
+
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
2153
|
+
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence)
|
|
2154
|
+
];
|
|
2155
|
+
}
|
|
2156
|
+
function buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName) {
|
|
2157
|
+
return (raw, source) => {
|
|
2062
2158
|
const resolved = resolveAsyncOptions(
|
|
2063
2159
|
raw,
|
|
2064
2160
|
asyncOptions.transport,
|
|
@@ -2070,20 +2166,17 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
2070
2166
|
if (asyncOptions.transport === "websocket") return resolved;
|
|
2071
2167
|
return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
|
|
2072
2168
|
};
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
|
|
2084
|
-
};
|
|
2169
|
+
}
|
|
2170
|
+
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
2171
|
+
const moduleName = moduleClass.name;
|
|
2172
|
+
assertOneFactoryPattern(asyncOptions, moduleName);
|
|
2173
|
+
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
2174
|
+
assertSseEndpointApplies(asyncOptions, moduleName);
|
|
2175
|
+
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
2176
|
+
const instanceId = crypto.randomUUID();
|
|
2177
|
+
const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
|
|
2178
|
+
const resolve = buildResolver(asyncOptions, instanceId, boundSseEndpoint, logger, moduleName);
|
|
2085
2179
|
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
2086
|
-
const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
|
|
2087
2180
|
const { providers: transportProviders, controllers } = wiring.buildAsync({
|
|
2088
2181
|
mode: asyncOptions.transport,
|
|
2089
2182
|
sseEndpoint: boundSseEndpoint
|
|
@@ -2094,16 +2187,8 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
2094
2187
|
controllers,
|
|
2095
2188
|
providers: [
|
|
2096
2189
|
...factoryClassProvider,
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
2100
|
-
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
2101
|
-
return opts.pubsub ?? new exports.InMemoryPubSub();
|
|
2102
|
-
}),
|
|
2103
|
-
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
2104
|
-
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2105
|
-
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
2106
|
-
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
|
|
2190
|
+
buildOptionsProvider(asyncOptions, resolve, FACTORY_TOKEN),
|
|
2191
|
+
...buildOptionDerivedProviders(logger, instanceId),
|
|
2107
2192
|
...SHARED_SERVICES,
|
|
2108
2193
|
...transportProviders,
|
|
2109
2194
|
...asyncOptions.extraProviders ?? []
|
|
@@ -2135,9 +2220,17 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
|
|
|
2135
2220
|
this.unsubscribe = null;
|
|
2136
2221
|
}
|
|
2137
2222
|
}
|
|
2223
|
+
dropped = windowedReport(
|
|
2224
|
+
() => ({ count: 0, last: "none" }),
|
|
2225
|
+
({ count, last }) => {
|
|
2226
|
+
this.logger.warn(
|
|
2227
|
+
`Pub/sub dropped ${count} message(s) it could not act on since the last report (last: ${last})`
|
|
2228
|
+
);
|
|
2229
|
+
}
|
|
2230
|
+
);
|
|
2138
2231
|
handle(msg) {
|
|
2139
|
-
if (msg.origin === this.instanceId) return;
|
|
2140
2232
|
try {
|
|
2233
|
+
if (msg.origin === this.instanceId) return;
|
|
2141
2234
|
switch (msg.op) {
|
|
2142
2235
|
case "emitToUser": {
|
|
2143
2236
|
const a = msg.args;
|
|
@@ -2171,14 +2264,17 @@ exports.RealtimePubSubSubscriber = class RealtimePubSubSubscriber {
|
|
|
2171
2264
|
break;
|
|
2172
2265
|
}
|
|
2173
2266
|
default: {
|
|
2174
|
-
|
|
2175
|
-
this.
|
|
2267
|
+
msg.op;
|
|
2268
|
+
this.drop("unknown op");
|
|
2176
2269
|
}
|
|
2177
2270
|
}
|
|
2178
2271
|
} catch (err) {
|
|
2179
|
-
this.
|
|
2272
|
+
this.drop(String(Object(err).constructor?.name ?? "Error"));
|
|
2180
2273
|
}
|
|
2181
2274
|
}
|
|
2275
|
+
drop(last) {
|
|
2276
|
+
this.dropped(({ count }) => ({ count: count + 1, last }));
|
|
2277
|
+
}
|
|
2182
2278
|
};
|
|
2183
2279
|
exports.RealtimePubSubSubscriber = __decorateClass([
|
|
2184
2280
|
common.Injectable(),
|
|
@@ -2267,6 +2363,7 @@ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
|
|
|
2267
2363
|
"end"
|
|
2268
2364
|
]);
|
|
2269
2365
|
var PUBLISHER_WAIT_MS = 2e3;
|
|
2366
|
+
var PUBLISH_WAIT_MS = 2e3;
|
|
2270
2367
|
var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
|
|
2271
2368
|
function connectionReason(err) {
|
|
2272
2369
|
const code = err?.code;
|
|
@@ -2298,7 +2395,20 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2298
2395
|
this.connectLazyClient();
|
|
2299
2396
|
throw this.cannotPublish(`the Redis client is ${status}`);
|
|
2300
2397
|
}
|
|
2301
|
-
|
|
2398
|
+
const sent = this.#pub.publish(this.channel, JSON.stringify(message));
|
|
2399
|
+
let timer;
|
|
2400
|
+
const expired = new Promise((_resolve, reject) => {
|
|
2401
|
+
timer = setTimeout(
|
|
2402
|
+
() => reject(this.cannotPublish(`the server did not answer within ${PUBLISH_WAIT_MS} ms`)),
|
|
2403
|
+
PUBLISH_WAIT_MS
|
|
2404
|
+
);
|
|
2405
|
+
timer.unref();
|
|
2406
|
+
});
|
|
2407
|
+
try {
|
|
2408
|
+
await Promise.race([sent, expired]);
|
|
2409
|
+
} finally {
|
|
2410
|
+
clearTimeout(timer);
|
|
2411
|
+
}
|
|
2302
2412
|
}
|
|
2303
2413
|
connectLazyClient() {
|
|
2304
2414
|
if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
|
|
@@ -2457,7 +2567,12 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
|
|
|
2457
2567
|
dispatch(payload) {
|
|
2458
2568
|
let msg;
|
|
2459
2569
|
try {
|
|
2460
|
-
|
|
2570
|
+
const parsed = JSON.parse(payload);
|
|
2571
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
2572
|
+
this.reportMalformed();
|
|
2573
|
+
return;
|
|
2574
|
+
}
|
|
2575
|
+
msg = parsed;
|
|
2461
2576
|
} catch {
|
|
2462
2577
|
this.reportMalformed();
|
|
2463
2578
|
return;
|
|
@@ -2562,7 +2677,9 @@ exports.describeError = describeError;
|
|
|
2562
2677
|
exports.parseCookieHeader = parseCookieHeader;
|
|
2563
2678
|
exports.quitWithin = quitWithin;
|
|
2564
2679
|
exports.realtimeError = realtimeError;
|
|
2680
|
+
exports.refuseReservedRoom = refuseReservedRoom;
|
|
2565
2681
|
exports.reportDeliveryFailure = reportDeliveryFailure;
|
|
2682
|
+
exports.requireRoomName = requireRoomName;
|
|
2566
2683
|
exports.resolveAuthTenant = resolveAuthTenant;
|
|
2567
2684
|
exports.runHook = runHook;
|
|
2568
2685
|
exports.sseWiring = sseWiring;
|