diff --git a/apps/web/src/views/home.ejs b/apps/web/src/views/home.ejs index 92e166b..61ec28c 100644 --- a/apps/web/src/views/home.ejs +++ b/apps/web/src/views/home.ejs @@ -30,21 +30,20 @@ <% it.monitors.forEach(function(m) { const latencies = (m.pings || []).filter(p => p.latency_ms != null); // Pick the region with the lowest avg latency (same logic as sparklineFromPings) - // Only consider the 3 most recent pings per region to pick best region - const byRegion = {}; - for (const p of latencies) { + // Pick best region from the 3 most recent pings overall (not per region) + const recentPings = latencies.slice(-3); + const recentRegions = {}; + for (const p of recentPings) { const key = p.region || '__none__'; - if (!byRegion[key]) byRegion[key] = []; - byRegion[key].push(p.latency_ms); + if (!recentRegions[key]) recentRegions[key] = []; + recentRegions[key].push(p.latency_ms); } let bestRegion = '__none__', bestAvg = Infinity; - for (const [region, vals] of Object.entries(byRegion)) { - const recent = vals.slice(-3); - const avg = recent.reduce((a, b) => a + b, 0) / recent.length; + for (const [region, vals] of Object.entries(recentRegions)) { + const avg = vals.reduce((a, b) => a + b, 0) / vals.length; if (avg < bestAvg) { bestAvg = avg; bestRegion = region; } } - const bestVals = byRegion[bestRegion] || []; - const avgLatency = bestVals.length ? bestVals[bestVals.length - 1] : null; + const avgLatency = latencies.length ? latencies[latencies.length - 1].latency_ms : null; %>
@@ -114,15 +113,24 @@ function getBestRegion(monitorId) { const regions = sparkData[monitorId] || {}; - let bestRegion = '__none__', bestAvg = Infinity; + // Collect all pings with timestamps to find the 3 most recent overall + const all = []; for (const [region, vals] of Object.entries(regions)) { - if (!vals.length) continue; - const recent = vals.slice(-3); - const avg = recent.reduce((a, b) => a + b, 0) / recent.length; + for (let i = 0; i < vals.length; i++) all.push({ region, val: vals[i], idx: i }); + } + // Use the last 3 entries (vals are appended in order) + const recent = all.slice(-3); + let bestRegion = '__none__', bestAvg = Infinity; + const byRegion = {}; + for (const p of recent) { + if (!byRegion[p.region]) byRegion[p.region] = []; + byRegion[p.region].push(p.val); + } + for (const [region, vals] of Object.entries(byRegion)) { + const avg = vals.reduce((a, b) => a + b, 0) / vals.length; if (avg < bestAvg) { bestAvg = avg; bestRegion = region; } } - const vals = (regions[bestRegion] || []); - const latest = vals.length ? vals[vals.length - 1] : null; + const latest = all.length ? all[all.length - 1].val : null; return { region: bestRegion, latest }; }