summaryrefslogtreecommitdiff
path: root/src/server/api/stream/server-stats.ts
blob: d4fbeefa04a2d4b80e8e9675a465806f74b20564 (plain)
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
import * as websocket from 'websocket';
import Xev from 'xev';

const ev = new Xev();

export default function(request: websocket.request, connection: websocket.connection): void {
	const onStats = (stats: any) => {
		connection.send(JSON.stringify({
			type: 'stats',
			body: stats
		}));
	};

	connection.on('message', async data => {
		const msg = JSON.parse(data.utf8Data);

		switch (msg.type) {
			case 'requestLog':
				ev.once(`serverStatsLog:${msg.id}`, statsLog => {
					connection.send(JSON.stringify({
						type: 'statsLog',
						body: statsLog
					}));
				});
				ev.emit('requestServerStatsLog', {
					id: msg.id,
					length: msg.length
				});
				break;
		}
	});

	ev.addListener('serverStats', onStats);

	connection.on('close', () => {
		ev.removeListener('serverStats', onStats);
	});
}