@bymax-one/nest-realtime 1.0.1 → 1.0.2
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 -1
- package/README.md +17 -14
- package/dist/server/index.cjs +226 -884
- package/dist/server/index.d.cts +45 -636
- package/dist/server/index.d.ts +45 -636
- package/dist/server/index.mjs +227 -884
- package/dist/websocket/index.cjs +2018 -0
- package/dist/websocket/index.d.cts +1083 -0
- package/dist/websocket/index.d.ts +1083 -0
- package/dist/websocket/index.mjs +2016 -0
- package/package.json +15 -2
package/dist/server/index.mjs
CHANGED
|
@@ -1,19 +1,11 @@
|
|
|
1
|
-
import { randomUUID } from 'crypto';
|
|
2
1
|
import { Injectable, Optional, Inject, Logger, Global, Module, Sse, Req, Res, Controller, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
3
|
import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
|
|
4
4
|
import { takeUntil, catchError, finalize } from 'rxjs/operators';
|
|
5
|
-
import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
|
|
6
|
-
import { IoAdapter } from '@nestjs/platform-socket.io';
|
|
7
5
|
|
|
8
6
|
var __defProp = Object.defineProperty;
|
|
9
7
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
10
8
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
11
|
-
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
12
|
-
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
13
|
-
}) : x)(function(x) {
|
|
14
|
-
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
15
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
16
|
-
});
|
|
17
9
|
var __decorateClass = (decorators, target, key, kind) => {
|
|
18
10
|
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
19
11
|
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
@@ -994,81 +986,6 @@ var InMemoryPubSub = class {
|
|
|
994
986
|
InMemoryPubSub = __decorateClass([
|
|
995
987
|
Injectable()
|
|
996
988
|
], InMemoryPubSub);
|
|
997
|
-
var RealtimePubSubSubscriber = class {
|
|
998
|
-
constructor(pubsub, instanceId, sse) {
|
|
999
|
-
this.pubsub = pubsub;
|
|
1000
|
-
this.instanceId = instanceId;
|
|
1001
|
-
this.sse = sse;
|
|
1002
|
-
}
|
|
1003
|
-
pubsub;
|
|
1004
|
-
instanceId;
|
|
1005
|
-
sse;
|
|
1006
|
-
logger = new Logger(RealtimePubSubSubscriber.name);
|
|
1007
|
-
unsubscribe = null;
|
|
1008
|
-
async onModuleInit() {
|
|
1009
|
-
try {
|
|
1010
|
-
this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
|
|
1011
|
-
} catch (err) {
|
|
1012
|
-
this.logger.warn(
|
|
1013
|
-
`Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
|
|
1014
|
-
);
|
|
1015
|
-
}
|
|
1016
|
-
}
|
|
1017
|
-
async onApplicationShutdown() {
|
|
1018
|
-
if (this.unsubscribe) {
|
|
1019
|
-
try {
|
|
1020
|
-
await this.unsubscribe();
|
|
1021
|
-
} catch (err) {
|
|
1022
|
-
this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
|
|
1023
|
-
}
|
|
1024
|
-
this.unsubscribe = null;
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
handle(msg) {
|
|
1028
|
-
if (msg.origin === this.instanceId) return;
|
|
1029
|
-
try {
|
|
1030
|
-
switch (msg.op) {
|
|
1031
|
-
case "emitToUser": {
|
|
1032
|
-
const a = msg.args;
|
|
1033
|
-
this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
|
|
1034
|
-
break;
|
|
1035
|
-
}
|
|
1036
|
-
case "emitToTenant": {
|
|
1037
|
-
const a = msg.args;
|
|
1038
|
-
this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
|
|
1039
|
-
break;
|
|
1040
|
-
}
|
|
1041
|
-
case "emitToRoom": {
|
|
1042
|
-
const a = msg.args;
|
|
1043
|
-
this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
|
|
1044
|
-
break;
|
|
1045
|
-
}
|
|
1046
|
-
case "broadcast": {
|
|
1047
|
-
const a = msg.args;
|
|
1048
|
-
this.sse.broadcastLocal(a.event, a.data, a.id);
|
|
1049
|
-
break;
|
|
1050
|
-
}
|
|
1051
|
-
case "disconnect": {
|
|
1052
|
-
const a = msg.args;
|
|
1053
|
-
void this.sse.disconnectLocal(a.connectionId, a.reason);
|
|
1054
|
-
break;
|
|
1055
|
-
}
|
|
1056
|
-
default: {
|
|
1057
|
-
const exhaustive = msg.op;
|
|
1058
|
-
this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
} catch (err) {
|
|
1062
|
-
this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
};
|
|
1066
|
-
RealtimePubSubSubscriber = __decorateClass([
|
|
1067
|
-
Injectable(),
|
|
1068
|
-
__decorateParam(0, Inject(REALTIME_PUBSUB_TOKEN)),
|
|
1069
|
-
__decorateParam(1, Inject(REALTIME_INSTANCE_ID_TOKEN)),
|
|
1070
|
-
__decorateParam(2, Inject(SseTransport))
|
|
1071
|
-
], RealtimePubSubSubscriber);
|
|
1072
989
|
var RealtimeService = class {
|
|
1073
990
|
constructor(transport) {
|
|
1074
991
|
this.transport = transport;
|
|
@@ -1236,475 +1153,42 @@ ReauthenticationService = __decorateClass([
|
|
|
1236
1153
|
__decorateParam(4, Optional()),
|
|
1237
1154
|
__decorateParam(4, Inject(REALTIME_HOOKS_TOKEN))
|
|
1238
1155
|
], ReauthenticationService);
|
|
1239
|
-
var CONNECTION_ROOM_PREFIX = "connection";
|
|
1240
|
-
var WebSocketTransport = class {
|
|
1241
|
-
constructor(connections, rooms, auth, hooks, options) {
|
|
1242
|
-
this.connections = connections;
|
|
1243
|
-
this.rooms = rooms;
|
|
1244
|
-
this.auth = auth;
|
|
1245
|
-
this.hooks = hooks;
|
|
1246
|
-
this.options = options;
|
|
1247
|
-
}
|
|
1248
|
-
connections;
|
|
1249
|
-
rooms;
|
|
1250
|
-
auth;
|
|
1251
|
-
hooks;
|
|
1252
|
-
options;
|
|
1253
|
-
kind = "websocket";
|
|
1254
|
-
logger = new Logger(WebSocketTransport.name);
|
|
1255
|
-
/** Nullable until the gateway's afterInit wires the instance. */
|
|
1256
|
-
server = null;
|
|
1257
|
-
/**
|
|
1258
|
-
* Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
|
|
1259
|
-
*
|
|
1260
|
-
* All emit methods silently no-op until this is called, so the transport is
|
|
1261
|
-
* safe to construct before the HTTP server is ready.
|
|
1262
|
-
*
|
|
1263
|
-
* @param server - The live Socket.IO `Server` instance from the NestJS gateway.
|
|
1264
|
-
*/
|
|
1265
|
-
setServer(server) {
|
|
1266
|
-
this.server = server;
|
|
1267
|
-
this.logger.log("Socket.IO server wired to WebSocketTransport");
|
|
1268
|
-
}
|
|
1269
|
-
/**
|
|
1270
|
-
* Resolve the map of locally-connected sockets, tolerating both server shapes.
|
|
1271
|
-
*
|
|
1272
|
-
* A root Socket.IO `Server` exposes the socket map at `.sockets.sockets` (its
|
|
1273
|
-
* `.sockets` is the root `Namespace`). When `websocket.namespace` is configured,
|
|
1274
|
-
* `RealtimeIoAdapter` wires the gateway to a `Namespace` instead, whose own
|
|
1275
|
-
* `.sockets` IS the socket map. Per-socket lookups (join/leave/disconnect) use
|
|
1276
|
-
* this indirection so they work under either shape.
|
|
1277
|
-
*/
|
|
1278
|
-
localSockets() {
|
|
1279
|
-
const server = this.server;
|
|
1280
|
-
if (!server) return void 0;
|
|
1281
|
-
const sockets = server.sockets;
|
|
1282
|
-
return sockets instanceof Map ? sockets : sockets.sockets;
|
|
1283
|
-
}
|
|
1284
|
-
/**
|
|
1285
|
-
* Expose the configured authenticator to the gateway.
|
|
1286
|
-
*
|
|
1287
|
-
* The gateway uses this to avoid a circular injection: `RealtimeGateway` →
|
|
1288
|
-
* `WebSocketTransport` → authenticator, rather than injecting the token
|
|
1289
|
-
* directly in the gateway.
|
|
1290
|
-
*
|
|
1291
|
-
* @returns The consumer-provided `IConnectionAuthenticator` instance.
|
|
1292
|
-
*/
|
|
1293
|
-
authenticator() {
|
|
1294
|
-
return this.auth;
|
|
1295
|
-
}
|
|
1296
|
-
/**
|
|
1297
|
-
* Register a freshly-authenticated WebSocket connection.
|
|
1298
|
-
*
|
|
1299
|
-
* Stores the connection record in `ConnectionRegistry` (with `subject: null` —
|
|
1300
|
-
* WS connections have no RxJS stream), auto-joins the canonical rooms, mirrors
|
|
1301
|
-
* membership into `RoomRegistry`, and fires the `onConnect` lifecycle hook.
|
|
1302
|
-
*
|
|
1303
|
-
* Cross-instance fan-out is handled by `@socket.io/redis-adapter`; this method
|
|
1304
|
-
* does not publish to `IRealtimePubSub`.
|
|
1305
|
-
*
|
|
1306
|
-
* @param socket - The authenticated Socket.IO socket instance.
|
|
1307
|
-
* @param auth - The resolved authentication result containing userId, tenantId, and roles.
|
|
1308
|
-
*/
|
|
1309
|
-
async registerSocket(socket, auth) {
|
|
1310
|
-
const connectedAt = /* @__PURE__ */ new Date();
|
|
1311
|
-
this.connections.register({
|
|
1312
|
-
connectionId: socket.id,
|
|
1313
|
-
userId: auth.userId,
|
|
1314
|
-
tenantId: auth.tenantId,
|
|
1315
|
-
transport: "websocket",
|
|
1316
|
-
ip: socket.handshake.address,
|
|
1317
|
-
userAgent: socket.handshake.headers["user-agent"],
|
|
1318
|
-
connectedAt,
|
|
1319
|
-
subject: null,
|
|
1320
|
-
close$: null,
|
|
1321
|
-
originalAuth: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
|
|
1322
|
-
});
|
|
1323
|
-
await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
1324
|
-
if (auth.tenantId) await socket.join(`${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
1325
|
-
await socket.join(`${CONNECTION_ROOM_PREFIX}:${socket.id}`);
|
|
1326
|
-
this.rooms.join(socket.id, `${ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
1327
|
-
if (auth.tenantId) this.rooms.join(socket.id, `${ROOM_PREFIXES.TENANT}:${auth.tenantId}`);
|
|
1328
|
-
await this.evictBeyondLimit(auth.userId);
|
|
1329
|
-
await this.hooks.onConnect?.({
|
|
1330
|
-
connectionId: socket.id,
|
|
1331
|
-
userId: auth.userId,
|
|
1332
|
-
tenantId: auth.tenantId,
|
|
1333
|
-
transport: "websocket",
|
|
1334
|
-
ip: socket.handshake.address,
|
|
1335
|
-
userAgent: socket.handshake.headers["user-agent"],
|
|
1336
|
-
connectedAt
|
|
1337
|
-
});
|
|
1338
|
-
}
|
|
1339
|
-
/**
|
|
1340
|
-
* Unregister a disconnected WebSocket connection.
|
|
1341
|
-
*
|
|
1342
|
-
* Removes the record from `ConnectionRegistry`, clears all room membership
|
|
1343
|
-
* from `RoomRegistry`, and fires the `onDisconnect` lifecycle hook with the
|
|
1344
|
-
* computed `durationMs`.
|
|
1345
|
-
*
|
|
1346
|
-
* @param connectionId - The Socket.IO socket `id` of the disconnected connection.
|
|
1347
|
-
* @param reason - Optional reason string forwarded to the `onDisconnect` hook.
|
|
1348
|
-
*/
|
|
1349
|
-
async unregisterSocket(connectionId, reason) {
|
|
1350
|
-
const record = this.connections.unregister(connectionId);
|
|
1351
|
-
if (!record) return;
|
|
1352
|
-
this.rooms.leaveAll(connectionId);
|
|
1353
|
-
const disconnectMeta = {
|
|
1354
|
-
connectionId,
|
|
1355
|
-
userId: record.userId,
|
|
1356
|
-
tenantId: record.tenantId,
|
|
1357
|
-
transport: "websocket",
|
|
1358
|
-
ip: record.ip,
|
|
1359
|
-
userAgent: record.userAgent,
|
|
1360
|
-
connectedAt: record.connectedAt,
|
|
1361
|
-
durationMs: Date.now() - record.connectedAt.getTime(),
|
|
1362
|
-
...reason !== void 0 ? { reason } : {}
|
|
1363
|
-
};
|
|
1364
|
-
await this.hooks.onDisconnect?.(disconnectMeta);
|
|
1365
|
-
}
|
|
1366
|
-
/**
|
|
1367
|
-
* Send an event to every connection of a user (uses `user:{userId}` room).
|
|
1368
|
-
*
|
|
1369
|
-
* @param userId - Target user identifier.
|
|
1370
|
-
* @param event - Event name to emit.
|
|
1371
|
-
* @param data - Payload forwarded to all matching connections.
|
|
1372
|
-
*/
|
|
1373
|
-
async emitToUser(userId, event, data) {
|
|
1374
|
-
this.server?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
|
|
1375
|
-
}
|
|
1376
|
-
/**
|
|
1377
|
-
* Send an event to every connection within a tenant (uses `tenant:{tenantId}` room).
|
|
1378
|
-
*
|
|
1379
|
-
* @param tenantId - Target tenant identifier.
|
|
1380
|
-
* @param event - Event name to emit.
|
|
1381
|
-
* @param data - Payload forwarded to all matching connections.
|
|
1382
|
-
*/
|
|
1383
|
-
async emitToTenant(tenantId, event, data) {
|
|
1384
|
-
this.server?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
|
|
1385
|
-
}
|
|
1386
|
-
/**
|
|
1387
|
-
* Send an event to every connection in an arbitrary room.
|
|
1388
|
-
*
|
|
1389
|
-
* @param roomId - The fully-qualified room identifier (e.g., `user:u-1`, `tenant:t-1`).
|
|
1390
|
-
* @param event - Event name to emit.
|
|
1391
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
1392
|
-
*/
|
|
1393
|
-
async emitToRoom(roomId, event, data) {
|
|
1394
|
-
this.server?.to(roomId).emit(event, data);
|
|
1395
|
-
}
|
|
1396
|
-
/**
|
|
1397
|
-
* Broadcast an event to all connected clients.
|
|
1398
|
-
*
|
|
1399
|
-
* @param event - Event name to emit.
|
|
1400
|
-
* @param data - Payload forwarded to every connected socket.
|
|
1401
|
-
*/
|
|
1402
|
-
async broadcast(event, data) {
|
|
1403
|
-
this.server?.emit(event, data);
|
|
1404
|
-
}
|
|
1405
|
-
/**
|
|
1406
|
-
* Join a connection to an additional room (updates both Socket.IO and `RoomRegistry`).
|
|
1407
|
-
*
|
|
1408
|
-
* @param connectionId - The socket `id` of the connection to join.
|
|
1409
|
-
* @param roomId - The room to join.
|
|
1410
|
-
*/
|
|
1411
|
-
async joinRoom(connectionId, roomId) {
|
|
1412
|
-
const socket = this.localSockets()?.get(connectionId);
|
|
1413
|
-
if (socket) {
|
|
1414
|
-
await socket.join(roomId);
|
|
1415
|
-
this.rooms.join(connectionId, roomId);
|
|
1416
|
-
}
|
|
1417
|
-
}
|
|
1418
|
-
/**
|
|
1419
|
-
* Remove a connection from a room (updates both Socket.IO and `RoomRegistry`).
|
|
1420
|
-
*
|
|
1421
|
-
* @param connectionId - The socket `id` of the connection to remove.
|
|
1422
|
-
* @param roomId - The room to leave.
|
|
1423
|
-
*/
|
|
1424
|
-
async leaveRoom(connectionId, roomId) {
|
|
1425
|
-
const socket = this.localSockets()?.get(connectionId);
|
|
1426
|
-
if (socket) {
|
|
1427
|
-
await socket.leave(roomId);
|
|
1428
|
-
this.rooms.leave(connectionId, roomId);
|
|
1429
|
-
}
|
|
1430
|
-
}
|
|
1431
|
-
/**
|
|
1432
|
-
* Force-disconnect a specific connection — adapter-aware, so revocation works
|
|
1433
|
-
* across nodes.
|
|
1434
|
-
*
|
|
1435
|
-
* A socket local to this node is closed directly as a fast path. Regardless,
|
|
1436
|
-
* `disconnectSockets` is broadcast to the connection's `connection:{id}` room:
|
|
1437
|
-
* under `@socket.io/redis-adapter` this fans out to remote nodes, so a
|
|
1438
|
-
* connection pinned to another instance is still force-closed. The local socket
|
|
1439
|
-
* has already left the room by then, so the broadcast does not double-close it.
|
|
1440
|
-
*
|
|
1441
|
-
* @param connectionId - The socket `id` of the connection to disconnect.
|
|
1442
|
-
* @param _reason - Optional reason string (unused at the Socket.IO level; passed to `unregisterSocket`).
|
|
1443
|
-
*/
|
|
1444
|
-
async disconnect(connectionId, _reason) {
|
|
1445
|
-
const server = this.server;
|
|
1446
|
-
if (!server) return;
|
|
1447
|
-
const local = this.localSockets()?.get(connectionId);
|
|
1448
|
-
if (local) local.disconnect(true);
|
|
1449
|
-
server.in(`${CONNECTION_ROOM_PREFIX}:${connectionId}`).disconnectSockets(true);
|
|
1450
|
-
}
|
|
1451
|
-
/**
|
|
1452
|
-
* Evict the user's oldest WebSocket connections (FIFO) when over
|
|
1453
|
-
* `websocket.maxConnectionsPerUser`. Emits `REALTIME_TOO_MANY_CONNECTIONS`
|
|
1454
|
-
* as the disconnect reason — never rejects the new connection with HTTP 429.
|
|
1455
|
-
*/
|
|
1456
|
-
async evictBeyondLimit(userId) {
|
|
1457
|
-
const max = this.options.websocket?.maxConnectionsPerUser;
|
|
1458
|
-
if (max === void 0 || max <= 0) return;
|
|
1459
|
-
let userConnections = this.connections.byUser(userId, "websocket");
|
|
1460
|
-
while (userConnections.length > max) {
|
|
1461
|
-
const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
|
|
1462
|
-
await this.disconnect(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
1463
|
-
await this.unregisterSocket(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
1464
|
-
userConnections = this.connections.byUser(userId, "websocket");
|
|
1465
|
-
}
|
|
1466
|
-
}
|
|
1467
|
-
};
|
|
1468
|
-
WebSocketTransport = __decorateClass([
|
|
1469
|
-
Injectable(),
|
|
1470
|
-
__decorateParam(0, Inject(ConnectionRegistry)),
|
|
1471
|
-
__decorateParam(1, Inject(RoomRegistry)),
|
|
1472
|
-
__decorateParam(2, Inject(REALTIME_AUTHENTICATOR_TOKEN)),
|
|
1473
|
-
__decorateParam(3, Inject(REALTIME_HOOKS_TOKEN)),
|
|
1474
|
-
__decorateParam(4, Inject(REALTIME_OPTIONS_TOKEN))
|
|
1475
|
-
], WebSocketTransport);
|
|
1476
|
-
function firstQueryValue(value) {
|
|
1477
|
-
return Array.isArray(value) ? value[0] : value;
|
|
1478
|
-
}
|
|
1479
|
-
var RealtimeGateway = class {
|
|
1480
|
-
constructor(transport, options) {
|
|
1481
|
-
this.transport = transport;
|
|
1482
|
-
this.options = options;
|
|
1483
|
-
}
|
|
1484
|
-
transport;
|
|
1485
|
-
options;
|
|
1486
|
-
logger = new Logger(RealtimeGateway.name);
|
|
1487
|
-
server;
|
|
1488
|
-
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
1489
|
-
afterInit(server) {
|
|
1490
|
-
this.transport.setServer(server);
|
|
1491
|
-
this.logger.log("RealtimeGateway initialized");
|
|
1492
|
-
}
|
|
1493
|
-
/**
|
|
1494
|
-
* Handle a new WebSocket connection.
|
|
1495
|
-
*
|
|
1496
|
-
* Builds a `ConnectionAuthContext` from the Socket.IO handshake, merging the
|
|
1497
|
-
* three supported auth patterns (spec §8.1):
|
|
1498
|
-
* - Cookie HttpOnly — extracted via `parseCookieHeader`.
|
|
1499
|
-
* - Ticket — available in `ctx.query.ticket` or via `auth.ticket`.
|
|
1500
|
-
* - Bearer header — available in `headers.authorization` or via `auth.token`.
|
|
1501
|
-
*
|
|
1502
|
-
* `socket.handshake.auth.token` and `.ticket` are the Socket.IO-idiomatic paths
|
|
1503
|
-
* (set via `io(url, { auth: { token } })`); the gateway normalizes them into the
|
|
1504
|
-
* context so the authenticator sees a single unified shape regardless of client.
|
|
1505
|
-
*
|
|
1506
|
-
* Query values follow the Node `ParsedUrlQuery` shape (`string | string[] |
|
|
1507
|
-
* undefined`); the single-value `ticket` parameter is collapsed to its first
|
|
1508
|
-
* element so the authenticator receives a well-defined string.
|
|
1509
|
-
*
|
|
1510
|
-
* Fail-closed: any thrown error disconnects the socket immediately so it cannot
|
|
1511
|
-
* linger in an unregistered state and receive broadcast events.
|
|
1512
|
-
*/
|
|
1513
|
-
async handleConnection(socket) {
|
|
1514
|
-
try {
|
|
1515
|
-
const { handshake } = socket;
|
|
1516
|
-
const headers = this.normalizeHeaders(handshake.headers);
|
|
1517
|
-
const query = { ...handshake.query };
|
|
1518
|
-
const handshakeAuth = handshake.auth;
|
|
1519
|
-
if (handshakeAuth?.token) headers["authorization"] = `Bearer ${handshakeAuth.token}`;
|
|
1520
|
-
if (handshakeAuth?.ticket) query["ticket"] = handshakeAuth.ticket;
|
|
1521
|
-
const ticket = firstQueryValue(query["ticket"]);
|
|
1522
|
-
if (ticket !== void 0) query["ticket"] = ticket;
|
|
1523
|
-
const ctx = {
|
|
1524
|
-
cookies: parseCookieHeader(handshake.headers.cookie ?? ""),
|
|
1525
|
-
headers,
|
|
1526
|
-
query,
|
|
1527
|
-
ip: handshake.address,
|
|
1528
|
-
userAgent: handshake.headers["user-agent"],
|
|
1529
|
-
transport: "websocket"
|
|
1530
|
-
};
|
|
1531
|
-
const auth = await this.transport.authenticator().authenticate(ctx);
|
|
1532
|
-
if (!auth) {
|
|
1533
|
-
socket.disconnect(true);
|
|
1534
|
-
return;
|
|
1535
|
-
}
|
|
1536
|
-
await this.transport.registerSocket(socket, auth);
|
|
1537
|
-
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
1538
|
-
socket.emit(RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
1539
|
-
connectionId: socket.id,
|
|
1540
|
-
traits: { userId: auth.userId, tenantId: auth.tenantId, roles: auth.roles }
|
|
1541
|
-
});
|
|
1542
|
-
}
|
|
1543
|
-
} catch (err) {
|
|
1544
|
-
this.logger.error(
|
|
1545
|
-
`handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
|
|
1546
|
-
);
|
|
1547
|
-
socket.disconnect(true);
|
|
1548
|
-
}
|
|
1549
|
-
}
|
|
1550
|
-
/** Handle a WebSocket disconnection — unregister the connection. */
|
|
1551
|
-
async handleDisconnect(socket) {
|
|
1552
|
-
await this.transport.unregisterSocket(socket.id, "CLIENT_DISCONNECT");
|
|
1553
|
-
}
|
|
1554
|
-
/**
|
|
1555
|
-
* Normalize raw Socket.IO handshake headers into a plain lowercase-keyed map.
|
|
1556
|
-
*
|
|
1557
|
-
* Array header values (e.g. `Set-Cookie`) are joined with `,` to produce a
|
|
1558
|
-
* single string, matching the shape expected by `ConnectionAuthContext.headers`.
|
|
1559
|
-
*/
|
|
1560
|
-
normalizeHeaders(input) {
|
|
1561
|
-
const out = {};
|
|
1562
|
-
for (const [k, v] of Object.entries(input)) {
|
|
1563
|
-
out[k.toLowerCase()] = Array.isArray(v) ? v.join(",") : v;
|
|
1564
|
-
}
|
|
1565
|
-
return out;
|
|
1566
|
-
}
|
|
1567
|
-
};
|
|
1568
|
-
__decorateClass([
|
|
1569
|
-
WebSocketServer()
|
|
1570
|
-
], RealtimeGateway.prototype, "server", 2);
|
|
1571
|
-
RealtimeGateway = __decorateClass([
|
|
1572
|
-
WebSocketGateway({
|
|
1573
|
-
cors: { origin: false }
|
|
1574
|
-
}),
|
|
1575
|
-
__decorateParam(0, Inject(WebSocketTransport)),
|
|
1576
|
-
__decorateParam(1, Inject(REALTIME_OPTIONS_TOKEN))
|
|
1577
|
-
], RealtimeGateway);
|
|
1578
|
-
var CompositeTransport = class {
|
|
1579
|
-
constructor(sse, ws) {
|
|
1580
|
-
this.sse = sse;
|
|
1581
|
-
this.ws = ws;
|
|
1582
|
-
}
|
|
1583
|
-
sse;
|
|
1584
|
-
ws;
|
|
1585
|
-
kind = "sse";
|
|
1586
|
-
logger = new Logger(CompositeTransport.name);
|
|
1587
|
-
/**
|
|
1588
|
-
* Emit to all connections of a user across both transports.
|
|
1589
|
-
*
|
|
1590
|
-
* @param userId - Target user identifier.
|
|
1591
|
-
* @param event - Event name to emit.
|
|
1592
|
-
* @param data - Payload forwarded to all matching connections.
|
|
1593
|
-
*/
|
|
1594
|
-
async emitToUser(userId, event, data) {
|
|
1595
|
-
await this.fanOut(
|
|
1596
|
-
"emitToUser",
|
|
1597
|
-
() => this.sse.emitToUser(userId, event, data),
|
|
1598
|
-
() => this.ws.emitToUser(userId, event, data)
|
|
1599
|
-
);
|
|
1600
|
-
}
|
|
1601
|
-
/**
|
|
1602
|
-
* Emit to all connections within a tenant across both transports.
|
|
1603
|
-
*
|
|
1604
|
-
* @param tenantId - Target tenant identifier.
|
|
1605
|
-
* @param event - Event name to emit.
|
|
1606
|
-
* @param data - Payload forwarded to all matching connections.
|
|
1607
|
-
*/
|
|
1608
|
-
async emitToTenant(tenantId, event, data) {
|
|
1609
|
-
await this.fanOut(
|
|
1610
|
-
"emitToTenant",
|
|
1611
|
-
() => this.sse.emitToTenant(tenantId, event, data),
|
|
1612
|
-
() => this.ws.emitToTenant(tenantId, event, data)
|
|
1613
|
-
);
|
|
1614
|
-
}
|
|
1615
|
-
/**
|
|
1616
|
-
* Emit to all connections in a room across both transports.
|
|
1617
|
-
*
|
|
1618
|
-
* @param roomId - The fully-qualified room identifier.
|
|
1619
|
-
* @param event - Event name to emit.
|
|
1620
|
-
* @param data - Payload forwarded to all connections in the room.
|
|
1621
|
-
*/
|
|
1622
|
-
async emitToRoom(roomId, event, data) {
|
|
1623
|
-
await this.fanOut(
|
|
1624
|
-
"emitToRoom",
|
|
1625
|
-
() => this.sse.emitToRoom(roomId, event, data),
|
|
1626
|
-
() => this.ws.emitToRoom(roomId, event, data)
|
|
1627
|
-
);
|
|
1628
|
-
}
|
|
1629
|
-
/**
|
|
1630
|
-
* Broadcast to all connected clients across both transports.
|
|
1631
|
-
*
|
|
1632
|
-
* @param event - Event name to emit.
|
|
1633
|
-
* @param data - Payload forwarded to every connected client.
|
|
1634
|
-
*/
|
|
1635
|
-
async broadcast(event, data) {
|
|
1636
|
-
await this.fanOut(
|
|
1637
|
-
"broadcast",
|
|
1638
|
-
() => this.sse.broadcast(event, data),
|
|
1639
|
-
() => this.ws.broadcast(event, data)
|
|
1640
|
-
);
|
|
1641
|
-
}
|
|
1642
|
-
/**
|
|
1643
|
-
* Join a connection to a room.
|
|
1644
|
-
*
|
|
1645
|
-
* Both transports are attempted; only the one that owns the connection
|
|
1646
|
-
* succeeds. The other's failure is expected and swallowed.
|
|
1647
|
-
*/
|
|
1648
|
-
async joinRoom(connectionId, roomId) {
|
|
1649
|
-
await Promise.all([
|
|
1650
|
-
this.sse.joinRoom(connectionId, roomId).catch(() => void 0),
|
|
1651
|
-
this.ws.joinRoom(connectionId, roomId).catch(() => void 0)
|
|
1652
|
-
]);
|
|
1653
|
-
}
|
|
1654
|
-
/**
|
|
1655
|
-
* Remove a connection from a room.
|
|
1656
|
-
*
|
|
1657
|
-
* Both transports are attempted tolerantly — one will succeed, the other
|
|
1658
|
-
* may fail silently.
|
|
1659
|
-
*/
|
|
1660
|
-
async leaveRoom(connectionId, roomId) {
|
|
1661
|
-
await Promise.all([
|
|
1662
|
-
this.sse.leaveRoom(connectionId, roomId).catch(() => void 0),
|
|
1663
|
-
this.ws.leaveRoom(connectionId, roomId).catch(() => void 0)
|
|
1664
|
-
]);
|
|
1665
|
-
}
|
|
1666
|
-
/**
|
|
1667
|
-
* Disconnect a specific connection.
|
|
1668
|
-
*
|
|
1669
|
-
* Both transports are attempted; the one owning the connection disconnects it.
|
|
1670
|
-
*/
|
|
1671
|
-
async disconnect(connectionId, reason) {
|
|
1672
|
-
await Promise.all([
|
|
1673
|
-
this.sse.disconnect(connectionId, reason).catch(() => void 0),
|
|
1674
|
-
this.ws.disconnect(connectionId, reason).catch(() => void 0)
|
|
1675
|
-
]);
|
|
1676
|
-
}
|
|
1677
|
-
/**
|
|
1678
|
-
* Run two transport tasks in parallel via `Promise.allSettled`.
|
|
1679
|
-
*
|
|
1680
|
-
* A rejection in either task is logged as a warning and does not propagate,
|
|
1681
|
-
* ensuring one failing transport never blocks delivery on the other.
|
|
1682
|
-
*/
|
|
1683
|
-
async fanOut(op, ...tasks) {
|
|
1684
|
-
const results = await Promise.allSettled(tasks.map((t) => t()));
|
|
1685
|
-
for (const result of results) {
|
|
1686
|
-
if (result.status === "rejected") {
|
|
1687
|
-
this.logger.warn(
|
|
1688
|
-
`Composite ${op} partially failed: ${result.reason.message ?? result.reason}`
|
|
1689
|
-
);
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
}
|
|
1693
|
-
};
|
|
1694
|
-
CompositeTransport = __decorateClass([
|
|
1695
|
-
Injectable(),
|
|
1696
|
-
__decorateParam(0, Inject(SseTransport)),
|
|
1697
|
-
__decorateParam(1, Inject(WebSocketTransport))
|
|
1698
|
-
], CompositeTransport);
|
|
1699
1156
|
|
|
1700
|
-
// src/server/realtime
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1157
|
+
// src/server/composition/realtime-module.factory.ts
|
|
1158
|
+
var EXPORTED_TOKENS = [
|
|
1159
|
+
RealtimeService,
|
|
1160
|
+
ConnectionRegistry,
|
|
1161
|
+
REALTIME_OPTIONS_TOKEN,
|
|
1162
|
+
REALTIME_INSTANCE_ID_TOKEN,
|
|
1163
|
+
REALTIME_AUTHENTICATOR_TOKEN,
|
|
1164
|
+
REALTIME_PUBSUB_TOKEN,
|
|
1165
|
+
REALTIME_HOOKS_TOKEN,
|
|
1166
|
+
REALTIME_OFFLINE_QUEUE_TOKEN,
|
|
1167
|
+
REALTIME_PRESENCE_TOKEN,
|
|
1168
|
+
REALTIME_TRANSPORT_TOKEN
|
|
1169
|
+
];
|
|
1170
|
+
var SHARED_SERVICES = [
|
|
1171
|
+
ConnectionRegistry,
|
|
1172
|
+
RoomRegistry,
|
|
1173
|
+
EventIdGenerator,
|
|
1174
|
+
EventReplayBuffer,
|
|
1175
|
+
HeartbeatService,
|
|
1176
|
+
RealtimeService,
|
|
1177
|
+
ReauthenticationService,
|
|
1178
|
+
OfflineQueueDeliveryService
|
|
1179
|
+
];
|
|
1180
|
+
function assertModeSupported(wiring, mode, moduleName) {
|
|
1181
|
+
if (wiring.modes.includes(mode)) return;
|
|
1182
|
+
const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
|
|
1183
|
+
throw new Error(
|
|
1184
|
+
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
function warnIfSingleInstance(pubsub, transport, logger) {
|
|
1188
|
+
if (transport === "websocket") return;
|
|
1189
|
+
if (!pubsub && process.env["NODE_ENV"] === "production") {
|
|
1190
|
+
logger.warn(
|
|
1191
|
+
"No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
|
|
1708
1192
|
);
|
|
1709
1193
|
}
|
|
1710
1194
|
}
|
|
@@ -1717,66 +1201,173 @@ function buildCommonProviders(resolved, instanceId) {
|
|
|
1717
1201
|
{ provide: REALTIME_HOOKS_TOKEN, useValue: resolved.hooks ?? {} },
|
|
1718
1202
|
{ provide: REALTIME_OFFLINE_QUEUE_TOKEN, useValue: resolved.offlineQueue },
|
|
1719
1203
|
{ provide: REALTIME_PRESENCE_TOKEN, useValue: resolved.presence },
|
|
1720
|
-
|
|
1721
|
-
RoomRegistry,
|
|
1722
|
-
EventIdGenerator,
|
|
1723
|
-
EventReplayBuffer,
|
|
1724
|
-
HeartbeatService,
|
|
1725
|
-
RealtimeService,
|
|
1726
|
-
ReauthenticationService,
|
|
1727
|
-
OfflineQueueDeliveryService
|
|
1204
|
+
...SHARED_SERVICES
|
|
1728
1205
|
];
|
|
1729
1206
|
}
|
|
1730
|
-
function
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
const
|
|
1734
|
-
const
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
providers
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1207
|
+
function composeForRoot(moduleClass, wiring, logger, options) {
|
|
1208
|
+
validateOptions(options);
|
|
1209
|
+
assertModeSupported(wiring, options.transport, moduleClass.name);
|
|
1210
|
+
const resolved = applyDefaults(options);
|
|
1211
|
+
const instanceId = randomUUID();
|
|
1212
|
+
warnIfSingleInstance(resolved.pubsub, resolved.transport, logger);
|
|
1213
|
+
const { providers, endpoints, gateways } = wiring.build(resolved);
|
|
1214
|
+
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
1215
|
+
return {
|
|
1216
|
+
module: moduleClass,
|
|
1217
|
+
controllers: endpoints.map((endpoint) => createSseController(endpoint)),
|
|
1218
|
+
providers: [...buildCommonProviders(resolved, instanceId), ...providers, ...gateways],
|
|
1219
|
+
exports: EXPORTED_TOKENS
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
|
|
1223
|
+
if (!raw) {
|
|
1224
|
+
throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
|
|
1225
|
+
}
|
|
1226
|
+
validateOptions(raw);
|
|
1227
|
+
if (raw.transport !== declaredMode) {
|
|
1228
|
+
throw new Error(
|
|
1229
|
+
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
|
|
1752
1230
|
);
|
|
1753
|
-
providers.push({ provide: REALTIME_TRANSPORT_TOKEN, useExisting: CompositeTransport });
|
|
1754
|
-
controllers.push(resolved.sse.endpoint);
|
|
1755
|
-
gateways.push(RealtimeGateway);
|
|
1756
1231
|
}
|
|
1757
|
-
|
|
1232
|
+
const resolved = applyDefaults(raw);
|
|
1233
|
+
logger.log(`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`);
|
|
1234
|
+
return resolved;
|
|
1758
1235
|
}
|
|
1759
|
-
function
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1236
|
+
function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
1237
|
+
const moduleName = moduleClass.name;
|
|
1238
|
+
const patterns = [
|
|
1239
|
+
asyncOptions.useFactory,
|
|
1240
|
+
asyncOptions.useClass,
|
|
1241
|
+
asyncOptions.useExisting
|
|
1242
|
+
].filter((pattern) => pattern !== void 0);
|
|
1243
|
+
if (patterns.length !== 1) {
|
|
1244
|
+
throw new Error(
|
|
1245
|
+
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
1249
|
+
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
1250
|
+
const instanceId = randomUUID();
|
|
1251
|
+
const resolve = (raw, source) => resolveAsyncOptions(raw, asyncOptions.transport, instanceId, source, logger, moduleName);
|
|
1252
|
+
const resolvedOptionsProvider = asyncOptions.useFactory ? {
|
|
1253
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
1254
|
+
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
1255
|
+
inject: [...asyncOptions.inject ?? []]
|
|
1256
|
+
} : {
|
|
1257
|
+
provide: REALTIME_OPTIONS_TOKEN,
|
|
1258
|
+
useFactory: async (factory) => resolve(
|
|
1259
|
+
await factory.createRealtimeOptions(),
|
|
1260
|
+
"createRealtimeOptions"
|
|
1261
|
+
),
|
|
1262
|
+
inject: [asyncOptions.useExisting ?? FACTORY_TOKEN]
|
|
1263
|
+
};
|
|
1264
|
+
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
1265
|
+
const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
|
|
1266
|
+
const { providers: transportProviders, controllers } = wiring.buildAsync(asyncOptions.transport);
|
|
1267
|
+
return {
|
|
1268
|
+
module: moduleClass,
|
|
1269
|
+
imports: asyncOptions.imports ?? [],
|
|
1270
|
+
controllers,
|
|
1271
|
+
providers: [
|
|
1272
|
+
...factoryClassProvider,
|
|
1273
|
+
resolvedOptionsProvider,
|
|
1274
|
+
fromOptions(REALTIME_AUTHENTICATOR_TOKEN, (opts) => opts.authenticator),
|
|
1275
|
+
fromOptions(REALTIME_PUBSUB_TOKEN, (opts) => {
|
|
1276
|
+
warnIfSingleInstance(opts.pubsub, opts.transport, logger);
|
|
1277
|
+
return opts.pubsub ?? new InMemoryPubSub();
|
|
1278
|
+
}),
|
|
1279
|
+
fromOptions(REALTIME_HOOKS_TOKEN, (opts) => opts.hooks ?? {}),
|
|
1280
|
+
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
1281
|
+
fromOptions(REALTIME_OFFLINE_QUEUE_TOKEN, (opts) => opts.offlineQueue),
|
|
1282
|
+
fromOptions(REALTIME_PRESENCE_TOKEN, (opts) => opts.presence),
|
|
1283
|
+
...SHARED_SERVICES,
|
|
1284
|
+
...transportProviders,
|
|
1285
|
+
...asyncOptions.extraProviders ?? []
|
|
1286
|
+
],
|
|
1287
|
+
exports: EXPORTED_TOKENS
|
|
1288
|
+
};
|
|
1777
1289
|
}
|
|
1778
|
-
|
|
1779
|
-
|
|
1290
|
+
var RealtimePubSubSubscriber = class {
|
|
1291
|
+
constructor(pubsub, instanceId, sse) {
|
|
1292
|
+
this.pubsub = pubsub;
|
|
1293
|
+
this.instanceId = instanceId;
|
|
1294
|
+
this.sse = sse;
|
|
1295
|
+
}
|
|
1296
|
+
pubsub;
|
|
1297
|
+
instanceId;
|
|
1298
|
+
sse;
|
|
1299
|
+
logger = new Logger(RealtimePubSubSubscriber.name);
|
|
1300
|
+
unsubscribe = null;
|
|
1301
|
+
async onModuleInit() {
|
|
1302
|
+
try {
|
|
1303
|
+
this.unsubscribe = await this.pubsub.subscribe((msg) => this.handle(msg));
|
|
1304
|
+
} catch (err) {
|
|
1305
|
+
this.logger.warn(
|
|
1306
|
+
`Failed to subscribe to pub/sub: ${err.message}. Cross-instance fan-out disabled; remote events will not reach this instance.`
|
|
1307
|
+
);
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
async onApplicationShutdown() {
|
|
1311
|
+
if (this.unsubscribe) {
|
|
1312
|
+
try {
|
|
1313
|
+
await this.unsubscribe();
|
|
1314
|
+
} catch (err) {
|
|
1315
|
+
this.logger.warn(`Pub/sub unsubscribe failed: ${err.message}`);
|
|
1316
|
+
}
|
|
1317
|
+
this.unsubscribe = null;
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
handle(msg) {
|
|
1321
|
+
if (msg.origin === this.instanceId) return;
|
|
1322
|
+
try {
|
|
1323
|
+
switch (msg.op) {
|
|
1324
|
+
case "emitToUser": {
|
|
1325
|
+
const a = msg.args;
|
|
1326
|
+
this.sse.emitToUserLocal(a.userId, a.event, a.data, a.id);
|
|
1327
|
+
break;
|
|
1328
|
+
}
|
|
1329
|
+
case "emitToTenant": {
|
|
1330
|
+
const a = msg.args;
|
|
1331
|
+
this.sse.emitToTenantLocal(a.tenantId, a.event, a.data, a.id);
|
|
1332
|
+
break;
|
|
1333
|
+
}
|
|
1334
|
+
case "emitToRoom": {
|
|
1335
|
+
const a = msg.args;
|
|
1336
|
+
this.sse.emitToRoomLocal(a.roomId, a.event, a.data, a.id);
|
|
1337
|
+
break;
|
|
1338
|
+
}
|
|
1339
|
+
case "broadcast": {
|
|
1340
|
+
const a = msg.args;
|
|
1341
|
+
this.sse.broadcastLocal(a.event, a.data, a.id);
|
|
1342
|
+
break;
|
|
1343
|
+
}
|
|
1344
|
+
case "disconnect": {
|
|
1345
|
+
const a = msg.args;
|
|
1346
|
+
void this.sse.disconnectLocal(a.connectionId, a.reason);
|
|
1347
|
+
break;
|
|
1348
|
+
}
|
|
1349
|
+
default: {
|
|
1350
|
+
const exhaustive = msg.op;
|
|
1351
|
+
this.logger.warn(`Unknown pub/sub op: ${String(exhaustive)}`);
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
} catch (err) {
|
|
1355
|
+
this.logger.warn(`Pub/sub message handling failed: ${err.message}`);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
};
|
|
1359
|
+
RealtimePubSubSubscriber = __decorateClass([
|
|
1360
|
+
Injectable(),
|
|
1361
|
+
__decorateParam(0, Inject(REALTIME_PUBSUB_TOKEN)),
|
|
1362
|
+
__decorateParam(1, Inject(REALTIME_INSTANCE_ID_TOKEN)),
|
|
1363
|
+
__decorateParam(2, Inject(SseTransport))
|
|
1364
|
+
], RealtimePubSubSubscriber);
|
|
1365
|
+
|
|
1366
|
+
// src/server/composition/sse-wiring.ts
|
|
1367
|
+
var DEFAULT_ASYNC_ENDPOINT = "/events";
|
|
1368
|
+
var sseWiring = {
|
|
1369
|
+
modes: ["sse"],
|
|
1370
|
+
build(resolved) {
|
|
1780
1371
|
return {
|
|
1781
1372
|
providers: [
|
|
1782
1373
|
SseTransport,
|
|
@@ -1784,68 +1375,29 @@ function buildAsyncTransportProviders(mode) {
|
|
|
1784
1375
|
RealtimePubSubSubscriber,
|
|
1785
1376
|
{ provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
|
|
1786
1377
|
],
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
}
|
|
1790
|
-
if (mode === "websocket") {
|
|
1791
|
-
assertWsPeerDeps();
|
|
1792
|
-
return {
|
|
1793
|
-
providers: [
|
|
1794
|
-
WebSocketTransport,
|
|
1795
|
-
RealtimeGateway,
|
|
1796
|
-
{ provide: REALTIME_TRANSPORT_TOKEN, useExisting: WebSocketTransport }
|
|
1797
|
-
],
|
|
1798
|
-
controllers: []
|
|
1378
|
+
endpoints: [resolved.sse.endpoint],
|
|
1379
|
+
gateways: []
|
|
1799
1380
|
};
|
|
1800
|
-
}
|
|
1801
|
-
|
|
1802
|
-
assertWsPeerDeps();
|
|
1381
|
+
},
|
|
1382
|
+
buildAsync() {
|
|
1803
1383
|
return {
|
|
1804
1384
|
providers: [
|
|
1805
1385
|
SseTransport,
|
|
1806
1386
|
SseSubscriptionHandler,
|
|
1807
|
-
WebSocketTransport,
|
|
1808
|
-
CompositeTransport,
|
|
1809
|
-
RealtimeGateway,
|
|
1810
1387
|
RealtimePubSubSubscriber,
|
|
1811
|
-
{ provide: REALTIME_TRANSPORT_TOKEN, useExisting:
|
|
1388
|
+
{ provide: REALTIME_TRANSPORT_TOKEN, useExisting: SseTransport }
|
|
1812
1389
|
],
|
|
1813
|
-
controllers: [createSseController(
|
|
1390
|
+
controllers: [createSseController(DEFAULT_ASYNC_ENDPOINT)]
|
|
1814
1391
|
};
|
|
1815
1392
|
}
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
};
|
|
1820
|
-
}
|
|
1393
|
+
};
|
|
1394
|
+
|
|
1395
|
+
// src/server/realtime.module.ts
|
|
1821
1396
|
var BymaxRealtimeModule = class {
|
|
1822
|
-
/**
|
|
1823
|
-
* Validate a raw async factory result, enforce the optional synchronous
|
|
1824
|
-
* `transport` hint, apply defaults, and log the bootstrap line.
|
|
1825
|
-
*
|
|
1826
|
-
* @throws when the factory returned nothing, the options are invalid, or the
|
|
1827
|
-
* resolved transport disagrees with the synchronous hint used to gate
|
|
1828
|
-
* provider registration.
|
|
1829
|
-
*/
|
|
1830
|
-
static resolveAsyncOptions(raw, transportHint, instanceId, source) {
|
|
1831
|
-
if (!raw) {
|
|
1832
|
-
throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
|
|
1833
|
-
}
|
|
1834
|
-
validateOptions(raw);
|
|
1835
|
-
if (transportHint !== void 0 && raw.transport !== transportHint) {
|
|
1836
|
-
throw new Error(
|
|
1837
|
-
`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync transport hint '${transportHint}' does not match the resolved transport '${raw.transport}'`
|
|
1838
|
-
);
|
|
1839
|
-
}
|
|
1840
|
-
const resolved = applyDefaults(raw);
|
|
1841
|
-
BymaxRealtimeModule.logger.log(
|
|
1842
|
-
`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`
|
|
1843
|
-
);
|
|
1844
|
-
return resolved;
|
|
1845
|
-
}
|
|
1846
1397
|
/**
|
|
1847
1398
|
* Configure the module synchronously.
|
|
1848
1399
|
*
|
|
1400
|
+
* @throws when the options are invalid.
|
|
1849
1401
|
* @example
|
|
1850
1402
|
* ```ts
|
|
1851
1403
|
* BymaxRealtimeModule.forRoot({
|
|
@@ -1855,180 +1407,42 @@ var BymaxRealtimeModule = class {
|
|
|
1855
1407
|
* ```
|
|
1856
1408
|
*/
|
|
1857
1409
|
static forRoot(options) {
|
|
1858
|
-
|
|
1859
|
-
const resolved = applyDefaults(options);
|
|
1860
|
-
const instanceId = randomUUID();
|
|
1861
|
-
if (!resolved.pubsub && process.env["NODE_ENV"] === "production") {
|
|
1862
|
-
BymaxRealtimeModule.logger.warn(
|
|
1863
|
-
"No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
|
|
1864
|
-
);
|
|
1865
|
-
}
|
|
1866
|
-
const common = buildCommonProviders(resolved, instanceId);
|
|
1867
|
-
const {
|
|
1868
|
-
providers: transportProviders,
|
|
1869
|
-
controllers,
|
|
1870
|
-
gateways
|
|
1871
|
-
} = buildTransportProviders(resolved);
|
|
1872
|
-
BymaxRealtimeModule.logger.log(
|
|
1873
|
-
`Bootstrapped (transport=${resolved.transport}, instanceId=${instanceId})`
|
|
1874
|
-
);
|
|
1875
|
-
return {
|
|
1876
|
-
module: BymaxRealtimeModule,
|
|
1877
|
-
controllers: controllers.map((ep) => createSseController(ep)),
|
|
1878
|
-
providers: [...common, ...transportProviders, ...gateways],
|
|
1879
|
-
exports: [
|
|
1880
|
-
RealtimeService,
|
|
1881
|
-
ConnectionRegistry,
|
|
1882
|
-
REALTIME_OPTIONS_TOKEN,
|
|
1883
|
-
REALTIME_INSTANCE_ID_TOKEN,
|
|
1884
|
-
REALTIME_AUTHENTICATOR_TOKEN,
|
|
1885
|
-
REALTIME_PUBSUB_TOKEN,
|
|
1886
|
-
REALTIME_HOOKS_TOKEN,
|
|
1887
|
-
REALTIME_OFFLINE_QUEUE_TOKEN,
|
|
1888
|
-
REALTIME_PRESENCE_TOKEN,
|
|
1889
|
-
REALTIME_TRANSPORT_TOKEN
|
|
1890
|
-
]
|
|
1891
|
-
};
|
|
1410
|
+
return composeForRoot(BymaxRealtimeModule, sseWiring, BymaxRealtimeModule.logger, options);
|
|
1892
1411
|
}
|
|
1893
1412
|
/**
|
|
1894
|
-
* Configure the module asynchronously so
|
|
1895
|
-
*
|
|
1896
|
-
* client, etc.
|
|
1413
|
+
* Configure the module asynchronously so options — and the authenticator —
|
|
1414
|
+
* can be resolved through DI: `ConfigService`, a Redis client, and so on.
|
|
1897
1415
|
*
|
|
1898
|
-
* Options are validated
|
|
1899
|
-
*
|
|
1900
|
-
*
|
|
1416
|
+
* Options are validated inside the resolving factory, so a malformed
|
|
1417
|
+
* configuration rejects at bootstrap and the application fails to start with
|
|
1418
|
+
* a clear error.
|
|
1901
1419
|
*
|
|
1902
|
-
* Controllers are registered at decoration time, so
|
|
1903
|
-
*
|
|
1904
|
-
*
|
|
1905
|
-
* pre-resolve the options before passing them.
|
|
1906
|
-
*
|
|
1907
|
-
* Pass a synchronous `transport` hint to gate WebSocket wiring exactly as
|
|
1908
|
-
* `forRoot` does — an SSE-only application then never registers the gateway,
|
|
1909
|
-
* never boots Socket.IO, and never requires the optional WS peer deps. Without
|
|
1910
|
-
* the hint, every transport provider is registered and the active one is
|
|
1911
|
-
* resolved at runtime from the factory result.
|
|
1420
|
+
* Controllers are registered at decoration time, so this path binds the SSE
|
|
1421
|
+
* controller to the default endpoint `/events`. A non-default endpoint needs
|
|
1422
|
+
* `forRoot` with pre-resolved options.
|
|
1912
1423
|
*
|
|
1424
|
+
* @throws when no factory pattern is given, more than one is, or the factory
|
|
1425
|
+
* resolves a transport other than `'sse'`.
|
|
1913
1426
|
* @example
|
|
1914
1427
|
* ```ts
|
|
1915
1428
|
* BymaxRealtimeModule.forRootAsync({
|
|
1916
1429
|
* transport: 'sse',
|
|
1917
1430
|
* imports: [ConfigModule],
|
|
1918
1431
|
* inject: [ConfigService],
|
|
1919
|
-
* useFactory:
|
|
1920
|
-
* transport: 'sse',
|
|
1921
|
-
* authenticator: new CookieJwtAuthenticator(cfg.
|
|
1432
|
+
* useFactory: (cfg: ConfigService) => ({
|
|
1433
|
+
* transport: 'sse' as const,
|
|
1434
|
+
* authenticator: new CookieJwtAuthenticator(cfg.getOrThrow('JWT_SECRET')),
|
|
1922
1435
|
* }),
|
|
1923
1436
|
* })
|
|
1924
1437
|
* ```
|
|
1925
1438
|
*/
|
|
1926
1439
|
static forRootAsync(asyncOptions) {
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
if (patterns.length !== 1) {
|
|
1933
|
-
throw new Error(
|
|
1934
|
-
`[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
|
|
1935
|
-
);
|
|
1936
|
-
}
|
|
1937
|
-
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
1938
|
-
const instanceId = randomUUID();
|
|
1939
|
-
const resolvedOptionsProvider = asyncOptions.useFactory ? {
|
|
1940
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
1941
|
-
useFactory: async (...args) => BymaxRealtimeModule.resolveAsyncOptions(
|
|
1942
|
-
await asyncOptions.useFactory(...args),
|
|
1943
|
-
asyncOptions.transport,
|
|
1944
|
-
instanceId,
|
|
1945
|
-
"useFactory"
|
|
1946
|
-
),
|
|
1947
|
-
inject: [...asyncOptions.inject ?? []]
|
|
1948
|
-
} : {
|
|
1949
|
-
provide: REALTIME_OPTIONS_TOKEN,
|
|
1950
|
-
useFactory: async (factory) => BymaxRealtimeModule.resolveAsyncOptions(
|
|
1951
|
-
await factory.createRealtimeOptions(),
|
|
1952
|
-
asyncOptions.transport,
|
|
1953
|
-
instanceId,
|
|
1954
|
-
"options factory"
|
|
1955
|
-
),
|
|
1956
|
-
inject: [asyncOptions.useClass ? FACTORY_TOKEN : asyncOptions.useExisting]
|
|
1957
|
-
};
|
|
1958
|
-
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
1959
|
-
const authenticatorProvider = {
|
|
1960
|
-
provide: REALTIME_AUTHENTICATOR_TOKEN,
|
|
1961
|
-
useFactory: (opts) => opts.authenticator,
|
|
1962
|
-
inject: [REALTIME_OPTIONS_TOKEN]
|
|
1963
|
-
};
|
|
1964
|
-
const pubsubProvider = {
|
|
1965
|
-
provide: REALTIME_PUBSUB_TOKEN,
|
|
1966
|
-
useFactory: (opts) => {
|
|
1967
|
-
if (!opts.pubsub && process.env["NODE_ENV"] === "production") {
|
|
1968
|
-
BymaxRealtimeModule.logger.warn(
|
|
1969
|
-
"No IRealtimePubSub provided in production \u2014 single-instance only. Provide a Redis-backed IRealtimePubSub for horizontal scaling."
|
|
1970
|
-
);
|
|
1971
|
-
}
|
|
1972
|
-
return opts.pubsub ?? new InMemoryPubSub();
|
|
1973
|
-
},
|
|
1974
|
-
inject: [REALTIME_OPTIONS_TOKEN]
|
|
1975
|
-
};
|
|
1976
|
-
const hooksProvider = {
|
|
1977
|
-
provide: REALTIME_HOOKS_TOKEN,
|
|
1978
|
-
useFactory: (opts) => opts.hooks ?? {},
|
|
1979
|
-
inject: [REALTIME_OPTIONS_TOKEN]
|
|
1980
|
-
};
|
|
1981
|
-
const offlineQueueProvider = {
|
|
1982
|
-
provide: REALTIME_OFFLINE_QUEUE_TOKEN,
|
|
1983
|
-
useFactory: (opts) => opts.offlineQueue,
|
|
1984
|
-
inject: [REALTIME_OPTIONS_TOKEN]
|
|
1985
|
-
};
|
|
1986
|
-
const presenceProvider = {
|
|
1987
|
-
provide: REALTIME_PRESENCE_TOKEN,
|
|
1988
|
-
useFactory: (opts) => opts.presence,
|
|
1989
|
-
inject: [REALTIME_OPTIONS_TOKEN]
|
|
1990
|
-
};
|
|
1991
|
-
const { providers: transportProviders, controllers } = buildAsyncTransportProviders(
|
|
1992
|
-
asyncOptions.transport
|
|
1440
|
+
return composeForRootAsync(
|
|
1441
|
+
BymaxRealtimeModule,
|
|
1442
|
+
sseWiring,
|
|
1443
|
+
BymaxRealtimeModule.logger,
|
|
1444
|
+
asyncOptions
|
|
1993
1445
|
);
|
|
1994
|
-
const providers = [
|
|
1995
|
-
...factoryClassProvider,
|
|
1996
|
-
resolvedOptionsProvider,
|
|
1997
|
-
authenticatorProvider,
|
|
1998
|
-
pubsubProvider,
|
|
1999
|
-
hooksProvider,
|
|
2000
|
-
{ provide: REALTIME_INSTANCE_ID_TOKEN, useValue: instanceId },
|
|
2001
|
-
offlineQueueProvider,
|
|
2002
|
-
presenceProvider,
|
|
2003
|
-
ConnectionRegistry,
|
|
2004
|
-
RoomRegistry,
|
|
2005
|
-
EventIdGenerator,
|
|
2006
|
-
EventReplayBuffer,
|
|
2007
|
-
HeartbeatService,
|
|
2008
|
-
RealtimeService,
|
|
2009
|
-
ReauthenticationService,
|
|
2010
|
-
OfflineQueueDeliveryService,
|
|
2011
|
-
...transportProviders,
|
|
2012
|
-
...asyncOptions.extraProviders ?? []
|
|
2013
|
-
];
|
|
2014
|
-
return {
|
|
2015
|
-
module: BymaxRealtimeModule,
|
|
2016
|
-
imports: asyncOptions.imports ?? [],
|
|
2017
|
-
providers,
|
|
2018
|
-
controllers,
|
|
2019
|
-
exports: [
|
|
2020
|
-
RealtimeService,
|
|
2021
|
-
ConnectionRegistry,
|
|
2022
|
-
REALTIME_OPTIONS_TOKEN,
|
|
2023
|
-
REALTIME_INSTANCE_ID_TOKEN,
|
|
2024
|
-
REALTIME_AUTHENTICATOR_TOKEN,
|
|
2025
|
-
REALTIME_PUBSUB_TOKEN,
|
|
2026
|
-
REALTIME_HOOKS_TOKEN,
|
|
2027
|
-
REALTIME_OFFLINE_QUEUE_TOKEN,
|
|
2028
|
-
REALTIME_PRESENCE_TOKEN,
|
|
2029
|
-
REALTIME_TRANSPORT_TOKEN
|
|
2030
|
-
]
|
|
2031
|
-
};
|
|
2032
1446
|
}
|
|
2033
1447
|
};
|
|
2034
1448
|
__publicField(BymaxRealtimeModule, "logger", new Logger(BymaxRealtimeModule.name));
|
|
@@ -2185,76 +1599,5 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
|
|
|
2185
1599
|
}
|
|
2186
1600
|
}
|
|
2187
1601
|
};
|
|
2188
|
-
var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
|
|
2189
|
-
logger = new Logger(_RealtimeIoAdapter.name);
|
|
2190
|
-
options;
|
|
2191
|
-
constructor(app) {
|
|
2192
|
-
super(app);
|
|
2193
|
-
this.options = app.get(REALTIME_OPTIONS_TOKEN);
|
|
2194
|
-
}
|
|
2195
|
-
/**
|
|
2196
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
2197
|
-
*
|
|
2198
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
2199
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
2200
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
2201
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
2202
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
2203
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
2204
|
-
* namespace leaves the root server untouched.
|
|
2205
|
-
*/
|
|
2206
|
-
create(port, options) {
|
|
2207
|
-
const server = super.create(port, options);
|
|
2208
|
-
const ns = this.options.websocket?.namespace;
|
|
2209
|
-
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
2210
|
-
return server.of(ns);
|
|
2211
|
-
}
|
|
2212
|
-
return server;
|
|
2213
|
-
}
|
|
2214
|
-
/**
|
|
2215
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
2216
|
-
*
|
|
2217
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
2218
|
-
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
2219
|
-
* dep — its absence does not crash the lib).
|
|
2220
|
-
*/
|
|
2221
|
-
createIOServer(port, opts) {
|
|
2222
|
-
const wsOpts = this.options.websocket ?? {};
|
|
2223
|
-
const mergedOpts = {
|
|
2224
|
-
...opts,
|
|
2225
|
-
cors: wsOpts.cors ?? opts?.cors,
|
|
2226
|
-
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
2227
|
-
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
2228
|
-
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
2229
|
-
};
|
|
2230
|
-
const server = super.createIOServer(port, mergedOpts);
|
|
2231
|
-
if (wsOpts.redisAdapter?.pubClient) {
|
|
2232
|
-
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
2233
|
-
}
|
|
2234
|
-
return server;
|
|
2235
|
-
}
|
|
2236
|
-
/**
|
|
2237
|
-
* Lazily load and install `@socket.io/redis-adapter`.
|
|
2238
|
-
*
|
|
2239
|
-
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
2240
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
2241
|
-
* the lib degrades gracefully to single-instance mode.
|
|
2242
|
-
*/
|
|
2243
|
-
installRedisAdapter(server, pubClient) {
|
|
2244
|
-
try {
|
|
2245
|
-
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
2246
|
-
const pub = pubClient;
|
|
2247
|
-
const sub = pub.duplicate();
|
|
2248
|
-
server.adapter(createAdapter(pub, sub));
|
|
2249
|
-
this.logger.log(
|
|
2250
|
-
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
2251
|
-
);
|
|
2252
|
-
} catch (err) {
|
|
2253
|
-
this.logger.error(
|
|
2254
|
-
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
2255
|
-
);
|
|
2256
|
-
}
|
|
2257
|
-
}
|
|
2258
|
-
};
|
|
2259
1602
|
|
|
2260
|
-
export { BymaxRealtimeModule,
|
|
1603
|
+
export { BymaxRealtimeModule, ConnectionRegistry, InMemoryPubSub, 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, RealtimeService, RedisOfflineQueue, RedisRealtimePubSub, composeRoomId };
|