status/lib/dashboard/socket.js

102 lines
2.2 KiB
JavaScript
Raw Normal View History

'use strict';
const { makeId } = require('core/makeid');
const decoder = new TextDecoder('utf-8');
let uws;
const mapService = (s, beat) => ({
id: s.id,
name: s.name,
cluster: s.cluster,
lastBeat: beat,
});
async function createDashboardSocket(server) {
uws = server.ws({
route: '/statusdashboard/socket',
onOpen: async ws => {
function sendTime() {
try {
ws.send(JSON.stringify({
cmd: 'time',
time: new Date().getTime(),
}));
}
catch {
return;
}
}
sendTime();
setInterval(sendTime, 5000);
async function sendStatuses() {
const services = await server.storage
.store('smartyellow/webservice')
.find()
.toArray();
const heartbeats = await server.storage
.store('smartyellow/webserviceheartbeat')
.find({ webservice: { $in: services.map(s => s.id) } })
.sort({ date: -1 })
.toArray();
const servicesUp = [];
const servicesDown = [];
const servicesUnknown = [];
console.log(heartbeats);
for (let service of services) {
const beat = heartbeats.find(b => b.webservice === service.id);
service = mapService(service, beat);
if (!beat) {
servicesUnknown.push(service);
}
else if (beat.down) {
servicesDown.push(service);
}
else {
servicesUp.push(service);
}
}
try {
ws.send(JSON.stringify({
cmd: 'data',
servicesUp,
servicesDown,
servicesUnknown,
}));
}
catch {
return;
}
}
sendStatuses();
setInterval(sendStatuses, 5000);
},
onUpgrade: async () => ({ id: makeId(10) }),
onMessage: async (ws, msg) => {
msg = JSON.parse(decoder.decode(msg));
if (!msg || !msg.command) {
return;
}
switch (msg.command) {
case 'data':
ws.send('data');
return;
default:
return;
}
},
});
}
module.exports = createDashboardSocket;