@bymax-one/nest-realtime 1.2.17 → 1.2.19

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,5 +1,5 @@
1
1
  import { DynamicModule, INestApplicationContext } from '@nestjs/common';
2
- import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, AuthenticationGate, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, ConnectionAdmission, ConnectionAuthContext, AuthenticationResult, AdmissionTicket, SseTransport } from '@bymax-one/nest-realtime/internal';
2
+ import { WebSocketRealtimeModuleOptions, WebSocketRealtimeModuleAsyncOptions, ITransport, ConnectionRegistry, RoomRegistry, AuthenticationGate, IConnectionLifecycleHooks, BymaxRealtimeModuleOptions, ConnectionAdmission, RealtimeMetricsTally, ConnectionAuthContext, AuthenticationResult, AdmissionTicket, RealtimeTracing, SseTransport } from '@bymax-one/nest-realtime/internal';
3
3
  export { WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions } from '@bymax-one/nest-realtime/internal';
4
4
  import { Server, Socket, ServerOptions } from 'socket.io';
5
5
  import { OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
@@ -79,12 +79,13 @@ declare class WebSocketTransport implements ITransport {
79
79
  private readonly hooks;
80
80
  private readonly options;
81
81
  private readonly admission?;
82
+ private readonly tally?;
82
83
  readonly kind: "websocket";
83
84
  private readonly logger;
84
85
  /** Nullable until the gateway's afterInit wires the instance. */
85
86
  private server;
86
87
  private warnedUnattached;
87
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, gate: AuthenticationGate, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, admission?: ConnectionAdmission | undefined);
88
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, gate: AuthenticationGate, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, admission?: ConnectionAdmission | undefined, tally?: RealtimeMetricsTally | undefined);
88
89
  /**
89
90
  * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
90
91
  * nearer the root than the realtime module still runs first, and until it returns a handshake is
@@ -263,15 +264,24 @@ declare class WebSocketTransport implements ITransport {
263
264
  declare class RealtimeGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
264
265
  private readonly transport;
265
266
  private readonly options;
267
+ private readonly tally?;
268
+ private readonly tracing?;
266
269
  private readonly logger;
267
270
  server: Server;
268
- constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions);
271
+ constructor(transport: WebSocketTransport, options: BymaxRealtimeModuleOptions, tally?: RealtimeMetricsTally | undefined, tracing?: RealtimeTracing | undefined);
269
272
  /** Identities the handshake middleware resolved, until `handleConnection` takes them. */
270
273
  private readonly authenticated;
271
274
  /** The place held for a socket from before its handshake is authenticated until it is registered. */
272
275
  private readonly tickets;
273
- /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
276
+ /**
277
+ * Authenticate before accept, inside the `realtime.handshake` span when tracing is wired.
278
+ *
279
+ * The refusal the handshake produces is held until the span has ended, so that the span carries it, and is
280
+ * then handed to `next`.
281
+ */
274
282
  private readonly authenticateHandshake;
283
+ /** Authenticate before accept: a refusal is a `connect_error` with `data.code`; a failure is generic. */
284
+ private handshake;
275
285
  /**
276
286
  * The error a handshake that failed is answered with, after the log line the failure earns.
277
287
  *
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { Injectable, Inject, Optional, Logger, Global, Module } from '@nestjs/common';
3
- import { ConnectionRegistry, RoomRegistry, AuthenticationGate, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, ConnectionAdmission, SseTransport, REALTIME_ERROR_CODES, describeError, ROOM_PREFIXES, runHook, DEFAULT_HOOK_TIMEOUT_MS, requireRoomName, refuseReservedRoom, unavailableError, UNBOUNDED_TICKET, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, admitRooms, AuthenticationUnavailableError, ConnectionLimitError, parseCookieHeader, RESERVED_EVENT_NAMES, quitWithin, realtimeError } from '@bymax-one/nest-realtime/internal';
3
+ import { ConnectionRegistry, RoomRegistry, AuthenticationGate, REALTIME_HOOKS_TOKEN, REALTIME_OPTIONS_TOKEN, ConnectionAdmission, RealtimeMetricsTally, SseTransport, RealtimeTracing, logEvent, ROOM_PREFIXES, runHook, DEFAULT_HOOK_TIMEOUT_MS, requireRoomName, refuseReservedRoom, unavailableError, REALTIME_ERROR_CODES, UNBOUNDED_TICKET, composeForRoot, composeForRootAsync, REALTIME_TRANSPORT_TOKEN, SseSubscriptionHandler, RealtimePubSubSubscriber, createSseController, resolveAuthTenant, assertIdentityIsNotBlank, admitRooms, ConnectionLimitError, AuthenticationUnavailableError, parseCookieHeader, RESERVED_EVENT_NAMES, describeError, quitWithin, realtimeError } from '@bymax-one/nest-realtime/internal';
4
4
  import { WebSocketServer, WebSocketGateway } from '@nestjs/websockets';
5
5
  import { IoAdapter } from '@nestjs/platform-socket.io';
6
6
 
@@ -35,13 +35,14 @@ var CONNECTION_ROOM_PREFIX = "connection";
35
35
  var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
36
36
  var _shuttingDown;
37
37
  var WebSocketTransport = class {
38
- constructor(connections, rooms, gate, hooks, options, admission) {
38
+ constructor(connections, rooms, gate, hooks, options, admission, tally) {
39
39
  this.connections = connections;
40
40
  this.rooms = rooms;
41
41
  this.gate = gate;
42
42
  this.hooks = hooks;
43
43
  this.options = options;
44
44
  this.admission = admission;
45
+ this.tally = tally;
45
46
  __publicField(this, "kind", "websocket");
46
47
  __publicField(this, "logger", new Logger(WebSocketTransport.name));
47
48
  __publicField(this, "server", null);
@@ -54,6 +55,7 @@ var WebSocketTransport = class {
54
55
  hooks;
55
56
  options;
56
57
  admission;
58
+ tally;
57
59
  onModuleDestroy() {
58
60
  __privateSet(this, _shuttingDown, true);
59
61
  }
@@ -70,8 +72,12 @@ var WebSocketTransport = class {
70
72
  attached(op) {
71
73
  if (!this.server && !this.warnedUnattached) {
72
74
  this.warnedUnattached = true;
73
- this.logger.warn(
74
- `${REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE} op=${op}: no WebSocket server is attached yet, so emits are dropped until the gateway initialises`
75
+ logEvent(
76
+ this.logger,
77
+ "warn",
78
+ "REALTIME_SERVER_NOT_ATTACHED",
79
+ "no WebSocket server is attached yet, so emits are dropped until the gateway initialises",
80
+ { op }
75
81
  );
76
82
  }
77
83
  return this.server;
@@ -109,9 +115,17 @@ var WebSocketTransport = class {
109
115
  await this.evictBeyondLimit(auth.userId);
110
116
  const failed = await this.runOnConnect(socket, auth, connectedAt);
111
117
  if (!failed) return;
112
- const message = `onConnect hook failed: ${describeError(failed.error)}`;
113
- if (this.options.onConnectFailure === "close") throw new Error(message);
114
- this.logger.error(message);
118
+ if (this.options.onConnectFailure === "close") {
119
+ throw new Error("onConnect hook failed", { cause: failed.error });
120
+ }
121
+ logEvent(
122
+ this.logger,
123
+ "error",
124
+ "REALTIME_HOOK_FAILED",
125
+ "onConnect hook failed",
126
+ { hook: "onConnect" },
127
+ failed.error
128
+ );
115
129
  }
116
130
  async joinRooms(socket, auth) {
117
131
  await socket.join(`${ROOM_PREFIXES.USER}:${auth.userId}`);
@@ -159,20 +173,35 @@ var WebSocketTransport = class {
159
173
  () => this.hooks.onDisconnect?.(disconnectMeta),
160
174
  this.options.hookTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
161
175
  );
162
- if (failed) this.logger.error(`onDisconnect hook failed: ${describeError(failed.error)}`);
176
+ if (failed) {
177
+ logEvent(
178
+ this.logger,
179
+ "error",
180
+ "REALTIME_HOOK_FAILED",
181
+ `onDisconnect hook failed`,
182
+ {
183
+ hook: "onDisconnect"
184
+ },
185
+ failed.error
186
+ );
187
+ }
163
188
  }
164
189
  async emitToUser(userId, event, data) {
165
190
  this.attached("emitToUser")?.to(`${ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
191
+ if (this.server) this.tally?.emitted("websocket");
166
192
  }
167
193
  async emitToTenant(tenantId, event, data) {
168
194
  this.attached("emitToTenant")?.to(`${ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
195
+ if (this.server) this.tally?.emitted("websocket");
169
196
  }
170
197
  async emitToRoom(roomId, event, data) {
171
198
  requireRoomName("emitToRoom", roomId);
172
199
  this.attached("emitToRoom")?.to(roomId).emit(event, data);
200
+ if (this.server) this.tally?.emitted("websocket");
173
201
  }
174
202
  async broadcast(event, data) {
175
203
  this.attached("broadcast")?.emit(event, data);
204
+ if (this.server) this.tally?.emitted("websocket");
176
205
  }
177
206
  async joinRoom(connectionId, roomId) {
178
207
  refuseReservedRoom("joinRoom", roomId);
@@ -222,6 +251,7 @@ var WebSocketTransport = class {
222
251
  let userConnections = this.connections.byUser(userId, "websocket");
223
252
  while (userConnections.length > max) {
224
253
  const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
254
+ this.tally?.evicted("per_user_cap");
225
255
  await this.disconnect(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
226
256
  await this.unregisterSocket(oldest.connectionId, REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
227
257
  userConnections = this.connections.byUser(userId, "websocket");
@@ -237,7 +267,9 @@ WebSocketTransport = __decorateClass([
237
267
  __decorateParam(3, Inject(REALTIME_HOOKS_TOKEN)),
238
268
  __decorateParam(4, Inject(REALTIME_OPTIONS_TOKEN)),
239
269
  __decorateParam(5, Optional()),
240
- __decorateParam(5, Inject(ConnectionAdmission))
270
+ __decorateParam(5, Inject(ConnectionAdmission)),
271
+ __decorateParam(6, Optional()),
272
+ __decorateParam(6, Inject(RealtimeMetricsTally))
241
273
  ], WebSocketTransport);
242
274
 
243
275
  // src/websocket/transports/composite/composite.transport.ts
@@ -311,7 +343,14 @@ var CompositeTransport = class {
311
343
  const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
312
344
  if (reasons.length === tasks.length) throw this.allFailed(op, reasons);
313
345
  for (const reason of reasons) {
314
- this.logger.warn(`Composite ${op} partially failed: ${describeError(reason)}`);
346
+ logEvent(
347
+ this.logger,
348
+ "warn",
349
+ "REALTIME_COMPOSITE_PARTIAL_FAILURE",
350
+ `Composite ${op} partially failed`,
351
+ { op },
352
+ reason
353
+ );
315
354
  }
316
355
  }
317
356
  allFailed(what, reasons) {
@@ -390,7 +429,12 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends IoAdapter {
390
429
  if (reported) return;
391
430
  reported = true;
392
431
  const kind = Object(err).constructor?.name ?? "Error";
393
- this.adapterLogger.warn(`Redis adapter subscriber command failed (${kind})`);
432
+ logEvent(
433
+ this.adapterLogger,
434
+ "warn",
435
+ "REALTIME_ADAPTER_COMMAND_FAILED",
436
+ `Redis adapter subscriber command failed (${kind})`
437
+ );
394
438
  });
395
439
  return pending;
396
440
  };
@@ -431,21 +475,41 @@ function firstQueryValue(value) {
431
475
  return Array.isArray(value) ? value[0] : value;
432
476
  }
433
477
  var RealtimeGateway = class {
434
- constructor(transport, options) {
478
+ constructor(transport, options, tally, tracing) {
435
479
  this.transport = transport;
436
480
  this.options = options;
481
+ this.tally = tally;
482
+ this.tracing = tracing;
437
483
  }
438
484
  transport;
439
485
  options;
486
+ tally;
487
+ tracing;
440
488
  logger = new Logger(RealtimeGateway.name);
441
489
  server;
442
490
  authenticated = /* @__PURE__ */ new WeakMap();
443
491
  tickets = /* @__PURE__ */ new WeakMap();
444
492
  authenticateHandshake = async (socket, next) => {
493
+ let outcome;
494
+ const run = async () => {
495
+ await this.handshake(socket, (err) => {
496
+ outcome = err;
497
+ });
498
+ if (outcome) throw outcome;
499
+ };
500
+ try {
501
+ await (this.tracing ? this.tracing.span("realtime.handshake", { "bymax.realtime.transport": "websocket" }, run) : run());
502
+ } catch {
503
+ }
504
+ if (outcome) next(outcome);
505
+ else next();
506
+ };
507
+ async handshake(socket, next) {
445
508
  let ticket;
446
509
  let handedOver = false;
447
510
  try {
448
511
  if (this.transport.shuttingDown) {
512
+ this.tally?.refused("unavailable");
449
513
  next(this.unavailable());
450
514
  return;
451
515
  }
@@ -453,10 +517,12 @@ var RealtimeGateway = class {
453
517
  ticket = held;
454
518
  const auth = await this.transport.authenticate(this.buildAuthContext(socket));
455
519
  if (this.transport.shuttingDown) {
520
+ this.tally?.refused("unavailable");
456
521
  next(this.unavailable());
457
522
  return;
458
523
  }
459
524
  if (!auth) {
525
+ this.tally?.refused("unauthorized");
460
526
  const refusal = new Error(REALTIME_ERROR_CODES.AUTH_FAILED);
461
527
  refusal.data = { code: REALTIME_ERROR_CODES.AUTH_FAILED };
462
528
  next(refusal);
@@ -473,12 +539,25 @@ var RealtimeGateway = class {
473
539
  } finally {
474
540
  if (!handedOver) ticket?.release();
475
541
  }
476
- };
542
+ }
477
543
  refusalFor(socket, err) {
478
- if (err instanceof AuthenticationUnavailableError || err instanceof ConnectionLimitError) {
544
+ if (err instanceof ConnectionLimitError) {
545
+ this.tally?.refused("limit");
479
546
  return this.unavailable("Internal Server Error");
480
547
  }
481
- this.logger.error(`handshake refused for socket ${socket.id}: ${describeError(err)}`);
548
+ if (err instanceof AuthenticationUnavailableError) {
549
+ this.tally?.refused("unavailable");
550
+ return this.unavailable("Internal Server Error");
551
+ }
552
+ this.tally?.refused("error");
553
+ logEvent(
554
+ this.logger,
555
+ "error",
556
+ "REALTIME_HANDSHAKE_FAILED",
557
+ `handshake refused`,
558
+ { socketId: socket.id },
559
+ err
560
+ );
482
561
  return new Error("Internal Server Error");
483
562
  }
484
563
  unavailable(message = REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE) {
@@ -494,7 +573,10 @@ var RealtimeGateway = class {
494
573
  }
495
574
  reportMissingAdapter() {
496
575
  const configured = Object.keys(this.options.websocket ?? {});
497
- this.logger.error(
576
+ logEvent(
577
+ this.logger,
578
+ "error",
579
+ "REALTIME_ADAPTER_MISSING",
498
580
  "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'."
499
581
  );
500
582
  }
@@ -535,9 +617,19 @@ var RealtimeGateway = class {
535
617
  });
536
618
  }
537
619
  } catch (err) {
538
- if (!(err instanceof AuthenticationUnavailableError || err instanceof ConnectionLimitError)) {
539
- this.logger.error(
540
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${describeError(err)}`
620
+ if (err instanceof ConnectionLimitError) {
621
+ this.tally?.refused("limit");
622
+ } else if (err instanceof AuthenticationUnavailableError) {
623
+ this.tally?.refused("unavailable");
624
+ } else {
625
+ this.tally?.refused("error");
626
+ logEvent(
627
+ this.logger,
628
+ "error",
629
+ "REALTIME_HANDSHAKE_FAILED",
630
+ `handleConnection threw \u2014 disconnecting`,
631
+ { socketId: socket.id },
632
+ err
541
633
  );
542
634
  }
543
635
  socket.disconnect(true);
@@ -564,6 +656,7 @@ var RealtimeGateway = class {
564
656
  this.tickets.delete(socket);
565
657
  if (auth) return { auth, ticket };
566
658
  if (this.transport.shuttingDown) {
659
+ this.tally?.refused("unavailable");
567
660
  socket.disconnect(true);
568
661
  return void 0;
569
662
  }
@@ -571,6 +664,7 @@ var RealtimeGateway = class {
571
664
  try {
572
665
  const fresh = await this.transport.authenticate(this.buildAuthContext(socket));
573
666
  if (!fresh) {
667
+ this.tally?.refused("unauthorized");
574
668
  socket.disconnect(true);
575
669
  held.release();
576
670
  return void 0;
@@ -602,7 +696,11 @@ RealtimeGateway = __decorateClass([
602
696
  cors: { origin: false }
603
697
  }),
604
698
  __decorateParam(0, Inject(WebSocketTransport)),
605
- __decorateParam(1, Inject(REALTIME_OPTIONS_TOKEN))
699
+ __decorateParam(1, Inject(REALTIME_OPTIONS_TOKEN)),
700
+ __decorateParam(2, Optional()),
701
+ __decorateParam(2, Inject(RealtimeMetricsTally)),
702
+ __decorateParam(3, Optional()),
703
+ __decorateParam(3, Inject(RealtimeTracing))
606
704
  ], RealtimeGateway);
607
705
 
608
706
  // src/websocket/websocket-wiring.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-realtime",
3
- "version": "1.2.17",
3
+ "version": "1.2.19",
4
4
  "description": "Realtime backend → frontend communication for NestJS — dual-transport SSE (default) and WebSocket (opt-in) with a unified server-side API.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -64,6 +64,16 @@
64
64
  "default": "./dist/websocket/index.cjs"
65
65
  }
66
66
  },
67
+ "./observability": {
68
+ "import": {
69
+ "types": "./dist/observability/index.d.ts",
70
+ "default": "./dist/observability/index.mjs"
71
+ },
72
+ "require": {
73
+ "types": "./dist/observability/index.d.cts",
74
+ "default": "./dist/observability/index.cjs"
75
+ }
76
+ },
67
77
  "./internal": {
68
78
  "import": {
69
79
  "types": "./dist/internal/index.d.ts",
@@ -87,6 +97,9 @@
87
97
  "websocket": [
88
98
  "./dist/websocket/index.d.cts"
89
99
  ],
100
+ "observability": [
101
+ "./dist/observability/index.d.cts"
102
+ ],
90
103
  "internal": [
91
104
  "./dist/internal/index.d.cts"
92
105
  ]
@@ -125,12 +138,15 @@
125
138
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.server.json"
126
139
  },
127
140
  "peerDependencies": {
141
+ "@bymax-one/nest-core": "^1.1.0",
128
142
  "@nestjs/common": "^11.0.16",
129
143
  "@nestjs/core": "^11.1.18",
130
144
  "@nestjs/platform-socket.io": "^11.0.0",
131
145
  "@nestjs/websockets": "^11.0.0",
146
+ "@opentelemetry/api": "^1.9.0",
132
147
  "@socket.io/redis-adapter": "^8.0.0",
133
148
  "ioredis": "^6.0.0",
149
+ "prom-client": "^15.0.0",
134
150
  "react": "^19.0.0",
135
151
  "react-dom": "^19.0.0",
136
152
  "reflect-metadata": "^0.2.0",
@@ -139,13 +155,16 @@
139
155
  "socket.io-client": "^4.0.0"
140
156
  },
141
157
  "peerDependenciesMeta": {
142
- "@nestjs/websockets": {
158
+ "@bymax-one/nest-core": {
143
159
  "optional": true
144
160
  },
145
161
  "@nestjs/platform-socket.io": {
146
162
  "optional": true
147
163
  },
148
- "socket.io": {
164
+ "@nestjs/websockets": {
165
+ "optional": true
166
+ },
167
+ "@opentelemetry/api": {
149
168
  "optional": true
150
169
  },
151
170
  "@socket.io/redis-adapter": {
@@ -154,24 +173,32 @@
154
173
  "ioredis": {
155
174
  "optional": true
156
175
  },
176
+ "prom-client": {
177
+ "optional": true
178
+ },
157
179
  "react": {
158
180
  "optional": true
159
181
  },
160
182
  "react-dom": {
161
183
  "optional": true
162
184
  },
185
+ "socket.io": {
186
+ "optional": true
187
+ },
163
188
  "socket.io-client": {
164
189
  "optional": true
165
190
  }
166
191
  },
167
192
  "devDependencies": {
168
193
  "@arethetypeswrong/cli": "^0.18.5",
194
+ "@bymax-one/nest-core": "1.6.10",
169
195
  "@nestjs/common": "^11.1.28",
170
196
  "@nestjs/core": "^11.1.28",
171
197
  "@nestjs/platform-express": "^11.1.28",
172
198
  "@nestjs/platform-socket.io": "^11.1.28",
173
199
  "@nestjs/testing": "^11.1.28",
174
200
  "@nestjs/websockets": "^11.1.28",
201
+ "@opentelemetry/api": "^1.10.0",
175
202
  "@socket.io/redis-adapter": "^8.0.0",
176
203
  "@stryker-mutator/core": "^9.6.1",
177
204
  "@stryker-mutator/jest-runner": "^9.6.1",
@@ -201,6 +228,7 @@
201
228
  "jest-environment-jsdom": "^30.0.0",
202
229
  "jsonwebtoken": "^9.0.3",
203
230
  "prettier": "^3.9.6",
231
+ "prom-client": "^15.1.3",
204
232
  "react": "^19.2.8",
205
233
  "react-dom": "^19.2.8",
206
234
  "reflect-metadata": "^0.2.2",