@bymax-one/nest-realtime 1.2.1 → 1.2.3
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 +133 -1
- package/README.md +82 -10
- package/dist/internal/index.cjs +71 -7
- package/dist/internal/index.d.cts +21 -2
- package/dist/internal/index.d.ts +21 -2
- package/dist/internal/index.mjs +72 -8
- package/dist/shared/index.cjs +1 -0
- package/dist/shared/index.d.cts +1 -0
- package/dist/shared/index.d.ts +1 -0
- package/dist/shared/index.mjs +1 -0
- package/dist/websocket/index.cjs +127 -78
- package/dist/websocket/index.d.cts +10 -7
- package/dist/websocket/index.d.ts +10 -7
- package/dist/websocket/index.mjs +133 -82
- package/package.json +1 -1
package/dist/internal/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
|
-
import { Injectable, Optional, Inject, Logger, Global, Module, Sse, Req, Res, Controller, InternalServerErrorException, UnauthorizedException } from '@nestjs/common';
|
|
2
|
+
import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, 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
|
|
|
@@ -26,6 +26,7 @@ var REALTIME_ERROR_CODES = {
|
|
|
26
26
|
TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
|
|
27
27
|
INVALID_TICKET: "REALTIME_INVALID_TICKET",
|
|
28
28
|
PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
|
|
29
|
+
REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
|
|
29
30
|
PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
|
|
30
31
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
31
32
|
};
|
|
@@ -217,7 +218,11 @@ var ConnectionRegistry = class {
|
|
|
217
218
|
byId = /* @__PURE__ */ new Map();
|
|
218
219
|
byUserId = /* @__PURE__ */ new Map();
|
|
219
220
|
byTenantId = /* @__PURE__ */ new Map();
|
|
220
|
-
/**
|
|
221
|
+
/**
|
|
222
|
+
* Register a connection and index it by user and tenant.
|
|
223
|
+
*
|
|
224
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
225
|
+
*/
|
|
221
226
|
register(record) {
|
|
222
227
|
this.byId.set(record.connectionId, record);
|
|
223
228
|
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
@@ -225,7 +230,11 @@ var ConnectionRegistry = class {
|
|
|
225
230
|
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
226
231
|
}
|
|
227
232
|
}
|
|
228
|
-
/**
|
|
233
|
+
/**
|
|
234
|
+
* Remove a connection from every index. Returns the removed record, if any.
|
|
235
|
+
*
|
|
236
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
237
|
+
*/
|
|
229
238
|
unregister(connectionId) {
|
|
230
239
|
const record = this.byId.get(connectionId);
|
|
231
240
|
if (!record) return void 0;
|
|
@@ -809,6 +818,7 @@ var SseSubscriptionHandler = class {
|
|
|
809
818
|
hooks;
|
|
810
819
|
offlineDelivery;
|
|
811
820
|
logger = new Logger(SseSubscriptionHandler.name);
|
|
821
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
812
822
|
/**
|
|
813
823
|
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
814
824
|
*
|
|
@@ -866,10 +876,22 @@ var SseSubscriptionHandler = class {
|
|
|
866
876
|
async handle(req, res) {
|
|
867
877
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
868
878
|
res.setHeader("X-Accel-Buffering", "no");
|
|
869
|
-
const
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
879
|
+
const done = this.authenticated.get(req);
|
|
880
|
+
this.authenticated.delete(req);
|
|
881
|
+
let authenticated;
|
|
882
|
+
try {
|
|
883
|
+
authenticated = done ?? await this.authenticateRequest(req);
|
|
884
|
+
} catch (err) {
|
|
885
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
886
|
+
}
|
|
887
|
+
try {
|
|
888
|
+
return await this.openStream(req, res, authenticated);
|
|
889
|
+
} catch (err) {
|
|
890
|
+
throw this.serverError(err, "SSE handshake failed");
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
async openStream(req, res, authenticated) {
|
|
894
|
+
const { context, auth: resolvedAuth } = authenticated;
|
|
873
895
|
const connectionId = randomUUID();
|
|
874
896
|
const subject = new Subject();
|
|
875
897
|
const close$ = new Subject();
|
|
@@ -892,6 +914,33 @@ var SseSubscriptionHandler = class {
|
|
|
892
914
|
queueEvents
|
|
893
915
|
});
|
|
894
916
|
}
|
|
917
|
+
/**
|
|
918
|
+
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
919
|
+
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
920
|
+
*/
|
|
921
|
+
async authenticateBeforeCommit(req) {
|
|
922
|
+
try {
|
|
923
|
+
this.authenticated.set(req, await this.authenticateRequest(req));
|
|
924
|
+
} catch (err) {
|
|
925
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
// Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
|
|
929
|
+
toClientError(err, what) {
|
|
930
|
+
return err instanceof HttpException ? err : this.serverError(err, what);
|
|
931
|
+
}
|
|
932
|
+
serverError(err, what) {
|
|
933
|
+
this.logger.error(
|
|
934
|
+
`${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
|
|
935
|
+
);
|
|
936
|
+
return new InternalServerErrorException();
|
|
937
|
+
}
|
|
938
|
+
async authenticateRequest(req) {
|
|
939
|
+
const context = buildAuthContext(req);
|
|
940
|
+
const auth = await this.transport.authenticate(context);
|
|
941
|
+
if (!auth) throw new UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
942
|
+
return { context, auth: this.resolveAndValidateIdentity(auth) };
|
|
943
|
+
}
|
|
895
944
|
/**
|
|
896
945
|
* Build the live Observable using a subscribe-before-register pattern.
|
|
897
946
|
*
|
|
@@ -946,7 +995,7 @@ var SseSubscriptionHandler = class {
|
|
|
946
995
|
this.fireHook(
|
|
947
996
|
() => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
|
|
948
997
|
);
|
|
949
|
-
subscriber.error(err);
|
|
998
|
+
subscriber.error(this.serverError(err, "SSE registration failed"));
|
|
950
999
|
});
|
|
951
1000
|
}
|
|
952
1001
|
/**
|
|
@@ -1003,6 +1052,20 @@ function normalizeEndpointPath(endpoint) {
|
|
|
1003
1052
|
// src/server/factories/sse-controller.factory.ts
|
|
1004
1053
|
function createSseController(endpoint) {
|
|
1005
1054
|
const ssePath = normalizeEndpointPath(endpoint);
|
|
1055
|
+
let SseAuthGuard = class {
|
|
1056
|
+
constructor(handler) {
|
|
1057
|
+
this.handler = handler;
|
|
1058
|
+
}
|
|
1059
|
+
handler;
|
|
1060
|
+
async canActivate(context) {
|
|
1061
|
+
await this.handler.authenticateBeforeCommit(context.switchToHttp().getRequest());
|
|
1062
|
+
return true;
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
1065
|
+
SseAuthGuard = __decorateClass([
|
|
1066
|
+
Injectable(),
|
|
1067
|
+
__decorateParam(0, Inject(SseSubscriptionHandler))
|
|
1068
|
+
], SseAuthGuard);
|
|
1006
1069
|
let DynamicSseController = class {
|
|
1007
1070
|
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
1008
1071
|
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
@@ -1016,6 +1079,7 @@ function createSseController(endpoint) {
|
|
|
1016
1079
|
}
|
|
1017
1080
|
};
|
|
1018
1081
|
__decorateClass([
|
|
1082
|
+
UseGuards(SseAuthGuard),
|
|
1019
1083
|
Sse(ssePath),
|
|
1020
1084
|
__decorateParam(0, Req()),
|
|
1021
1085
|
__decorateParam(1, Res({ passthrough: true }))
|
package/dist/shared/index.cjs
CHANGED
|
@@ -30,6 +30,7 @@ var REALTIME_ERROR_CODES = {
|
|
|
30
30
|
TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
|
|
31
31
|
INVALID_TICKET: "REALTIME_INVALID_TICKET",
|
|
32
32
|
PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
|
|
33
|
+
REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
|
|
33
34
|
PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
|
|
34
35
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
35
36
|
};
|
package/dist/shared/index.d.cts
CHANGED
|
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
153
153
|
readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
|
|
154
154
|
readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
|
|
155
155
|
readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
|
|
156
|
+
readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
|
|
156
157
|
readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
|
|
157
158
|
readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
|
|
158
159
|
};
|
package/dist/shared/index.d.ts
CHANGED
|
@@ -153,6 +153,7 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
153
153
|
readonly TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS";
|
|
154
154
|
readonly INVALID_TICKET: "REALTIME_INVALID_TICKET";
|
|
155
155
|
readonly PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE";
|
|
156
|
+
readonly REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED";
|
|
156
157
|
readonly PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE";
|
|
157
158
|
readonly REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS";
|
|
158
159
|
};
|
package/dist/shared/index.mjs
CHANGED
|
@@ -28,6 +28,7 @@ var REALTIME_ERROR_CODES = {
|
|
|
28
28
|
TOO_MANY_CONNECTIONS: "REALTIME_TOO_MANY_CONNECTIONS",
|
|
29
29
|
INVALID_TICKET: "REALTIME_INVALID_TICKET",
|
|
30
30
|
PUBSUB_UNAVAILABLE: "REALTIME_PUBSUB_UNAVAILABLE",
|
|
31
|
+
REDIS_ADAPTER_FAILED: "REALTIME_REDIS_ADAPTER_FAILED",
|
|
31
32
|
PAYLOAD_TOO_LARGE: "REALTIME_PAYLOAD_TOO_LARGE",
|
|
32
33
|
REPLAY_BUFFER_MISS: "REALTIME_REPLAY_BUFFER_MISS"
|
|
33
34
|
};
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -393,6 +393,90 @@ exports.CompositeTransport = __decorateClass([
|
|
|
393
393
|
__decorateParam(0, common.Inject(internal.SseTransport)),
|
|
394
394
|
__decorateParam(1, common.Inject(exports.WebSocketTransport))
|
|
395
395
|
], exports.CompositeTransport);
|
|
396
|
+
var realtimeServers = /* @__PURE__ */ new WeakSet();
|
|
397
|
+
function isRealtimeIoServer(server) {
|
|
398
|
+
return typeof server === "object" && server !== null && realtimeServers.has(server);
|
|
399
|
+
}
|
|
400
|
+
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
401
|
+
adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
|
|
402
|
+
options;
|
|
403
|
+
constructor(app) {
|
|
404
|
+
super(app);
|
|
405
|
+
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Bind the gateway to `websocket.namespace` when configured.
|
|
409
|
+
*
|
|
410
|
+
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
411
|
+
* the module options resolve — so the namespace cannot be declared there.
|
|
412
|
+
* Instead we build the root server via `super.create` (which routes through the
|
|
413
|
+
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
414
|
+
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
415
|
+
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
416
|
+
* namespace leaves the root server untouched.
|
|
417
|
+
*/
|
|
418
|
+
create(port, options) {
|
|
419
|
+
const server = super.create(port, options);
|
|
420
|
+
const ns = this.options.websocket?.namespace;
|
|
421
|
+
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
422
|
+
const namespace = server.of(ns);
|
|
423
|
+
realtimeServers.add(namespace);
|
|
424
|
+
return namespace;
|
|
425
|
+
}
|
|
426
|
+
return server;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Create the Socket.IO server with merged WebSocket options.
|
|
430
|
+
*
|
|
431
|
+
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
432
|
+
* `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
|
|
433
|
+
*/
|
|
434
|
+
createIOServer(port, opts) {
|
|
435
|
+
const wsOpts = this.options.websocket ?? {};
|
|
436
|
+
const mergedOpts = {
|
|
437
|
+
...opts,
|
|
438
|
+
cors: wsOpts.cors ?? opts?.cors,
|
|
439
|
+
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
440
|
+
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
441
|
+
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
442
|
+
};
|
|
443
|
+
const server = super.createIOServer(port, mergedOpts);
|
|
444
|
+
if (wsOpts.redisAdapter?.pubClient) {
|
|
445
|
+
try {
|
|
446
|
+
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
447
|
+
} catch (err) {
|
|
448
|
+
server.close().catch(() => void 0);
|
|
449
|
+
throw err;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
realtimeServers.add(server);
|
|
453
|
+
return server;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
|
|
457
|
+
* silent single-instance server drops cross-node messages. An unreachable Redis
|
|
458
|
+
* is not one; reconnecting stays with the client.
|
|
459
|
+
*/
|
|
460
|
+
installRedisAdapter(server, pubClient) {
|
|
461
|
+
try {
|
|
462
|
+
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
463
|
+
const pub = pubClient;
|
|
464
|
+
const sub = pub.duplicate();
|
|
465
|
+
server.adapter(createAdapter(pub, sub));
|
|
466
|
+
} catch (err) {
|
|
467
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
468
|
+
throw new Error(
|
|
469
|
+
`[${_RealtimeIoAdapter.name}] ${internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED}: websocket.redisAdapter is set but the Socket.IO Redis adapter could not be installed (${reason}). Install @socket.io/redis-adapter and pass an ioredis client as pubClient.`,
|
|
470
|
+
{ cause: err }
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
this.adapterLogger.log(
|
|
474
|
+
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
|
|
479
|
+
// src/websocket/transports/websocket/realtime.gateway.ts
|
|
396
480
|
function firstQueryValue(value) {
|
|
397
481
|
return Array.isArray(value) ? value[0] : value;
|
|
398
482
|
}
|
|
@@ -405,11 +489,43 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
405
489
|
options;
|
|
406
490
|
logger = new common.Logger(exports.RealtimeGateway.name);
|
|
407
491
|
server;
|
|
492
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
493
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
494
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
495
|
+
authenticateHandshake = async (socket, next) => {
|
|
496
|
+
try {
|
|
497
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
498
|
+
if (!auth) {
|
|
499
|
+
const refusal = new Error(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
500
|
+
refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
|
|
501
|
+
next(refusal);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
505
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
506
|
+
this.authenticated.set(socket, resolvedAuth);
|
|
507
|
+
next();
|
|
508
|
+
} catch (err) {
|
|
509
|
+
this.logger.error(
|
|
510
|
+
`handshake refused for socket ${socket.id}: ${err instanceof Error ? err.message : String(err)}`
|
|
511
|
+
);
|
|
512
|
+
next(new Error("Internal Server Error"));
|
|
513
|
+
}
|
|
514
|
+
};
|
|
408
515
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
409
516
|
afterInit(server) {
|
|
517
|
+
server.use(this.authenticateHandshake);
|
|
410
518
|
this.transport.setServer(server);
|
|
519
|
+
if (!isRealtimeIoServer(server)) this.reportMissingAdapter();
|
|
411
520
|
this.logger.log("RealtimeGateway initialized");
|
|
412
521
|
}
|
|
522
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
523
|
+
reportMissingAdapter() {
|
|
524
|
+
const configured = Object.keys(this.options.websocket ?? {});
|
|
525
|
+
this.logger.error(
|
|
526
|
+
"RealtimeIoAdapter is not the active WebSocket adapter, so the websocket options" + (configured.length > 0 ? ` (${configured.join(", ")})` : "") + " are ignored and the gateway CORS stays closed (origin: false): browsers on another origin cannot connect. Add app.useWebSocketAdapter(new RealtimeIoAdapter(app)) in main.ts, importing it from '@bymax-one/nest-realtime/websocket'."
|
|
527
|
+
);
|
|
528
|
+
}
|
|
413
529
|
/**
|
|
414
530
|
* Handle a new WebSocket connection.
|
|
415
531
|
*
|
|
@@ -462,13 +578,17 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
462
578
|
}
|
|
463
579
|
async handleConnection(socket) {
|
|
464
580
|
try {
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
581
|
+
let resolvedAuth = this.authenticated.get(socket);
|
|
582
|
+
this.authenticated.delete(socket);
|
|
583
|
+
if (!resolvedAuth) {
|
|
584
|
+
const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
|
|
585
|
+
if (!auth) {
|
|
586
|
+
socket.disconnect(true);
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
590
|
+
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
469
591
|
}
|
|
470
|
-
const resolvedAuth = internal.resolveAuthTenant(this.options, auth);
|
|
471
|
-
internal.assertIdentityIsNotBlank(resolvedAuth);
|
|
472
592
|
await this.transport.registerSocket(socket, resolvedAuth);
|
|
473
593
|
if (this.options.websocket?.emitConnectionEvent !== false) {
|
|
474
594
|
socket.emit(internal.RESERVED_EVENT_NAMES.CONNECTION_ESTABLISHED, {
|
|
@@ -482,7 +602,7 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
482
602
|
}
|
|
483
603
|
} catch (err) {
|
|
484
604
|
this.logger.error(
|
|
485
|
-
`handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err.message}`
|
|
605
|
+
`handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${err instanceof Error ? err.message : String(err)}`
|
|
486
606
|
);
|
|
487
607
|
socket.disconnect(true);
|
|
488
608
|
}
|
|
@@ -632,76 +752,5 @@ exports.BymaxRealtimeWebSocketModule = __decorateClass([
|
|
|
632
752
|
common.Global(),
|
|
633
753
|
common.Module({})
|
|
634
754
|
], exports.BymaxRealtimeWebSocketModule);
|
|
635
|
-
var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAdapter {
|
|
636
|
-
adapterLogger = new common.Logger(_RealtimeIoAdapter.name);
|
|
637
|
-
options;
|
|
638
|
-
constructor(app) {
|
|
639
|
-
super(app);
|
|
640
|
-
this.options = app.get(internal.REALTIME_OPTIONS_TOKEN);
|
|
641
|
-
}
|
|
642
|
-
/**
|
|
643
|
-
* Bind the gateway to `websocket.namespace` when configured.
|
|
644
|
-
*
|
|
645
|
-
* `@WebSocketGateway()` args are evaluated at class-decoration time — before
|
|
646
|
-
* the module options resolve — so the namespace cannot be declared there.
|
|
647
|
-
* Instead we build the root server via `super.create` (which routes through the
|
|
648
|
-
* overridden {@link createIOServer}, applying CORS/ping/Redis) and then return
|
|
649
|
-
* the requested namespace via `server.of(ns)`. The gateway's `@WebSocketServer()`
|
|
650
|
-
* and `WebSocketTransport` then operate on that `Namespace`. A `'/'` or unset
|
|
651
|
-
* namespace leaves the root server untouched.
|
|
652
|
-
*/
|
|
653
|
-
create(port, options) {
|
|
654
|
-
const server = super.create(port, options);
|
|
655
|
-
const ns = this.options.websocket?.namespace;
|
|
656
|
-
if (ns && ns !== "/" && typeof server.of === "function") {
|
|
657
|
-
return server.of(ns);
|
|
658
|
-
}
|
|
659
|
-
return server;
|
|
660
|
-
}
|
|
661
|
-
/**
|
|
662
|
-
* Create the Socket.IO server with merged WebSocket options.
|
|
663
|
-
*
|
|
664
|
-
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
665
|
-
* `@socket.io/redis-adapter` lazily (so the package stays an optional peer
|
|
666
|
-
* dep — its absence does not crash the lib).
|
|
667
|
-
*/
|
|
668
|
-
createIOServer(port, opts) {
|
|
669
|
-
const wsOpts = this.options.websocket ?? {};
|
|
670
|
-
const mergedOpts = {
|
|
671
|
-
...opts,
|
|
672
|
-
cors: wsOpts.cors ?? opts?.cors,
|
|
673
|
-
pingInterval: wsOpts.pingIntervalMs ?? 25e3,
|
|
674
|
-
pingTimeout: wsOpts.pingTimeoutMs ?? 2e4,
|
|
675
|
-
maxHttpBufferSize: wsOpts.maxHttpBufferSize ?? 1e6
|
|
676
|
-
};
|
|
677
|
-
const server = super.createIOServer(port, mergedOpts);
|
|
678
|
-
if (wsOpts.redisAdapter?.pubClient) {
|
|
679
|
-
this.installRedisAdapter(server, wsOpts.redisAdapter.pubClient);
|
|
680
|
-
}
|
|
681
|
-
return server;
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* Lazily load and install `@socket.io/redis-adapter`.
|
|
685
|
-
*
|
|
686
|
-
* Uses a dynamic `require` so the package stays optional — absent peers do
|
|
687
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
688
|
-
* the lib degrades gracefully to single-instance mode.
|
|
689
|
-
*/
|
|
690
|
-
installRedisAdapter(server, pubClient) {
|
|
691
|
-
try {
|
|
692
|
-
const { createAdapter } = __require("@socket.io/redis-adapter");
|
|
693
|
-
const pub = pubClient;
|
|
694
|
-
const sub = pub.duplicate();
|
|
695
|
-
server.adapter(createAdapter(pub, sub));
|
|
696
|
-
this.adapterLogger.log(
|
|
697
|
-
"Socket.IO Redis adapter registered \u2014 cross-instance WebSocket fan-out enabled"
|
|
698
|
-
);
|
|
699
|
-
} catch (err) {
|
|
700
|
-
this.adapterLogger.error(
|
|
701
|
-
`Failed to register @socket.io/redis-adapter: ${err.message}. Falling back to single-instance mode.`
|
|
702
|
-
);
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
};
|
|
706
755
|
|
|
707
756
|
exports.RealtimeIoAdapter = RealtimeIoAdapter;
|
|
@@ -226,8 +226,14 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
226
226
|
private readonly logger;
|
|
227
227
|
server: Server;
|
|
228
228
|
constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
|
|
229
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
230
|
+
private readonly authenticated;
|
|
231
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
232
|
+
private readonly authenticateHandshake;
|
|
229
233
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
230
234
|
afterInit(server: Server): void;
|
|
235
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
236
|
+
private reportMissingAdapter;
|
|
231
237
|
/**
|
|
232
238
|
* Handle a new WebSocket connection.
|
|
233
239
|
*
|
|
@@ -320,16 +326,13 @@ declare class RealtimeIoAdapter extends IoAdapter {
|
|
|
320
326
|
* Create the Socket.IO server with merged WebSocket options.
|
|
321
327
|
*
|
|
322
328
|
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
323
|
-
* `@socket.io/redis-adapter` lazily
|
|
324
|
-
* dep — its absence does not crash the lib).
|
|
329
|
+
* `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
|
|
325
330
|
*/
|
|
326
331
|
createIOServer(port: number, opts?: ServerOptions): unknown;
|
|
327
332
|
/**
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
*
|
|
331
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
332
|
-
* the lib degrades gracefully to single-instance mode.
|
|
333
|
+
* Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
|
|
334
|
+
* silent single-instance server drops cross-node messages. An unreachable Redis
|
|
335
|
+
* is not one; reconnecting stays with the client.
|
|
333
336
|
*/
|
|
334
337
|
private installRedisAdapter;
|
|
335
338
|
}
|
|
@@ -226,8 +226,14 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
|
|
|
226
226
|
private readonly logger;
|
|
227
227
|
server: Server;
|
|
228
228
|
constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
|
|
229
|
+
/** Identities the handshake middleware resolved, until `handleConnection` takes them. */
|
|
230
|
+
private readonly authenticated;
|
|
231
|
+
/** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
|
|
232
|
+
private readonly authenticateHandshake;
|
|
229
233
|
/** Wire the resolved Socket.IO server to the transport after gateway init. */
|
|
230
234
|
afterInit(server: Server): void;
|
|
235
|
+
/** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
|
|
236
|
+
private reportMissingAdapter;
|
|
231
237
|
/**
|
|
232
238
|
* Handle a new WebSocket connection.
|
|
233
239
|
*
|
|
@@ -320,16 +326,13 @@ declare class RealtimeIoAdapter extends IoAdapter {
|
|
|
320
326
|
* Create the Socket.IO server with merged WebSocket options.
|
|
321
327
|
*
|
|
322
328
|
* When `websocket.redisAdapter.pubClient` is set, installs the
|
|
323
|
-
* `@socket.io/redis-adapter` lazily
|
|
324
|
-
* dep — its absence does not crash the lib).
|
|
329
|
+
* `@socket.io/redis-adapter` lazily: the optional peer is needed only then.
|
|
325
330
|
*/
|
|
326
331
|
createIOServer(port: number, opts?: ServerOptions): unknown;
|
|
327
332
|
/**
|
|
328
|
-
*
|
|
329
|
-
*
|
|
330
|
-
*
|
|
331
|
-
* not crash the lib. A load or install failure is logged and tolerated;
|
|
332
|
-
* the lib degrades gracefully to single-instance mode.
|
|
333
|
+
* Install `@socket.io/redis-adapter`. A deterministic failure fails the boot: a
|
|
334
|
+
* silent single-instance server drops cross-node messages. An unreachable Redis
|
|
335
|
+
* is not one; reconnecting stays with the client.
|
|
333
336
|
*/
|
|
334
337
|
private installRedisAdapter;
|
|
335
338
|
}
|