Files
EasyDNS-Web/internal/server/web/static/charts.js
T
Mateusz Gruszczyński de13d851a8
Go quality gates / test (push) Waiting to run
v0.1.1
2026-11-30 14:44:28 +01:00

142 lines
7.3 KiB
JavaScript

/* EasyDNS telemetry charts. Source: authenticated Go panel samples of the
* existing EasyDNS GET /api/v1/stats endpoint. There is no synthetic history.
* Fleet aggregate QPS is server-aligned and requires complete coverage. */
(() => {
'use strict';
const COLORS = {cyan:'#72cfe1', amber:'#f1b42b', red:'#ec8588',grid:'#303a34',muted:'#8d9d91',text:'#dce6df'};
const NODE_COLORS = ['#72cfe1','#f1b42b','#a5d996','#ba9be6','#e98b87','#85a8ff','#e0bf9a','#75d3ad','#d9a6ce','#d1cc83','#b4d5e9','#b48c7e','#a5bb7f','#cc92a1','#8fb5b3','#c6bbd5'];
const chartTypes = {
queries:{series:[['queryRate','Queries / s','cyan']],unit:'/s'},
cache:{series:[['cacheHitRate','Cache hit %','cyan']],unit:'%',range:[0,100]},
latency:{series:[['p50ms','p50','cyan'],['p95ms','p95','amber'],['p99ms','p99','red']],unit:'ms'},
blocked:{series:[['blocked','Blocked / s','amber']],unit:'/s'},
responses:{series:[['noerror','NOERROR','cyan'],['nxdomain','NXDOMAIN','amber'],['servfail','SERVFAIL','red']],unit:'/s'},
nxdomain:{series:[['nxdomain','NXDOMAIN','amber']],unit:'/s'}
};
const root = document.querySelector('[data-metrics-mode]');
const mode = root?.dataset.metricsMode || 'single';
let telemetry = {samples:[], nodes:[]};
const canvases = [...document.querySelectorAll('canvas[data-dns-chart]')];
if (!canvases.length) return;
function asPoints(samples, key) {
return (Array.isArray(samples) ? samples : []).map(s => {
const time = Date.parse(s.time);
const value = s[key];
return {time, value: typeof value === 'number' && Number.isFinite(value) ? value : null};
}).filter(p => Number.isFinite(p.time));
}
function seriesFor(typeName) {
const kind = chartTypes[typeName];
if (!kind) return [];
const nodes = Array.isArray(telemetry.nodes) ? telemetry.nodes : [];
if (mode === 'split' || (mode === 'aggregate' && typeName === 'latency')) {
const key = mode === 'split'
? ({queries:'queryRate',responses:'noerror',cache:'cacheHitRate',latency:'p95ms',blocked:'blocked',nxdomain:'nxdomain'}[typeName])
: 'p95ms';
return nodes.map((n,i) => ({label: String(n.name || n.id || 'Server'), color: NODE_COLORS[i % NODE_COLORS.length], points: asPoints(n.samples, key)}));
}
return kind.series.map(([key,label,color]) => ({label, color:COLORS[color], points:asPoints(telemetry.samples, key)}));
}
function render(canvas) {
const type = chartTypes[canvas.dataset.dnsChart]; if (!type) return;
const rect = canvas.getBoundingClientRect();
if (rect.width < 30 || rect.height < 30) return;
const width = rect.width, height = rect.height, dpr = Math.min(2, window.devicePixelRatio || 1);
canvas.width = Math.round(width * dpr); canvas.height = Math.round(height * dpr);
const ctx = canvas.getContext('2d'); if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const pad = {left:48,right:12,top:10,bottom:25};
const plotW = Math.max(5,width-pad.left-pad.right), plotH = Math.max(5,height-pad.top-pad.bottom);
const series = seriesFor(canvas.dataset.dnsChart);
const observed = series.flatMap(s => s.points.filter(p => p.value !== null));
ctx.font = '10px ui-monospace,Consolas,monospace'; ctx.textBaseline = 'middle';
if (observed.length === 0) {
ctx.fillStyle=COLORS.muted; ctx.textAlign='center';
ctx.fillText('Collecting live samples…',width/2,height/2-4);
ctx.fillText(mode === 'aggregate' ? 'All nodes must report fresh readings' : 'First rate after 2 successful polls',width/2,height/2+14);
return;
}
const times = series.flatMap(s => s.points.map(p=>p.time));
const start = Math.min(...times), end = Math.max(...times);
const timeSpan = Math.max(1000,end-start);
const x = t => pad.left + plotW * (t-start)/timeSpan;
const min = type.range ? type.range[0] : 0;
let max = type.range ? type.range[1] : Math.max(0.001,...observed.map(p=>p.value)) * 1.16;
if (!Number.isFinite(max) || max <= min) max = min+1;
const y = val => pad.top + plotH * (1 - (val-min)/(max-min));
ctx.textAlign = 'right'; ctx.lineWidth = 1;
for (let tick=0;tick<=4;tick++) {
const v=min+(max-min)*tick/4, py=y(v);
ctx.strokeStyle=COLORS.grid;ctx.setLineDash([2,4]);ctx.beginPath();ctx.moveTo(pad.left,py);ctx.lineTo(width-pad.right,py);ctx.stroke();
ctx.fillStyle=COLORS.muted;
ctx.fillText((max <= 10 ? v.toFixed(1) : Math.round(v).toString()) + type.unit,pad.left-8,py);
}
ctx.setLineDash([]);ctx.textAlign='center';ctx.fillStyle=COLORS.muted;
[0,.25,.5,.75,1].forEach(f=>{
const t=new Date(start+f*timeSpan);
ctx.fillText(t.toLocaleTimeString(undefined,{hour:'2-digit',minute:'2-digit'}),x(start+f*timeSpan),height-9);
});
series.forEach(s => {
ctx.beginPath(); ctx.strokeStyle=s.color; ctx.lineWidth=1.7; ctx.lineJoin='round';
let previous=null;
s.points.forEach(p => {
if (p.value===null) {previous=null;return;}
const px=x(p.time), py=y(p.value);
// A server outage may leave a long period without any samples. Do not
// draw a fabricated continuous line across a missing-data interval.
if (!previous || p.time-previous.time>30000) ctx.moveTo(px,py);
else ctx.lineTo(px,py);
previous=p;
});
ctx.stroke();
// A single measured rate is drawn as a point, never extended into a
// synthetic line or repeated as historical data.
const valid = s.points.filter(p=>p.value!==null);
if (valid.length === 1) {
ctx.beginPath();ctx.fillStyle=s.color;
ctx.arc(x(valid[0].time),y(valid[0].value),2.5,0,Math.PI*2);ctx.fill();
}
});
}
function updateLegends() {
if (mode === 'single') return; // Preserve original static per-metric legends.
document.querySelectorAll('[data-chart-legend]').forEach(el => {
const chartType=el.dataset.chartLegend;
const series=seriesFor(chartType);
el.replaceChildren();
series.forEach(s => {
const marker=document.createElement('span');
marker.className='legend-dot';marker.style.background=s.color;
const label=document.createElement('span');label.textContent=s.label;
el.append(marker,label);
});
if (mode==='aggregate' && chartType!=='latency') {
const scope=document.createElement('span');scope.className='subtle';
scope.textContent='Complete fleet samples only'; el.append(scope);
}
});
}
async function poll() {
try {
const path='/ui/telemetry?mode='+encodeURIComponent(mode);
const r=await fetch(path,{credentials:'same-origin',cache:'no-store',headers:{Accept:'application/json'}});
if(!r.ok || !(r.headers.get('content-type')||'').includes('json'))return;
const payload=await r.json();
if (mode !== 'single' && payload.mode !== mode) return;
telemetry={samples:Array.isArray(payload.samples)?payload.samples:[],nodes:Array.isArray(payload.nodes)?payload.nodes:[]};
updateLegends();canvases.forEach(render);
} catch (_) { // Keep last genuine readings; do not fill gaps with zeroes.
}
}
document.addEventListener('DOMContentLoaded',()=>{
const observer=new ResizeObserver(()=>canvases.forEach(render));
canvases.forEach(c=>observer.observe(c));
poll();setInterval(poll,15000);
});
})();