@bymax-one/nest-realtime 1.2.8 → 1.2.10

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.
@@ -1,11 +1,14 @@
1
1
  import { randomUUID } from 'crypto';
2
- import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, HttpException, UnauthorizedException } from '@nestjs/common';
2
+ import { Injectable, Optional, Inject, Logger, Global, Module, UseGuards, Sse, Req, Res, Controller, InternalServerErrorException, ServiceUnavailableException, HttpException, UnauthorizedException } from '@nestjs/common';
3
3
  import { Subject, of, EMPTY, Observable, merge } from 'rxjs';
4
4
  import { takeUntil, catchError, finalize } from 'rxjs/operators';
5
5
  import { isIP } from 'net';
6
6
 
7
7
  var __defProp = Object.defineProperty;
8
8
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __typeError = (msg) => {
10
+ throw TypeError(msg);
11
+ };
9
12
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
13
  var __decorateClass = (decorators, target, key, kind) => {
11
14
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
@@ -16,7 +19,11 @@ var __decorateClass = (decorators, target, key, kind) => {
16
19
  return result;
17
20
  };
18
21
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
19
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
22
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
23
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
24
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
25
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
26
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
20
27
 
21
28
  // src/shared/constants/error-codes.constants.ts
22
29
  var REALTIME_ERROR_CODES = {
@@ -61,22 +68,36 @@ var DEFAULT_HEARTBEAT_MS = 3e4;
61
68
  var HEARTBEAT_MIN_MS = 5e3;
62
69
  var HEARTBEAT_MAX_MS = 9e4;
63
70
 
71
+ // src/server/utils/realtime-error.ts
72
+ function realtimeError(code, detail, options = {}) {
73
+ const lead = options.who === void 0 ? code : `[${options.who}] ${code}`;
74
+ const message = `${lead}: ${detail}`;
75
+ const error = "cause" in options ? new Error(message, { cause: options.cause }) : new Error(message);
76
+ return Object.assign(error, { code });
77
+ }
78
+
64
79
  // src/server/config/validate-options.ts
65
80
  var VALID_TRANSPORTS = /* @__PURE__ */ new Set(["sse", "websocket", "both"]);
66
81
  function validateOptions(options) {
67
82
  if (!options.transport || !VALID_TRANSPORTS.has(options.transport)) {
68
- throw new Error(
69
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`
83
+ throw realtimeError(
84
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
85
+ `options.transport must be one of 'sse' | 'websocket' | 'both' (got: ${String(options.transport)})`,
86
+ { who: "BymaxRealtimeModule" }
70
87
  );
71
88
  }
72
89
  if (!options.authenticator) {
73
- throw new Error(
74
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator is required \u2014 the library never ships a default authenticator`
90
+ throw realtimeError(
91
+ REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
92
+ `options.authenticator is required \u2014 the library never ships a default authenticator`,
93
+ { who: "BymaxRealtimeModule" }
75
94
  );
76
95
  }
77
96
  if (typeof options.authenticator.authenticate !== "function") {
78
- throw new Error(
79
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.NO_AUTHENTICATOR}: options.authenticator must implement IConnectionAuthenticator.authenticate(context)`
97
+ throw realtimeError(
98
+ REALTIME_ERROR_CODES.NO_AUTHENTICATOR,
99
+ `options.authenticator must implement IConnectionAuthenticator.authenticate(context)`,
100
+ { who: "BymaxRealtimeModule" }
80
101
  );
81
102
  }
82
103
  validateSseOptions(options);
@@ -95,18 +116,24 @@ function validateSseOptions(options) {
95
116
  const sse = options.sse;
96
117
  const heartbeatMs = sse?.heartbeatMs;
97
118
  if (heartbeatMs !== void 0 && !(typeof heartbeatMs === "number" && heartbeatMs >= HEARTBEAT_MIN_MS && heartbeatMs <= HEARTBEAT_MAX_MS)) {
98
- throw new Error(
99
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`
119
+ throw realtimeError(
120
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
121
+ `options.sse.heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${String(heartbeatMs)})`,
122
+ { who: "BymaxRealtimeModule" }
100
123
  );
101
124
  }
102
125
  if (sse?.replayBufferSize !== void 0 && sse.replayBufferSize < 0) {
103
- throw new Error(
104
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.replayBufferSize must be >= 0`
126
+ throw realtimeError(
127
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
128
+ `options.sse.replayBufferSize must be >= 0`,
129
+ { who: "BymaxRealtimeModule" }
105
130
  );
106
131
  }
107
132
  if (sse?.maxConnectionsPerUser !== void 0 && sse.maxConnectionsPerUser < 0) {
108
- throw new Error(
109
- `[BymaxRealtimeModule] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`
133
+ throw realtimeError(
134
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
135
+ `options.sse.maxConnectionsPerUser must be >= 0 (0 disables the per-user connection cap)`,
136
+ { who: "BymaxRealtimeModule" }
110
137
  );
111
138
  }
112
139
  }
@@ -210,13 +237,15 @@ function resolveAuthTenant(options, auth) {
210
237
  }
211
238
  function assertIdentityIsNotBlank(auth) {
212
239
  if (isBlank(auth.userId)) {
213
- throw new Error(
214
- `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
240
+ throw realtimeError(
241
+ REALTIME_ERROR_CODES.AUTH_FAILED,
242
+ `the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
215
243
  );
216
244
  }
217
245
  if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
218
- throw new Error(
219
- `${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
246
+ throw realtimeError(
247
+ REALTIME_ERROR_CODES.AUTH_FAILED,
248
+ `the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
220
249
  );
221
250
  }
222
251
  }
@@ -401,7 +430,7 @@ function composeRoomId(prefix, ...parts) {
401
430
 
402
431
  // src/server/utils/unavailable-error.ts
403
432
  function unavailableError(code, who, what, cause) {
404
- return new Error(`[${who}] ${code}: ${what} (${describeError(cause)})`, { cause });
433
+ return realtimeError(code, `${what} (${describeError(cause)})`, { who, cause });
405
434
  }
406
435
  var InMemoryPubSub = class {
407
436
  handlers = /* @__PURE__ */ new Set();
@@ -458,8 +487,9 @@ var HeartbeatService = class {
458
487
  timers = /* @__PURE__ */ new Map();
459
488
  start(connectionId, res, intervalMs) {
460
489
  if (intervalMs < HEARTBEAT_MIN_MS || intervalMs > HEARTBEAT_MAX_MS) {
461
- throw new Error(
462
- `${REALTIME_ERROR_CODES.INVALID_OPTIONS}: heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
490
+ throw realtimeError(
491
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
492
+ `heartbeatMs must be between ${HEARTBEAT_MIN_MS} and ${HEARTBEAT_MAX_MS} ms (got ${intervalMs})`
463
493
  );
464
494
  }
465
495
  this.stop(connectionId);
@@ -490,6 +520,7 @@ HeartbeatService = __decorateClass([
490
520
  ], HeartbeatService);
491
521
 
492
522
  // src/server/transports/sse/sse.transport.ts
523
+ var _shuttingDown;
493
524
  var SseTransport = class {
494
525
  constructor(connections, rooms, replayBuffer, idGen, heartbeat, auth, pubsub, hooks, options, instanceId, offlineQueue) {
495
526
  this.connections = connections;
@@ -503,6 +534,9 @@ var SseTransport = class {
503
534
  this.options = options;
504
535
  this.instanceId = instanceId;
505
536
  this.offlineQueue = offlineQueue;
537
+ __publicField(this, "kind", "sse");
538
+ __publicField(this, "logger", new Logger(SseTransport.name));
539
+ __privateAdd(this, _shuttingDown, false);
506
540
  }
507
541
  connections;
508
542
  rooms;
@@ -515,14 +549,19 @@ var SseTransport = class {
515
549
  options;
516
550
  instanceId;
517
551
  offlineQueue;
518
- kind = "sse";
519
- logger = new Logger(SseTransport.name);
520
- async onApplicationShutdown() {
552
+ async beforeApplicationShutdown() {
553
+ __privateSet(this, _shuttingDown, true);
521
554
  this.heartbeat.stopAll();
522
555
  for (const conn of this.connections.allByTransport("sse")) {
523
556
  await this.disconnectLocal(conn.connectionId);
524
557
  }
525
558
  }
559
+ async onApplicationShutdown() {
560
+ await this.beforeApplicationShutdown();
561
+ }
562
+ get shuttingDown() {
563
+ return __privateGet(this, _shuttingDown);
564
+ }
526
565
  get heartbeatMs() {
527
566
  return this.options.sse?.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
528
567
  }
@@ -743,6 +782,7 @@ var SseTransport = class {
743
782
  }
744
783
  }
745
784
  };
785
+ _shuttingDown = new WeakMap();
746
786
  SseTransport = __decorateClass([
747
787
  Injectable(),
748
788
  __decorateParam(0, Inject(ConnectionRegistry)),
@@ -843,6 +883,7 @@ var SseSubscriptionHandler = class {
843
883
  async handle(req, res) {
844
884
  res.setHeader("Cache-Control", "no-cache, no-transform");
845
885
  res.setHeader("X-Accel-Buffering", "no");
886
+ this.refuseDuringShutdown();
846
887
  const done = this.authenticated.get(req);
847
888
  this.authenticated.delete(req);
848
889
  let authenticated;
@@ -851,11 +892,19 @@ var SseSubscriptionHandler = class {
851
892
  } catch (err) {
852
893
  throw this.toClientError(err, "SSE authentication failed");
853
894
  }
895
+ let stream;
854
896
  try {
855
- return await this.openStream(req, res, authenticated);
897
+ stream = await this.openStream(req, res, authenticated);
856
898
  } catch (err) {
857
899
  throw this.serverError(err, "SSE handshake failed");
858
900
  }
901
+ this.refuseDuringShutdown();
902
+ return stream;
903
+ }
904
+ refuseDuringShutdown() {
905
+ if (this.transport.shuttingDown) {
906
+ throw new ServiceUnavailableException(REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
907
+ }
859
908
  }
860
909
  async openStream(req, res, authenticated) {
861
910
  const { context, auth: resolvedAuth } = authenticated;
@@ -903,6 +952,10 @@ var SseSubscriptionHandler = class {
903
952
  }
904
953
  buildStream(p) {
905
954
  return new Observable((subscriber) => {
955
+ if (this.transport.shuttingDown) {
956
+ subscriber.complete();
957
+ return void 0;
958
+ }
906
959
  const inner = this.subscribePipeline(p, subscriber);
907
960
  if (!subscriber.closed && p.queueEvents.length > 0) {
908
961
  void this.offlineDelivery?.acknowledge(p.resolvedAuth.userId, p.queueEvents);
@@ -1132,11 +1185,7 @@ var ReauthenticationService = class {
1132
1185
  }
1133
1186
  async handleFailure(conn) {
1134
1187
  this.positiveCache.delete(conn.connectionId);
1135
- if (this.policy.onFailure === "event") {
1136
- await this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1137
- reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1138
- });
1139
- }
1188
+ if (this.policy.onFailure === "event") this.notify(conn);
1140
1189
  void Promise.resolve(
1141
1190
  this.hooks?.onReauthenticationFailed?.({
1142
1191
  connectionId: conn.connectionId,
@@ -1154,6 +1203,20 @@ var ReauthenticationService = class {
1154
1203
  });
1155
1204
  await this.realtime.disconnect(conn.connectionId, REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED);
1156
1205
  }
1206
+ notify(conn) {
1207
+ const failed = (err) => {
1208
+ this.logger.warn(
1209
+ `Reauthentication notification for ${conn.connectionId} failed, disconnecting anyway: ${describeError(err)}`
1210
+ );
1211
+ };
1212
+ try {
1213
+ this.realtime.emitToUser(conn.userId, RESERVED_EVENT_NAMES.CONNECTION_REAUTH_FAILED, {
1214
+ reason: REALTIME_ERROR_CODES.REAUTHENTICATION_FAILED
1215
+ }).catch(failed);
1216
+ } catch (err) {
1217
+ failed(err);
1218
+ }
1219
+ }
1157
1220
  };
1158
1221
  ReauthenticationService = __decorateClass([
1159
1222
  Injectable(),
@@ -1192,8 +1255,10 @@ var SHARED_SERVICES = [
1192
1255
  function assertModeSupported(wiring, mode, moduleName) {
1193
1256
  if (wiring.modes.includes(mode)) return;
1194
1257
  const alternative = mode === "sse" ? "'BymaxRealtimeModule' from '@bymax-one/nest-realtime'" : "'BymaxRealtimeWebSocketModule' from '@bymax-one/nest-realtime/websocket'";
1195
- throw new Error(
1196
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`
1258
+ throw realtimeError(
1259
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1260
+ `transport '${mode}' is not served by this module (it serves ${wiring.modes.map((m) => `'${m}'`).join(", ")}). Use ${alternative}.`,
1261
+ { who: moduleName }
1197
1262
  );
1198
1263
  }
1199
1264
  function warnIfSingleInstance(pubsub, transport, logger) {
@@ -1233,26 +1298,32 @@ function composeForRoot(moduleClass, wiring, logger, options) {
1233
1298
  }
1234
1299
  function assertSseEndpointApplies(asyncOptions, moduleName) {
1235
1300
  if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
1236
- throw new Error(
1237
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
1301
+ throw realtimeError(
1302
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1303
+ `sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`,
1304
+ { who: moduleName }
1238
1305
  );
1239
1306
  }
1240
1307
  function bindSseEndpoint(resolved, declared, bound, moduleName) {
1241
1308
  if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
1242
- throw new Error(
1243
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
1309
+ throw realtimeError(
1310
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1311
+ `the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`,
1312
+ { who: moduleName }
1244
1313
  );
1245
1314
  }
1246
1315
  return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
1247
1316
  }
1248
1317
  function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
1249
1318
  if (!raw) {
1250
- throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
1319
+ throw realtimeError(REALTIME_ERROR_CODES.INVALID_OPTIONS, `${source} returned nothing`);
1251
1320
  }
1252
1321
  validateOptions(raw);
1253
1322
  if (raw.transport !== declaredMode) {
1254
- throw new Error(
1255
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`
1323
+ throw realtimeError(
1324
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1325
+ `forRootAsync was registered for transport '${declaredMode}' but the factory resolved '${raw.transport}'`,
1326
+ { who: moduleName }
1256
1327
  );
1257
1328
  }
1258
1329
  const resolved = applyDefaults(raw);
@@ -1267,8 +1338,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
1267
1338
  asyncOptions.useExisting
1268
1339
  ].filter((pattern) => pattern !== void 0);
1269
1340
  if (patterns.length !== 1) {
1270
- throw new Error(
1271
- `[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`
1341
+ throw realtimeError(
1342
+ REALTIME_ERROR_CODES.INVALID_OPTIONS,
1343
+ `forRootAsync requires exactly one of useFactory, useClass, or useExisting (received ${patterns.length})`,
1344
+ { who: moduleName }
1272
1345
  );
1273
1346
  }
1274
1347
  assertModeSupported(wiring, asyncOptions.transport, moduleName);
@@ -1451,6 +1524,16 @@ BymaxRealtimeModule = __decorateClass([
1451
1524
  Module({})
1452
1525
  ], BymaxRealtimeModule);
1453
1526
  var MALFORMED_REPORT_INTERVAL_MS = 6e4;
1527
+ var CANNOT_PUBLISH = /* @__PURE__ */ new Set([
1528
+ "wait",
1529
+ "connecting",
1530
+ "connect",
1531
+ "reconnecting",
1532
+ "close",
1533
+ "end"
1534
+ ]);
1535
+ var PUBLISHER_WAIT_MS = 2e3;
1536
+ var CONNECTION_OVER = ["ready", "close", "reconnecting", "end"];
1454
1537
  function connectionReason(err) {
1455
1538
  const code = err?.code;
1456
1539
  const text = describeError(err);
@@ -1467,25 +1550,47 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1467
1550
  #subscribed = false;
1468
1551
  #outageLogged = false;
1469
1552
  #retired = /* @__PURE__ */ new WeakSet();
1553
+ #lastRefusal;
1470
1554
  constructor(options) {
1471
1555
  this.#pub = options.client;
1472
1556
  this.channel = options.channel ?? "bymax:realtime";
1473
1557
  }
1474
1558
  isSubscribed() {
1475
- return this.#subscribed;
1559
+ return this.#subscribed && !CANNOT_PUBLISH.has(this.#pub.status);
1476
1560
  }
1477
1561
  async publish(message) {
1478
1562
  const status = this.#pub.status;
1479
- if (status === "reconnecting" || status === "close" || status === "end") {
1480
- throw unavailableError(
1481
- REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1482
- _RedisRealtimePubSub.name,
1483
- `cannot publish to "${this.channel}"`,
1484
- new Error(`the Redis client is ${status}`)
1485
- );
1563
+ if (CANNOT_PUBLISH.has(status)) {
1564
+ this.connectLazyClient();
1565
+ throw this.cannotPublish(`the Redis client is ${status}`);
1486
1566
  }
1487
1567
  await this.#pub.publish(this.channel, JSON.stringify(message));
1488
1568
  }
1569
+ connectLazyClient() {
1570
+ if (this.#pub.status === "wait") this.#pub.connect().catch(() => void 0);
1571
+ }
1572
+ publisherSettled() {
1573
+ const pub = this.#pub;
1574
+ if (pub.status !== "connecting" && pub.status !== "connect") return Promise.resolve();
1575
+ return new Promise((resolve) => {
1576
+ const settle = () => {
1577
+ clearTimeout(deadline);
1578
+ for (const event of CONNECTION_OVER) pub.off(event, settle);
1579
+ resolve();
1580
+ };
1581
+ const deadline = setTimeout(settle, PUBLISHER_WAIT_MS);
1582
+ deadline.unref();
1583
+ for (const event of CONNECTION_OVER) pub.once(event, settle);
1584
+ });
1585
+ }
1586
+ cannotPublish(reason) {
1587
+ return unavailableError(
1588
+ REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE,
1589
+ _RedisRealtimePubSub.name,
1590
+ `cannot publish to "${this.channel}"`,
1591
+ new Error(reason)
1592
+ );
1593
+ }
1489
1594
  async subscribe(handler) {
1490
1595
  this.handlers.add(handler);
1491
1596
  let sub;
@@ -1496,6 +1601,7 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1496
1601
  this.#subInit = null;
1497
1602
  throw err;
1498
1603
  }
1604
+ await this.publisherSettled();
1499
1605
  return async () => {
1500
1606
  this.handlers.delete(handler);
1501
1607
  if (this.handlers.size === 0) {
@@ -1517,6 +1623,8 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1517
1623
  }
1518
1624
  async createSubscriber() {
1519
1625
  this.#outageLogged = false;
1626
+ this.#lastRefusal = void 0;
1627
+ this.connectLazyClient();
1520
1628
  const sub = this.#pub.duplicate({ autoResubscribe: false, enableOfflineQueue: true });
1521
1629
  let attached = false;
1522
1630
  sub.on("message", (_ch, payload) => this.dispatch(payload));
@@ -1574,14 +1682,18 @@ var RedisRealtimePubSub = class _RedisRealtimePubSub {
1574
1682
  refused(err) {
1575
1683
  if (err?.name !== "ReplyError") return;
1576
1684
  this.#subscribed = false;
1685
+ const reason = describeError(err);
1686
+ if (reason === this.#lastRefusal) return;
1687
+ this.#lastRefusal = reason;
1577
1688
  this.logger.warn(
1578
- `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${describeError(err)}`
1689
+ `${REALTIME_ERROR_CODES.PUBSUB_UNAVAILABLE}: the server refused the subscription to "${this.channel}": ${reason}`
1579
1690
  );
1580
1691
  }
1581
1692
  markUp() {
1582
1693
  if (this.#subscribed) return;
1583
1694
  this.#subscribed = true;
1584
1695
  this.#outageLogged = false;
1696
+ this.#lastRefusal = void 0;
1585
1697
  this.logger.log(
1586
1698
  `Subscribed to "${this.channel}"; remote events and revocations reach this instance`
1587
1699
  );
@@ -1684,4 +1796,4 @@ var RedisOfflineQueue = class _RedisOfflineQueue {
1684
1796
  }
1685
1797
  };
1686
1798
 
1687
- export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
1799
+ export { BymaxRealtimeModule, ConnectionRegistry, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, realtimeError, reportDeliveryFailure, resolveAuthTenant, sseWiring, unavailableError };
@@ -7,6 +7,9 @@ var platformSocket_io = require('@nestjs/platform-socket.io');
7
7
 
8
8
  var __defProp = Object.defineProperty;
9
9
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __typeError = (msg) => {
11
+ throw TypeError(msg);
12
+ };
10
13
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
14
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
12
15
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -23,8 +26,13 @@ var __decorateClass = (decorators, target, key, kind) => {
23
26
  return result;
24
27
  };
25
28
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
26
- var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
29
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
30
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
31
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
32
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
33
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
27
34
  var CONNECTION_ROOM_PREFIX = "connection";
35
+ var _shuttingDown;
28
36
  exports.WebSocketTransport = class WebSocketTransport {
29
37
  constructor(connections, rooms, auth, hooks, options) {
30
38
  this.connections = connections;
@@ -32,16 +40,23 @@ exports.WebSocketTransport = class WebSocketTransport {
32
40
  this.auth = auth;
33
41
  this.hooks = hooks;
34
42
  this.options = options;
43
+ __publicField(this, "kind", "websocket");
44
+ __publicField(this, "logger", new common.Logger(exports.WebSocketTransport.name));
45
+ __publicField(this, "server", null);
46
+ __publicField(this, "warnedUnattached", false);
47
+ __privateAdd(this, _shuttingDown, false);
35
48
  }
36
49
  connections;
37
50
  rooms;
38
51
  auth;
39
52
  hooks;
40
53
  options;
41
- kind = "websocket";
42
- logger = new common.Logger(exports.WebSocketTransport.name);
43
- server = null;
44
- warnedUnattached = false;
54
+ async beforeApplicationShutdown() {
55
+ __privateSet(this, _shuttingDown, true);
56
+ }
57
+ get shuttingDown() {
58
+ return __privateGet(this, _shuttingDown);
59
+ }
45
60
  setServer(server) {
46
61
  this.server = server;
47
62
  this.logger.log("Socket.IO server wired to WebSocketTransport");
@@ -181,6 +196,7 @@ exports.WebSocketTransport = class WebSocketTransport {
181
196
  }
182
197
  }
183
198
  };
199
+ _shuttingDown = new WeakMap();
184
200
  exports.WebSocketTransport = __decorateClass([
185
201
  common.Injectable(),
186
202
  __decorateParam(0, common.Inject(internal.ConnectionRegistry)),
@@ -251,21 +267,24 @@ exports.CompositeTransport = class CompositeTransport {
251
267
  const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
252
268
  if (reasons.length === 0) return;
253
269
  if (reasons.length === 1) throw reasons[0];
254
- throw internal.unavailableError(
255
- internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
256
- exports.CompositeTransport.name,
257
- `${op} of ${connectionId} failed on both transports`,
258
- new AggregateError(reasons, reasons.map(internal.describeError).join("; "))
259
- );
270
+ throw this.allFailed(`${op} of ${connectionId}`, reasons);
260
271
  }
261
272
  async fanOut(op, ...tasks) {
262
273
  const results = await Promise.allSettled(tasks.map((t) => t()));
263
- for (const result of results) {
264
- if (result.status === "rejected") {
265
- this.logger.warn(`Composite ${op} partially failed: ${internal.describeError(result.reason)}`);
266
- }
274
+ const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
275
+ if (reasons.length === tasks.length) throw this.allFailed(op, reasons);
276
+ for (const reason of reasons) {
277
+ this.logger.warn(`Composite ${op} partially failed: ${internal.describeError(reason)}`);
267
278
  }
268
279
  }
280
+ allFailed(what, reasons) {
281
+ return internal.unavailableError(
282
+ internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
283
+ exports.CompositeTransport.name,
284
+ `${what} failed on both transports`,
285
+ new AggregateError(reasons, reasons.map(internal.describeError).join("; "))
286
+ );
287
+ }
269
288
  };
270
289
  exports.CompositeTransport = __decorateClass([
271
290
  common.Injectable(),
@@ -322,9 +341,10 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
322
341
  server.adapter(createAdapter(pub, sub));
323
342
  } catch (err) {
324
343
  const reason = internal.describeError(err);
325
- throw new Error(
326
- `[${_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.`,
327
- { cause: err }
344
+ throw internal.realtimeError(
345
+ internal.REALTIME_ERROR_CODES.REDIS_ADAPTER_FAILED,
346
+ `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.`,
347
+ { who: _RealtimeIoAdapter.name, cause: err }
328
348
  );
329
349
  }
330
350
  this.adapterLogger.log(
@@ -349,7 +369,15 @@ exports.RealtimeGateway = class RealtimeGateway {
349
369
  authenticated = /* @__PURE__ */ new WeakMap();
350
370
  authenticateHandshake = async (socket, next) => {
351
371
  try {
372
+ if (this.transport.shuttingDown) {
373
+ next(this.unavailable());
374
+ return;
375
+ }
352
376
  const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
377
+ if (this.transport.shuttingDown) {
378
+ next(this.unavailable());
379
+ return;
380
+ }
353
381
  if (!auth) {
354
382
  const refusal = new Error(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
355
383
  refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
@@ -365,6 +393,11 @@ exports.RealtimeGateway = class RealtimeGateway {
365
393
  next(new Error("Internal Server Error"));
366
394
  }
367
395
  };
396
+ unavailable() {
397
+ const refusal = new Error(internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE);
398
+ refusal.data = { code: internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE };
399
+ return refusal;
400
+ }
368
401
  afterInit(server) {
369
402
  server.use(this.authenticateHandshake);
370
403
  this.transport.setServer(server);
@@ -401,6 +434,10 @@ exports.RealtimeGateway = class RealtimeGateway {
401
434
  let resolvedAuth = this.authenticated.get(socket);
402
435
  this.authenticated.delete(socket);
403
436
  if (!resolvedAuth) {
437
+ if (this.transport.shuttingDown) {
438
+ socket.disconnect(true);
439
+ return;
440
+ }
404
441
  const auth = await this.transport.authenticator().authenticate(this.buildAuthContext(socket));
405
442
  if (!auth) {
406
443
  socket.disconnect(true);
@@ -72,6 +72,7 @@ declare class BymaxRealtimeWebSocketModule {
72
72
  * the gateway. All emit methods are safe no-ops while the server is unset.
73
73
  */
74
74
  declare class WebSocketTransport implements ITransport {
75
+ #private;
75
76
  private readonly connections;
76
77
  private readonly rooms;
77
78
  private readonly auth;
@@ -83,6 +84,16 @@ declare class WebSocketTransport implements ITransport {
83
84
  private server;
84
85
  private warnedUnattached;
85
86
  constructor(connections: ConnectionRegistry, rooms: RoomRegistry, auth: IConnectionAuthenticator, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions);
87
+ /**
88
+ * Mark shutdown as begun, so the gateway refuses a handshake from here on.
89
+ *
90
+ * Socket.IO closes every connection that is open when the server closes, so no connection is
91
+ * torn down here; a socket accepted after this point would only be closed a moment later, and
92
+ * its authenticator may already depend on a store the host has closed.
93
+ */
94
+ beforeApplicationShutdown(): Promise<void>;
95
+ /** Whether shutdown has begun, after which a new handshake is refused. */
96
+ get shuttingDown(): boolean;
86
97
  /**
87
98
  * Wire the Socket.IO server. Called by `RealtimeGateway.afterInit`.
88
99
  *
@@ -238,6 +249,8 @@ declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnG
238
249
  private readonly authenticated;
239
250
  /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
240
251
  private readonly authenticateHandshake;
252
+ /** The refusal for a handshake that arrives once shutdown has begun: a `connect_error` carrying `data.code`. */
253
+ private unavailable;
241
254
  /** Wire the resolved Socket.IO server to the transport after gateway init. */
242
255
  afterInit(server: Server): void;
243
256
  /** Report a server that `RealtimeIoAdapter` did not create: its options are dropped. */
@@ -350,7 +363,8 @@ declare class RealtimeIoAdapter extends IoAdapter {
350
363
  *
351
364
  * Every `emitTo*` and `broadcast` invokes both SSE and WebSocket transports in
352
365
  * parallel via `Promise.allSettled` so a failure in one never aborts the other.
353
- * Failures are logged as warnings without rethrowing.
366
+ * A failure of one is logged as a warning and the call resolves; a failure of both
367
+ * rejects.
354
368
  *
355
369
  * `joinRoom`, `leaveRoom`, and `disconnect` ask both transports and settle both: each
356
370
  * transport acts only on a connection it holds, and a connection neither holds is handed
@@ -432,10 +446,12 @@ declare class CompositeTransport implements ITransport {
432
446
  /**
433
447
  * Run two transport tasks in parallel via `Promise.allSettled`.
434
448
  *
435
- * A rejection in either task is logged as a warning and does not propagate,
436
- * ensuring one failing transport never blocks delivery on the other.
449
+ * One task failing is logged as a warning and the call resolves, so one failing transport
450
+ * never blocks delivery on the other. Every task failing rejects.
437
451
  */
438
452
  private fanOut;
453
+ /** The rejection for an operation that failed on every transport, with every reason in `cause`. */
454
+ private allFailed;
439
455
  }
440
456
 
441
457
  export { BymaxRealtimeWebSocketModule, CompositeTransport, RealtimeGateway, RealtimeIoAdapter, WebSocketTransport };