@bymax-one/nest-realtime 1.2.18 → 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.
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ var metrics = require('@bymax-one/nest-core/metrics');
4
+ var common = require('@nestjs/common');
5
+ var promClient = require('prom-client');
6
+ var internal = require('@bymax-one/nest-realtime/internal');
7
+ var health = require('@bymax-one/nest-core/health');
8
+
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __decorateClass = (decorators, target, key, kind) => {
11
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
12
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
13
+ if (decorator = decorators[i])
14
+ result = (decorator(result)) || result;
15
+ return result;
16
+ };
17
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
18
+ function countedBy(registry, spec) {
19
+ const { label, keys, read } = spec;
20
+ new promClient.Counter({
21
+ name: spec.name,
22
+ help: spec.help,
23
+ labelNames: [label],
24
+ registers: [registry],
25
+ collect() {
26
+ this.reset();
27
+ const counts = read();
28
+ for (const key of keys) this.inc({ [label]: key }, counts[key]);
29
+ }
30
+ });
31
+ }
32
+ exports.RealtimeMetrics = class RealtimeMetrics {
33
+ constructor(tally, connections) {
34
+ this.tally = tally;
35
+ this.connections = connections;
36
+ }
37
+ tally;
38
+ connections;
39
+ registerMetrics(registry) {
40
+ const { tally, connections } = this;
41
+ new promClient.Gauge({
42
+ name: "bymax_realtime_connections",
43
+ help: "Connections open on this instance now, by transport.",
44
+ labelNames: ["transport"],
45
+ registers: [registry],
46
+ collect() {
47
+ for (const transport of internal.TALLY_TRANSPORTS) {
48
+ this.set({ transport }, connections.allByTransport(transport).length);
49
+ }
50
+ }
51
+ });
52
+ countedBy(registry, {
53
+ name: "bymax_realtime_connections_refused_total",
54
+ help: "Handshakes refused since start, by reason: limit, unauthorized, unavailable or error.",
55
+ label: "reason",
56
+ keys: internal.REFUSAL_REASONS,
57
+ read: () => tally.snapshot().refused
58
+ });
59
+ countedBy(registry, {
60
+ name: "bymax_realtime_evictions_total",
61
+ help: "Connections closed since start, by reason: per_user_cap, slow_consumer or revoked.",
62
+ label: "reason",
63
+ keys: internal.EVICTION_REASONS,
64
+ read: () => tally.snapshot().evicted
65
+ });
66
+ countedBy(registry, {
67
+ name: "bymax_realtime_events_emitted_total",
68
+ help: "Emit calls handled on this instance since start, by transport, whether or not a connection received the event.",
69
+ label: "transport",
70
+ keys: internal.TALLY_TRANSPORTS,
71
+ read: () => tally.snapshot().emitted
72
+ });
73
+ new promClient.Counter({
74
+ name: "bymax_realtime_slow_consumer_drops_total",
75
+ help: "Connections cut since start for not reading what they were sent.",
76
+ registers: [registry],
77
+ collect() {
78
+ this.reset();
79
+ this.inc(tally.snapshot().slowConsumerDrops);
80
+ }
81
+ });
82
+ }
83
+ };
84
+ exports.RealtimeMetrics = __decorateClass([
85
+ metrics.BymaxMetricsContributor(),
86
+ common.Injectable(),
87
+ __decorateParam(0, common.Inject(internal.RealtimeMetricsTally)),
88
+ __decorateParam(1, common.Inject(internal.ConnectionRegistry))
89
+ ], exports.RealtimeMetrics);
90
+ exports.RealtimePubSubHealthIndicator = class RealtimePubSubHealthIndicator {
91
+ constructor(pubsub) {
92
+ this.pubsub = pubsub;
93
+ }
94
+ pubsub;
95
+ name = "realtime-pubsub";
96
+ async check() {
97
+ return { status: this.pubsub.isSubscribed?.() === false ? "down" : "up" };
98
+ }
99
+ };
100
+ exports.RealtimePubSubHealthIndicator = __decorateClass([
101
+ health.BymaxHealthIndicator(),
102
+ common.Injectable(),
103
+ __decorateParam(0, common.Inject(internal.REALTIME_PUBSUB_TOKEN))
104
+ ], exports.RealtimePubSubHealthIndicator);
@@ -0,0 +1,47 @@
1
+ import { IMetricsContributor, MetricsRegistry } from '@bymax-one/nest-core/metrics';
2
+ import { RealtimeMetricsTally, ConnectionRegistry, IRealtimePubSub } from '@bymax-one/nest-realtime/internal';
3
+ import { IHealthIndicator, HealthIndicatorResult } from '@bymax-one/nest-core/health';
4
+
5
+ /**
6
+ * Registers the realtime collectors on the registry the scrape endpoint serves.
7
+ *
8
+ * Every counter is read from the tally on each scrape, after a reset, instead of being written as events
9
+ * arrive: the tally starts counting before this class runs, and a counter fed by events would drop that window.
10
+ * Labels are the closed sets the tally is keyed by; no id, tenant, user or message ever becomes one.
11
+ *
12
+ * @example
13
+ * // providers: [RealtimeMetrics] (BymaxCoreModule discovers it and calls registerMetrics once at bootstrap)
14
+ */
15
+ declare class RealtimeMetrics implements IMetricsContributor {
16
+ private readonly tally;
17
+ private readonly connections;
18
+ constructor(tally: RealtimeMetricsTally, connections: ConnectionRegistry);
19
+ /**
20
+ * Register the collectors against the scrape registry.
21
+ *
22
+ * @param registry - The registry the scrape endpoint serves.
23
+ */
24
+ registerMetrics(registry: MetricsRegistry): void;
25
+ }
26
+
27
+ /**
28
+ * Reports whether this instance still receives what the other instances publish.
29
+ *
30
+ * It asks the bus for its own state and sends nothing, so it is as cheap as a property read and needs no
31
+ * timeout of its own. A bus that does not report its state, such as the in-memory one, counts as up: there
32
+ * is no signal to be alarmed by, and a probe that failed for want of one would take the instance out of
33
+ * rotation for nothing. The result carries no detail, because a host name or a credential must not reach a
34
+ * readiness response.
35
+ *
36
+ * @example
37
+ * // providers: [RealtimePubSubHealthIndicator] (BymaxCoreModule discovers it with `health.autoDiscover`)
38
+ */
39
+ declare class RealtimePubSubHealthIndicator implements IHealthIndicator {
40
+ private readonly pubsub;
41
+ readonly name = "realtime-pubsub";
42
+ constructor(pubsub: IRealtimePubSub);
43
+ /** The indicator's outcome: `down` only when the bus says it is not subscribed. */
44
+ check(): Promise<HealthIndicatorResult>;
45
+ }
46
+
47
+ export { RealtimeMetrics, RealtimePubSubHealthIndicator };
@@ -0,0 +1,47 @@
1
+ import { IMetricsContributor, MetricsRegistry } from '@bymax-one/nest-core/metrics';
2
+ import { RealtimeMetricsTally, ConnectionRegistry, IRealtimePubSub } from '@bymax-one/nest-realtime/internal';
3
+ import { IHealthIndicator, HealthIndicatorResult } from '@bymax-one/nest-core/health';
4
+
5
+ /**
6
+ * Registers the realtime collectors on the registry the scrape endpoint serves.
7
+ *
8
+ * Every counter is read from the tally on each scrape, after a reset, instead of being written as events
9
+ * arrive: the tally starts counting before this class runs, and a counter fed by events would drop that window.
10
+ * Labels are the closed sets the tally is keyed by; no id, tenant, user or message ever becomes one.
11
+ *
12
+ * @example
13
+ * // providers: [RealtimeMetrics] (BymaxCoreModule discovers it and calls registerMetrics once at bootstrap)
14
+ */
15
+ declare class RealtimeMetrics implements IMetricsContributor {
16
+ private readonly tally;
17
+ private readonly connections;
18
+ constructor(tally: RealtimeMetricsTally, connections: ConnectionRegistry);
19
+ /**
20
+ * Register the collectors against the scrape registry.
21
+ *
22
+ * @param registry - The registry the scrape endpoint serves.
23
+ */
24
+ registerMetrics(registry: MetricsRegistry): void;
25
+ }
26
+
27
+ /**
28
+ * Reports whether this instance still receives what the other instances publish.
29
+ *
30
+ * It asks the bus for its own state and sends nothing, so it is as cheap as a property read and needs no
31
+ * timeout of its own. A bus that does not report its state, such as the in-memory one, counts as up: there
32
+ * is no signal to be alarmed by, and a probe that failed for want of one would take the instance out of
33
+ * rotation for nothing. The result carries no detail, because a host name or a credential must not reach a
34
+ * readiness response.
35
+ *
36
+ * @example
37
+ * // providers: [RealtimePubSubHealthIndicator] (BymaxCoreModule discovers it with `health.autoDiscover`)
38
+ */
39
+ declare class RealtimePubSubHealthIndicator implements IHealthIndicator {
40
+ private readonly pubsub;
41
+ readonly name = "realtime-pubsub";
42
+ constructor(pubsub: IRealtimePubSub);
43
+ /** The indicator's outcome: `down` only when the bus says it is not subscribed. */
44
+ check(): Promise<HealthIndicatorResult>;
45
+ }
46
+
47
+ export { RealtimeMetrics, RealtimePubSubHealthIndicator };
@@ -0,0 +1,104 @@
1
+ import { BymaxMetricsContributor } from '@bymax-one/nest-core/metrics';
2
+ import { Injectable, Inject } from '@nestjs/common';
3
+ import { Gauge, Counter } from 'prom-client';
4
+ import { RealtimeMetricsTally, ConnectionRegistry, REALTIME_PUBSUB_TOKEN, TALLY_TRANSPORTS, REFUSAL_REASONS, EVICTION_REASONS } from '@bymax-one/nest-realtime/internal';
5
+ import { BymaxHealthIndicator } from '@bymax-one/nest-core/health';
6
+
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __decorateClass = (decorators, target, key, kind) => {
9
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
10
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
11
+ if (decorator = decorators[i])
12
+ result = (decorator(result)) || result;
13
+ return result;
14
+ };
15
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
16
+ function countedBy(registry, spec) {
17
+ const { label, keys, read } = spec;
18
+ new Counter({
19
+ name: spec.name,
20
+ help: spec.help,
21
+ labelNames: [label],
22
+ registers: [registry],
23
+ collect() {
24
+ this.reset();
25
+ const counts = read();
26
+ for (const key of keys) this.inc({ [label]: key }, counts[key]);
27
+ }
28
+ });
29
+ }
30
+ var RealtimeMetrics = class {
31
+ constructor(tally, connections) {
32
+ this.tally = tally;
33
+ this.connections = connections;
34
+ }
35
+ tally;
36
+ connections;
37
+ registerMetrics(registry) {
38
+ const { tally, connections } = this;
39
+ new Gauge({
40
+ name: "bymax_realtime_connections",
41
+ help: "Connections open on this instance now, by transport.",
42
+ labelNames: ["transport"],
43
+ registers: [registry],
44
+ collect() {
45
+ for (const transport of TALLY_TRANSPORTS) {
46
+ this.set({ transport }, connections.allByTransport(transport).length);
47
+ }
48
+ }
49
+ });
50
+ countedBy(registry, {
51
+ name: "bymax_realtime_connections_refused_total",
52
+ help: "Handshakes refused since start, by reason: limit, unauthorized, unavailable or error.",
53
+ label: "reason",
54
+ keys: REFUSAL_REASONS,
55
+ read: () => tally.snapshot().refused
56
+ });
57
+ countedBy(registry, {
58
+ name: "bymax_realtime_evictions_total",
59
+ help: "Connections closed since start, by reason: per_user_cap, slow_consumer or revoked.",
60
+ label: "reason",
61
+ keys: EVICTION_REASONS,
62
+ read: () => tally.snapshot().evicted
63
+ });
64
+ countedBy(registry, {
65
+ name: "bymax_realtime_events_emitted_total",
66
+ help: "Emit calls handled on this instance since start, by transport, whether or not a connection received the event.",
67
+ label: "transport",
68
+ keys: TALLY_TRANSPORTS,
69
+ read: () => tally.snapshot().emitted
70
+ });
71
+ new Counter({
72
+ name: "bymax_realtime_slow_consumer_drops_total",
73
+ help: "Connections cut since start for not reading what they were sent.",
74
+ registers: [registry],
75
+ collect() {
76
+ this.reset();
77
+ this.inc(tally.snapshot().slowConsumerDrops);
78
+ }
79
+ });
80
+ }
81
+ };
82
+ RealtimeMetrics = __decorateClass([
83
+ BymaxMetricsContributor(),
84
+ Injectable(),
85
+ __decorateParam(0, Inject(RealtimeMetricsTally)),
86
+ __decorateParam(1, Inject(ConnectionRegistry))
87
+ ], RealtimeMetrics);
88
+ var RealtimePubSubHealthIndicator = class {
89
+ constructor(pubsub) {
90
+ this.pubsub = pubsub;
91
+ }
92
+ pubsub;
93
+ name = "realtime-pubsub";
94
+ async check() {
95
+ return { status: this.pubsub.isSubscribed?.() === false ? "down" : "up" };
96
+ }
97
+ };
98
+ RealtimePubSubHealthIndicator = __decorateClass([
99
+ BymaxHealthIndicator(),
100
+ Injectable(),
101
+ __decorateParam(0, Inject(REALTIME_PUBSUB_TOKEN))
102
+ ], RealtimePubSubHealthIndicator);
103
+
104
+ export { RealtimeMetrics, RealtimePubSubHealthIndicator };
@@ -35,13 +35,14 @@ var CONNECTION_ROOM_PREFIX = "connection";
35
35
  var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
36
36
  var _shuttingDown;
37
37
  exports.WebSocketTransport = class WebSocketTransport {
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 common.Logger(exports.WebSocketTransport.name));
47
48
  __publicField(this, "server", null);
@@ -54,6 +55,7 @@ exports.WebSocketTransport = class WebSocketTransport {
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 @@ exports.WebSocketTransport = class WebSocketTransport {
70
72
  attached(op) {
71
73
  if (!this.server && !this.warnedUnattached) {
72
74
  this.warnedUnattached = true;
73
- this.logger.warn(
74
- `${internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE} op=${op}: no WebSocket server is attached yet, so emits are dropped until the gateway initialises`
75
+ internal.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 @@ exports.WebSocketTransport = class WebSocketTransport {
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: ${internal.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
+ internal.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(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
@@ -159,20 +173,35 @@ exports.WebSocketTransport = class WebSocketTransport {
159
173
  () => this.hooks.onDisconnect?.(disconnectMeta),
160
174
  this.options.hookTimeoutMs ?? internal.DEFAULT_HOOK_TIMEOUT_MS
161
175
  );
162
- if (failed) this.logger.error(`onDisconnect hook failed: ${internal.describeError(failed.error)}`);
176
+ if (failed) {
177
+ internal.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(`${internal.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(`${internal.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
  internal.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
  internal.refuseReservedRoom("joinRoom", roomId);
@@ -222,6 +251,7 @@ exports.WebSocketTransport = class WebSocketTransport {
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, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
226
256
  await this.unregisterSocket(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
227
257
  userConnections = this.connections.byUser(userId, "websocket");
@@ -237,7 +267,9 @@ exports.WebSocketTransport = __decorateClass([
237
267
  __decorateParam(3, common.Inject(internal.REALTIME_HOOKS_TOKEN)),
238
268
  __decorateParam(4, common.Inject(internal.REALTIME_OPTIONS_TOKEN)),
239
269
  __decorateParam(5, common.Optional()),
240
- __decorateParam(5, common.Inject(internal.ConnectionAdmission))
270
+ __decorateParam(5, common.Inject(internal.ConnectionAdmission)),
271
+ __decorateParam(6, common.Optional()),
272
+ __decorateParam(6, common.Inject(internal.RealtimeMetricsTally))
241
273
  ], exports.WebSocketTransport);
242
274
 
243
275
  // src/websocket/transports/composite/composite.transport.ts
@@ -311,7 +343,14 @@ exports.CompositeTransport = class CompositeTransport {
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: ${internal.describeError(reason)}`);
346
+ internal.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 platformSocket_io.IoAda
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
+ internal.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
  exports.RealtimeGateway = class RealtimeGateway {
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 common.Logger(exports.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 @@ exports.RealtimeGateway = class RealtimeGateway {
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(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
461
527
  refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
462
528
  next(refusal);
@@ -473,12 +539,25 @@ exports.RealtimeGateway = class RealtimeGateway {
473
539
  } finally {
474
540
  if (!handedOver) ticket?.release();
475
541
  }
476
- };
542
+ }
477
543
  refusalFor(socket, err) {
478
- if (err instanceof internal.AuthenticationUnavailableError || err instanceof internal.ConnectionLimitError) {
544
+ if (err instanceof internal.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}: ${internal.describeError(err)}`);
548
+ if (err instanceof internal.AuthenticationUnavailableError) {
549
+ this.tally?.refused("unavailable");
550
+ return this.unavailable("Internal Server Error");
551
+ }
552
+ this.tally?.refused("error");
553
+ internal.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 = internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE) {
@@ -494,7 +573,10 @@ exports.RealtimeGateway = class RealtimeGateway {
494
573
  }
495
574
  reportMissingAdapter() {
496
575
  const configured = Object.keys(this.options.websocket ?? {});
497
- this.logger.error(
576
+ internal.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 @@ exports.RealtimeGateway = class RealtimeGateway {
535
617
  });
536
618
  }
537
619
  } catch (err) {
538
- if (!(err instanceof internal.AuthenticationUnavailableError || err instanceof internal.ConnectionLimitError)) {
539
- this.logger.error(
540
- `handleConnection threw for socket ${socket.id} \u2014 disconnecting: ${internal.describeError(err)}`
620
+ if (err instanceof internal.ConnectionLimitError) {
621
+ this.tally?.refused("limit");
622
+ } else if (err instanceof internal.AuthenticationUnavailableError) {
623
+ this.tally?.refused("unavailable");
624
+ } else {
625
+ this.tally?.refused("error");
626
+ internal.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 @@ exports.RealtimeGateway = class RealtimeGateway {
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 @@ exports.RealtimeGateway = class RealtimeGateway {
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 @@ exports.RealtimeGateway = __decorateClass([
602
696
  cors: { origin: false }
603
697
  }),
604
698
  __decorateParam(0, common.Inject(exports.WebSocketTransport)),
605
- __decorateParam(1, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
699
+ __decorateParam(1, common.Inject(internal.REALTIME_OPTIONS_TOKEN)),
700
+ __decorateParam(2, common.Optional()),
701
+ __decorateParam(2, common.Inject(internal.RealtimeMetricsTally)),
702
+ __decorateParam(3, common.Optional()),
703
+ __decorateParam(3, common.Inject(internal.RealtimeTracing))
606
704
  ], exports.RealtimeGateway);
607
705
 
608
706
  // src/websocket/websocket-wiring.ts
@@ -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
  *