-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.ts
234 lines (196 loc) · 7.27 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import * as http from 'http';
import * as express from 'express';
import * as io from 'socket.io';
import * as prom from 'prom-client';
export function metrics(ioServer: io.Server, options?: IMetricsOptions) {
return new SocketIOMetrics(ioServer, options);
}
export interface IMetricsOptions {
port?: number | string;
path?: string;
createServer?: boolean,
collectDefaultMetrics?: boolean
checkForNewNamespaces?: boolean
}
export interface IMetrics {
connectedSockets: prom.Gauge;
connectTotal: prom.Counter;
disconnectTotal: prom.Counter;
eventsReceivedTotal: prom.Counter;
eventsSentTotal: prom.Counter;
bytesReceived: prom.Counter;
bytesTransmitted: prom.Counter;
errorsTotal: prom.Counter;
}
export class SocketIOMetrics {
public register: prom.Registry;
public metrics: IMetrics;
private ioServer: io.Server;
private express: express.Express;
private expressServer: http.Server;
private options: IMetricsOptions;
private boundNamespaces = new Set();
private defaultOptions: IMetricsOptions = {
port: 9090,
path: '/metrics',
createServer: true,
collectDefaultMetrics: false,
checkForNewNamespaces: true
};
constructor(ioServer: io.Server, options?: IMetricsOptions) {
this.options = { ...this.defaultOptions, ...options };
this.ioServer = ioServer;
this.register = prom.register;
this.initMetrics();
this.bindMetrics();
if (this.options.collectDefaultMetrics) {
prom.collectDefaultMetrics({
register: this.register
});
}
if (this.options.createServer) {
this.start();
}
}
/*
* Metrics Server
*/
public start() {
if (!this.expressServer || !this.expressServer.listening) {
this.initServer();
}
}
public async close() {
return this.expressServer.close();
}
private initServer() {
this.express = express();
this.expressServer = this.express.listen(this.options.port);
this.express.get(this.options.path, (req: express.Request, res: express.Response) => {
res.set('Content-Type', this.register.contentType);
res.end(this.register.metrics());
});
}
/*
* Metrics logic
*/
private initMetrics() {
this.metrics = {
connectedSockets: new prom.Gauge({
name: 'socket_io_connected',
help: 'Number of currently connected sockets'
}),
connectTotal: new prom.Counter({
name: 'socket_io_connect_total',
help: 'Total count of socket.io connection requests',
labelNames: ['namespace']
}),
disconnectTotal: new prom.Counter({
name: 'socket_io_disconnect_total',
help: 'Total count of socket.io disconnections',
labelNames: ['namespace']
}),
eventsReceivedTotal: new prom.Counter({
name: 'socket_io_events_received_total',
help: 'Total count of socket.io received events',
labelNames: ['event', 'namespace']
}),
eventsSentTotal: new prom.Counter({
name: 'socket_io_events_sent_total',
help: 'Total count of socket.io sent events',
labelNames: ['event', 'namespace']
}),
bytesReceived: new prom.Counter({
name: 'socket_io_receive_bytes',
help: 'Total socket.io bytes received',
labelNames: ['event', 'namespace']
}),
bytesTransmitted: new prom.Counter({
name: 'socket_io_transmit_bytes',
help: 'Total socket.io bytes transmitted',
labelNames: ['event', 'namespace']
}),
errorsTotal: new prom.Counter({
name: 'socket_io_errors_total',
help: 'Total socket.io errors',
labelNames: ['namespace']
})
};
}
private bindMetricsOnEmitter(server: NodeJS.EventEmitter, labels: prom.labelValues) {
const blacklisted_events = new Set([
'error',
'connect',
'disconnect',
'disconnecting',
'newListener',
'removeListener'
]);
server.on('connect', (socket: any) => {
// Connect events
this.metrics.connectTotal.inc(labels);
this.metrics.connectedSockets.set((this.ioServer.engine as any).clientsCount);
// Disconnect events
socket.on('disconnect', () => {
this.metrics.disconnectTotal.inc(labels);
this.metrics.connectedSockets.set((this.ioServer.engine as any).clientsCount);
});
// Hook into emit (outgoing event)
const org_emit = socket.emit;
socket.emit = (event: string, ...data: any[]) => {
if (!blacklisted_events.has(event)) {
let labelsWithEvent = { event: event, ...labels };
this.metrics.bytesTransmitted.inc(labelsWithEvent, this.dataToBytes(data));
this.metrics.eventsSentTotal.inc(labelsWithEvent);
}
return org_emit.apply(socket, [event, ...data]);
};
// Hook into onevent (incoming event)
const org_onevent = socket.onevent;
socket.onevent = (packet: any) => {
if (packet && packet.data) {
const [event, data] = packet.data;
if (event === 'error') {
this.metrics.connectedSockets.set((this.ioServer.engine as any).clientsCount);
this.metrics.errorsTotal.inc(labels);
} else if (!blacklisted_events.has(event)) {
let labelsWithEvent = { event: event, ...labels };
this.metrics.bytesReceived.inc(labelsWithEvent, this.dataToBytes(data));
this.metrics.eventsReceivedTotal.inc(labelsWithEvent);
}
}
return org_onevent.call(socket, packet);
};
});
}
private bindNamespaceMetrics(server: io.Server, namespace: string) {
if (this.boundNamespaces.has(namespace)) {
return;
}
const namespaceServer = server.of(namespace);
this.bindMetricsOnEmitter(namespaceServer, { namespace: namespace });
this.boundNamespaces.add(namespace);
}
private bindMetrics() {
Object.keys(this.ioServer.nsps).forEach((nsp) =>
this.bindNamespaceMetrics(this.ioServer, nsp)
);
if (this.options.checkForNewNamespaces) {
setInterval(() => {
Object.keys(this.ioServer.nsps).forEach((nsp) =>
this.bindNamespaceMetrics(this.ioServer, nsp)
);
}, 2000);
}
}
/*
* Helping methods
*/
private dataToBytes(data: any) {
try {
return Buffer.byteLength((typeof data === 'string') ? data : JSON.stringify(data) || '', 'utf8');
} catch (e) {
return 0;
}
}
}