@bymax-one/nest-realtime 1.2.18 → 1.2.20
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 +59 -1
- package/README.md +94 -10
- package/dist/internal/index.cjs +535 -104
- package/dist/internal/index.d.cts +129 -7
- package/dist/internal/index.d.ts +129 -7
- package/dist/internal/index.mjs +532 -106
- package/dist/observability/index.cjs +104 -0
- package/dist/observability/index.d.cts +47 -0
- package/dist/observability/index.d.ts +47 -0
- package/dist/observability/index.mjs +104 -0
- package/dist/websocket/index.cjs +128 -20
- package/dist/websocket/index.d.cts +14 -4
- package/dist/websocket/index.d.ts +14 -4
- package/dist/websocket/index.mjs +129 -21
- package/package.json +31 -3
|
@@ -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 };
|
package/dist/websocket/index.cjs
CHANGED
|
@@ -31,17 +31,28 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
|
|
|
31
31
|
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
|
|
32
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
33
|
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
34
|
+
|
|
35
|
+
// src/websocket/transports/websocket/connect-hook-failure.ts
|
|
36
|
+
var ConnectHookFailure = class extends Error {
|
|
37
|
+
constructor(cause) {
|
|
38
|
+
super("onConnect hook failed", { cause });
|
|
39
|
+
this.name = "ConnectHookFailure";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
// src/websocket/transports/websocket/websocket.transport.ts
|
|
34
44
|
var CONNECTION_ROOM_PREFIX = "connection";
|
|
35
45
|
var DEFAULT_MAX_CONNECTIONS_PER_USER = 5;
|
|
36
46
|
var _shuttingDown;
|
|
37
47
|
exports.WebSocketTransport = class WebSocketTransport {
|
|
38
|
-
constructor(connections, rooms, gate, hooks, options, admission) {
|
|
48
|
+
constructor(connections, rooms, gate, hooks, options, admission, tally) {
|
|
39
49
|
this.connections = connections;
|
|
40
50
|
this.rooms = rooms;
|
|
41
51
|
this.gate = gate;
|
|
42
52
|
this.hooks = hooks;
|
|
43
53
|
this.options = options;
|
|
44
54
|
this.admission = admission;
|
|
55
|
+
this.tally = tally;
|
|
45
56
|
__publicField(this, "kind", "websocket");
|
|
46
57
|
__publicField(this, "logger", new common.Logger(exports.WebSocketTransport.name));
|
|
47
58
|
__publicField(this, "server", null);
|
|
@@ -54,6 +65,7 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
54
65
|
hooks;
|
|
55
66
|
options;
|
|
56
67
|
admission;
|
|
68
|
+
tally;
|
|
57
69
|
onModuleDestroy() {
|
|
58
70
|
__privateSet(this, _shuttingDown, true);
|
|
59
71
|
}
|
|
@@ -70,8 +82,12 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
70
82
|
attached(op) {
|
|
71
83
|
if (!this.server && !this.warnedUnattached) {
|
|
72
84
|
this.warnedUnattached = true;
|
|
73
|
-
|
|
74
|
-
|
|
85
|
+
internal.logEvent(
|
|
86
|
+
this.logger,
|
|
87
|
+
"warn",
|
|
88
|
+
"REALTIME_SERVER_NOT_ATTACHED",
|
|
89
|
+
"no WebSocket server is attached yet, so emits are dropped until the gateway initialises",
|
|
90
|
+
{ op }
|
|
75
91
|
);
|
|
76
92
|
}
|
|
77
93
|
return this.server;
|
|
@@ -109,9 +125,17 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
109
125
|
await this.evictBeyondLimit(auth.userId);
|
|
110
126
|
const failed = await this.runOnConnect(socket, auth, connectedAt);
|
|
111
127
|
if (!failed) return;
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
128
|
+
if (this.options.onConnectFailure === "close") {
|
|
129
|
+
throw new ConnectHookFailure(failed.error);
|
|
130
|
+
}
|
|
131
|
+
internal.logEvent(
|
|
132
|
+
this.logger,
|
|
133
|
+
"error",
|
|
134
|
+
"REALTIME_HOOK_FAILED",
|
|
135
|
+
"onConnect hook failed",
|
|
136
|
+
{ hook: "onConnect" },
|
|
137
|
+
failed.error
|
|
138
|
+
);
|
|
115
139
|
}
|
|
116
140
|
async joinRooms(socket, auth) {
|
|
117
141
|
await socket.join(`${internal.ROOM_PREFIXES.USER}:${auth.userId}`);
|
|
@@ -159,20 +183,35 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
159
183
|
() => this.hooks.onDisconnect?.(disconnectMeta),
|
|
160
184
|
this.options.hookTimeoutMs ?? internal.DEFAULT_HOOK_TIMEOUT_MS
|
|
161
185
|
);
|
|
162
|
-
if (failed)
|
|
186
|
+
if (failed) {
|
|
187
|
+
internal.logEvent(
|
|
188
|
+
this.logger,
|
|
189
|
+
"error",
|
|
190
|
+
"REALTIME_HOOK_FAILED",
|
|
191
|
+
`onDisconnect hook failed`,
|
|
192
|
+
{
|
|
193
|
+
hook: "onDisconnect"
|
|
194
|
+
},
|
|
195
|
+
failed.error
|
|
196
|
+
);
|
|
197
|
+
}
|
|
163
198
|
}
|
|
164
199
|
async emitToUser(userId, event, data) {
|
|
165
200
|
this.attached("emitToUser")?.to(`${internal.ROOM_PREFIXES.USER}:${userId}`).emit(event, data);
|
|
201
|
+
if (this.server) this.tally?.emitted("websocket");
|
|
166
202
|
}
|
|
167
203
|
async emitToTenant(tenantId, event, data) {
|
|
168
204
|
this.attached("emitToTenant")?.to(`${internal.ROOM_PREFIXES.TENANT}:${tenantId}`).emit(event, data);
|
|
205
|
+
if (this.server) this.tally?.emitted("websocket");
|
|
169
206
|
}
|
|
170
207
|
async emitToRoom(roomId, event, data) {
|
|
171
208
|
internal.requireRoomName("emitToRoom", roomId);
|
|
172
209
|
this.attached("emitToRoom")?.to(roomId).emit(event, data);
|
|
210
|
+
if (this.server) this.tally?.emitted("websocket");
|
|
173
211
|
}
|
|
174
212
|
async broadcast(event, data) {
|
|
175
213
|
this.attached("broadcast")?.emit(event, data);
|
|
214
|
+
if (this.server) this.tally?.emitted("websocket");
|
|
176
215
|
}
|
|
177
216
|
async joinRoom(connectionId, roomId) {
|
|
178
217
|
internal.refuseReservedRoom("joinRoom", roomId);
|
|
@@ -196,7 +235,7 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
196
235
|
throw internal.unavailableError(
|
|
197
236
|
internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE,
|
|
198
237
|
exports.WebSocketTransport.name,
|
|
199
|
-
`the WebSocket server is not attached, so ${connectionId} cannot be revoked`,
|
|
238
|
+
`the WebSocket server is not attached, so ${connectionId} cannot be revoked (server not attached)`,
|
|
200
239
|
new Error("server not attached")
|
|
201
240
|
);
|
|
202
241
|
}
|
|
@@ -222,6 +261,7 @@ exports.WebSocketTransport = class WebSocketTransport {
|
|
|
222
261
|
let userConnections = this.connections.byUser(userId, "websocket");
|
|
223
262
|
while (userConnections.length > max) {
|
|
224
263
|
const oldest = userConnections.reduce((a, b) => a.connectedAt <= b.connectedAt ? a : b);
|
|
264
|
+
this.tally?.evicted("per_user_cap");
|
|
225
265
|
await this.disconnect(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
226
266
|
await this.unregisterSocket(oldest.connectionId, internal.REALTIME_ERROR_CODES.TOO_MANY_CONNECTIONS);
|
|
227
267
|
userConnections = this.connections.byUser(userId, "websocket");
|
|
@@ -237,7 +277,9 @@ exports.WebSocketTransport = __decorateClass([
|
|
|
237
277
|
__decorateParam(3, common.Inject(internal.REALTIME_HOOKS_TOKEN)),
|
|
238
278
|
__decorateParam(4, common.Inject(internal.REALTIME_OPTIONS_TOKEN)),
|
|
239
279
|
__decorateParam(5, common.Optional()),
|
|
240
|
-
__decorateParam(5, common.Inject(internal.ConnectionAdmission))
|
|
280
|
+
__decorateParam(5, common.Inject(internal.ConnectionAdmission)),
|
|
281
|
+
__decorateParam(6, common.Optional()),
|
|
282
|
+
__decorateParam(6, common.Inject(internal.RealtimeMetricsTally))
|
|
241
283
|
], exports.WebSocketTransport);
|
|
242
284
|
|
|
243
285
|
// src/websocket/transports/composite/composite.transport.ts
|
|
@@ -311,7 +353,14 @@ exports.CompositeTransport = class CompositeTransport {
|
|
|
311
353
|
const reasons = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
312
354
|
if (reasons.length === tasks.length) throw this.allFailed(op, reasons);
|
|
313
355
|
for (const reason of reasons) {
|
|
314
|
-
|
|
356
|
+
internal.logEvent(
|
|
357
|
+
this.logger,
|
|
358
|
+
"warn",
|
|
359
|
+
"REALTIME_COMPOSITE_PARTIAL_FAILURE",
|
|
360
|
+
`Composite ${op} partially failed`,
|
|
361
|
+
{ op },
|
|
362
|
+
reason
|
|
363
|
+
);
|
|
315
364
|
}
|
|
316
365
|
}
|
|
317
366
|
allFailed(what, reasons) {
|
|
@@ -390,7 +439,12 @@ var RealtimeIoAdapter = class _RealtimeIoAdapter extends platformSocket_io.IoAda
|
|
|
390
439
|
if (reported) return;
|
|
391
440
|
reported = true;
|
|
392
441
|
const kind = Object(err).constructor?.name ?? "Error";
|
|
393
|
-
|
|
442
|
+
internal.logEvent(
|
|
443
|
+
this.adapterLogger,
|
|
444
|
+
"warn",
|
|
445
|
+
"REALTIME_ADAPTER_COMMAND_FAILED",
|
|
446
|
+
`Redis adapter subscriber command failed (${kind})`
|
|
447
|
+
);
|
|
394
448
|
});
|
|
395
449
|
return pending;
|
|
396
450
|
};
|
|
@@ -431,21 +485,41 @@ function firstQueryValue(value) {
|
|
|
431
485
|
return Array.isArray(value) ? value[0] : value;
|
|
432
486
|
}
|
|
433
487
|
exports.RealtimeGateway = class RealtimeGateway {
|
|
434
|
-
constructor(transport, options) {
|
|
488
|
+
constructor(transport, options, tally, tracing) {
|
|
435
489
|
this.transport = transport;
|
|
436
490
|
this.options = options;
|
|
491
|
+
this.tally = tally;
|
|
492
|
+
this.tracing = tracing;
|
|
437
493
|
}
|
|
438
494
|
transport;
|
|
439
495
|
options;
|
|
496
|
+
tally;
|
|
497
|
+
tracing;
|
|
440
498
|
logger = new common.Logger(exports.RealtimeGateway.name);
|
|
441
499
|
server;
|
|
442
500
|
authenticated = /* @__PURE__ */ new WeakMap();
|
|
443
501
|
tickets = /* @__PURE__ */ new WeakMap();
|
|
444
502
|
authenticateHandshake = async (socket, next) => {
|
|
503
|
+
let outcome;
|
|
504
|
+
const run = async () => {
|
|
505
|
+
await this.handshake(socket, (err) => {
|
|
506
|
+
outcome = err;
|
|
507
|
+
});
|
|
508
|
+
if (outcome) throw outcome;
|
|
509
|
+
};
|
|
510
|
+
try {
|
|
511
|
+
await (this.tracing ? this.tracing.span("realtime.handshake", { "bymax.realtime.transport": "websocket" }, run) : run());
|
|
512
|
+
} catch {
|
|
513
|
+
}
|
|
514
|
+
if (outcome) next(outcome);
|
|
515
|
+
else next();
|
|
516
|
+
};
|
|
517
|
+
async handshake(socket, next) {
|
|
445
518
|
let ticket;
|
|
446
519
|
let handedOver = false;
|
|
447
520
|
try {
|
|
448
521
|
if (this.transport.shuttingDown) {
|
|
522
|
+
this.tally?.refused("unavailable");
|
|
449
523
|
next(this.unavailable());
|
|
450
524
|
return;
|
|
451
525
|
}
|
|
@@ -453,10 +527,12 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
453
527
|
ticket = held;
|
|
454
528
|
const auth = await this.transport.authenticate(this.buildAuthContext(socket));
|
|
455
529
|
if (this.transport.shuttingDown) {
|
|
530
|
+
this.tally?.refused("unavailable");
|
|
456
531
|
next(this.unavailable());
|
|
457
532
|
return;
|
|
458
533
|
}
|
|
459
534
|
if (!auth) {
|
|
535
|
+
this.tally?.refused("unauthorized");
|
|
460
536
|
const refusal = new Error(internal.REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
461
537
|
refusal.data = { code: internal.REALTIME_ERROR_CODES.AUTH_FAILED };
|
|
462
538
|
next(refusal);
|
|
@@ -473,12 +549,25 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
473
549
|
} finally {
|
|
474
550
|
if (!handedOver) ticket?.release();
|
|
475
551
|
}
|
|
476
|
-
}
|
|
552
|
+
}
|
|
477
553
|
refusalFor(socket, err) {
|
|
478
|
-
if (err instanceof internal.
|
|
554
|
+
if (err instanceof internal.ConnectionLimitError) {
|
|
555
|
+
this.tally?.refused("limit");
|
|
556
|
+
return this.unavailable("Internal Server Error");
|
|
557
|
+
}
|
|
558
|
+
if (err instanceof internal.AuthenticationUnavailableError) {
|
|
559
|
+
this.tally?.refused("unavailable");
|
|
479
560
|
return this.unavailable("Internal Server Error");
|
|
480
561
|
}
|
|
481
|
-
this.
|
|
562
|
+
this.tally?.refused("error");
|
|
563
|
+
internal.logEvent(
|
|
564
|
+
this.logger,
|
|
565
|
+
"error",
|
|
566
|
+
"REALTIME_HANDSHAKE_FAILED",
|
|
567
|
+
`handshake refused`,
|
|
568
|
+
{ socketId: socket.id },
|
|
569
|
+
err
|
|
570
|
+
);
|
|
482
571
|
return new Error("Internal Server Error");
|
|
483
572
|
}
|
|
484
573
|
unavailable(message = internal.REALTIME_ERROR_CODES.TRANSPORT_UNAVAILABLE) {
|
|
@@ -494,7 +583,10 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
494
583
|
}
|
|
495
584
|
reportMissingAdapter() {
|
|
496
585
|
const configured = Object.keys(this.options.websocket ?? {});
|
|
497
|
-
|
|
586
|
+
internal.logEvent(
|
|
587
|
+
this.logger,
|
|
588
|
+
"error",
|
|
589
|
+
"REALTIME_ADAPTER_MISSING",
|
|
498
590
|
"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
591
|
);
|
|
500
592
|
}
|
|
@@ -535,9 +627,19 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
535
627
|
});
|
|
536
628
|
}
|
|
537
629
|
} catch (err) {
|
|
538
|
-
if (
|
|
539
|
-
this.
|
|
540
|
-
|
|
630
|
+
if (err instanceof internal.ConnectionLimitError) {
|
|
631
|
+
this.tally?.refused("limit");
|
|
632
|
+
} else if (err instanceof internal.AuthenticationUnavailableError) {
|
|
633
|
+
this.tally?.refused("unavailable");
|
|
634
|
+
} else {
|
|
635
|
+
if (!(err instanceof ConnectHookFailure)) this.tally?.refused("error");
|
|
636
|
+
internal.logEvent(
|
|
637
|
+
this.logger,
|
|
638
|
+
"error",
|
|
639
|
+
"REALTIME_HANDSHAKE_FAILED",
|
|
640
|
+
`handleConnection threw \u2014 disconnecting`,
|
|
641
|
+
{ socketId: socket.id },
|
|
642
|
+
err
|
|
541
643
|
);
|
|
542
644
|
}
|
|
543
645
|
socket.disconnect(true);
|
|
@@ -564,6 +666,7 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
564
666
|
this.tickets.delete(socket);
|
|
565
667
|
if (auth) return { auth, ticket };
|
|
566
668
|
if (this.transport.shuttingDown) {
|
|
669
|
+
this.tally?.refused("unavailable");
|
|
567
670
|
socket.disconnect(true);
|
|
568
671
|
return void 0;
|
|
569
672
|
}
|
|
@@ -571,6 +674,7 @@ exports.RealtimeGateway = class RealtimeGateway {
|
|
|
571
674
|
try {
|
|
572
675
|
const fresh = await this.transport.authenticate(this.buildAuthContext(socket));
|
|
573
676
|
if (!fresh) {
|
|
677
|
+
this.tally?.refused("unauthorized");
|
|
574
678
|
socket.disconnect(true);
|
|
575
679
|
held.release();
|
|
576
680
|
return void 0;
|
|
@@ -602,7 +706,11 @@ exports.RealtimeGateway = __decorateClass([
|
|
|
602
706
|
cors: { origin: false }
|
|
603
707
|
}),
|
|
604
708
|
__decorateParam(0, common.Inject(exports.WebSocketTransport)),
|
|
605
|
-
__decorateParam(1, common.Inject(internal.REALTIME_OPTIONS_TOKEN))
|
|
709
|
+
__decorateParam(1, common.Inject(internal.REALTIME_OPTIONS_TOKEN)),
|
|
710
|
+
__decorateParam(2, common.Optional()),
|
|
711
|
+
__decorateParam(2, common.Inject(internal.RealtimeMetricsTally)),
|
|
712
|
+
__decorateParam(3, common.Optional()),
|
|
713
|
+
__decorateParam(3, common.Inject(internal.RealtimeTracing))
|
|
606
714
|
], exports.RealtimeGateway);
|
|
607
715
|
|
|
608
716
|
// 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
|
-
/**
|
|
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
|
*
|