Make the JSON endpoint quick

This commit is contained in:
Marco van Dijk 2024-12-01 13:02:31 +01:00
parent 8a994ba272
commit 24bd005f04

View File

@ -87,6 +87,8 @@ function sleep(ms) {
let ensDomainCache = {}; let ensDomainCache = {};
let orchCache = {}; let orchCache = {};
let lastStringify = 0; //< We will stringify every 15 seconds so the the JSON endpoint can respond quickly
let jsonString = "";
let lastLeaderboardCheck = 0; let lastLeaderboardCheck = 0;
let isSynced = false; let isSynced = false;
@ -446,7 +448,7 @@ masterRouter.get("/prometheus", async (req, res) => {
masterRouter.get("/json", async (req, res) => { masterRouter.get("/json", async (req, res) => {
try { try {
res.set("Content-Type", "application/json"); res.set("Content-Type", "application/json");
res.end(JSON.stringify(orchCache)); res.end(jsonString);
} catch (err) { } catch (err) {
res.status(400).send(err); res.status(400).send(err);
} }
@ -614,16 +616,40 @@ const recoverStorage = async function () {
}; };
recoverStorage(); recoverStorage();
// Strip individual measurements from the cache to keep the response tiny
function shallowCopy() {
const mrClean = {};
for (const orchestratorId in orchCache) {
const orchestrator = orchCache[orchestratorId];
// Shallow copy (which references original memory pointers)
mrClean[orchestratorId] = { ...orchestrator };
// Overwrite regionalStats ref
if (orchestrator.regionalStats) {
mrClean[orchestratorId].regionalStats = {};
for (const region in orchestrator.regionalStats) {
const regionStats = orchestrator.regionalStats[region];
// Shallow copy region stats without measurements
mrClean[orchestratorId].regionalStats[region] = { ...regionStats };
delete mrClean[orchestratorId].regionalStats[region].measurements;
}
}
}
return JSON.stringify(mrClean);
}
const runTests = async function () { const runTests = async function () {
try { try {
const now = new Date().getTime(); const now = new Date().getTime();
if ( if (!lastLeaderboardCheck || now - lastLeaderboardCheck > CONF_SCORE_TIMEOUT) {
!lastLeaderboardCheck ||
now - lastLeaderboardCheck > CONF_SCORE_TIMEOUT
) {
await updateOrchScores(); await updateOrchScores();
lastLeaderboardCheck = now; lastLeaderboardCheck = now;
} }
if (!lastStringify || now - lastStringify > 15000) {
jsonString = shallowCopy();
lastStringify = now;
}
setTimeout(() => { setTimeout(() => {
runTests(); runTests();
}, CONF_SLEEPTIME); }, CONF_SLEEPTIME);