Efficient websocket tiles

This commit is contained in:
Romein van Buren 2023-02-25 14:38:57 +01:00
parent 6f9e34ee6d
commit 5967941008
Signed by: romein
GPG Key ID: 0EFF8478ADDF6C49

View File

@ -326,22 +326,23 @@ module.exports = {
order: 100,
purpose: 'Start the websocket for the dashboard after boot',
handler: () => {
const timers = {};
let tiles = [];
let downIdsBefore = [];
let downIdsAfter = [];
let newOutage = false;
const mapService = (s, beat) => ({
function mapService(s, beat) {
return {
id: s.id,
name: s.name,
cluster: s.cluster,
lastBeat: beat,
checked: s.lastChecked,
});
};
}
server.ws({
route: '/status/dashboard/socket',
onOpen: async ws => {
async function sendStatuses() {
async function getTiles() {
const services = await server.storage
.store('smartyellow/webservice')
.find({ public: true })
@ -351,7 +352,7 @@ module.exports = {
.find({ webservice: { $in: services.map(s => s.id) } })
.sort({ date: -1 })
.toArray();
const tiles = [];
tiles = [];
for (let service of services) {
const beat = heartbeats.find(b => b.webservice === service.id);
@ -394,22 +395,32 @@ module.exports = {
}
downIdsBefore = [ ...downIdsAfter ];
downIdsAfter = [];
}
// Load tiles every 10 seconds.
setInterval(getTiles, 10000);
server.ws({
route: '/status/dashboard/socket',
onOpen: async ws => {
function sendTiles() {
try {
const json = JSON.stringify({ newOutage, tiles });
ws.send(json);
}
catch {
return;
}
catch { /* noop */ }
}
// Send statuses on open and every 5 seconds.
sendStatuses();
setInterval(sendStatuses, 5000);
// Send tiles on open and every 5 seconds.
sendTiles();
timers[ws.id] = setInterval(sendTiles, 5000);
},
onUpgrade: () => ({ id: makeId(10) }),
onMessage: () => { /* nevermind */ },
onClose: ws => {
clearInterval(timers[ws.id]);
delete timers[ws.id];
},
onUpgrade: async () => ({ id: makeId(10) }),
onMessage: async () => { /* do nothing */ },
});
},
},