Something went wrong. Try again.
Metric and Time-Series Engine: A Minimal Archiving Time Series Storage Service
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>mats - Time-Series Engine</title> <style> * { box-sizing: border-box; } body { margin: 0; font-family: Arial, sans-serif; background-color: #fff; line-height: 1.3; text-align: center; color: #000; } pre, code { font-family: Menlo, monospace; font-size: 0.875rem; } a { color: #000; text-decoration: underline; } a:hover { text-decoration: none; background-color: #000; color: #fff; } .topbar { background: #e0e0e0; border-bottom: 2px solid #000; color: #000; } .topbar > .container { display: flex; justify-content: space-between; align-items: center; padding: 1rem 1.25rem; max-width: 75rem; margin-left: auto; margin-right: auto; } .topbar h1 { margin: 0; font-size: 1.25rem; font-weight: bold; color: #000; } .topbar h1 span { font-weight: normal; font-size: 1rem; color: #444; margin-left: 8px; } .badge { font-family: Menlo, monospace; font-size: 0.8125rem; background: #fff; color: #000; border: 1px solid #000; border-radius: 4px; padding: 4px 10px; } .page { width: 100%; } .page > .container { margin-left: auto; margin-right: auto; padding: 0 1.25rem; max-width: 75rem; text-align: left; } .controls { background: #f2f2f2; border: 1px solid #000; border-radius: 4px; padding: 12px; margin: 1.25rem 0; display: flex; gap: 10px; flex-wrap: wrap; align-items: center; } .controls label { font-weight: bold; font-size: 0.875rem; } input, select { background: #fff; color: #000; border: 1px solid #000; border-radius: 4px; padding: 6px 10px; font-family: Menlo, monospace; font-size: 0.875rem; } input:focus, select:focus { outline: 2px solid #000; } button { background: #000; color: #fff; border: 1px solid #000; border-radius: 4px; padding: 6px 16px; font-family: Arial, sans-serif; font-size: 0.875rem; font-weight: bold; cursor: pointer; transition: background 0.1s, color 0.1s; } button:hover:not(:disabled) { background: #fff; color: #000; } button:disabled { background: #777; border-color: #777; color: #eee; cursor: not-allowed; } .query-status { display: none; align-items: center; gap: 6px; font-family: Menlo, monospace; font-size: 0.8125rem; color: #444; margin-left: 6px; } @keyframes spin { to { transform: rotate(360deg); } } .spinner { display: inline-block; width: 14px; height: 14px; border: 2px solid #ccc; border-top-color: #000; border-radius: 50%; animation: spin 0.8s linear infinite; vertical-align: middle; } .spinner-btn { display: inline-block; width: 12px; height: 12px; border: 2px solid rgba(255, 255, 255, 0.4); border-top-color: #fff; border-radius: 50%; animation: spin 0.8s linear infinite; vertical-align: middle; margin-right: 6px; } .spinner-large { display: inline-block; width: 32px; height: 32px; border: 3px solid #ccc; border-top-color: #000; border-radius: 50%; animation: spin 0.8s linear infinite; } .charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(480px, 1fr)); gap: 16px; } .card { background: #fff; border: 1px solid #000; border-radius: 4px; padding: 14px; box-shadow: 3px 3px 0px #000; } .card-title { font-family: Arial, sans-serif; font-size: 0.9375rem; font-weight: bold; margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #000; display: flex; justify-content: space-between; align-items: baseline; } .card-title small { font-family: Menlo, monospace; font-weight: normal; font-size: 0.8125rem; color: #555; margin-left: 6px; } .chart-container { width: 100%; height: 220px; position: relative; background: #fafafa; border: 1px dashed #d1d5db; border-radius: 2px; display: flex; align-items: center; justify-content: center; overflow: hidden; } .chart-container.loaded { background: #fff; border: 1px solid transparent; cursor: crosshair; } .chart-container svg { width: 100%; height: 100%; position: absolute; top: 0; left: 0; display: block; } .chart-container img { width: 100%; height: 100%; object-fit: contain; opacity: 0; transition: opacity 0.2s ease-in-out; position: absolute; top: 0; left: 0; } .chart-container img.loaded { opacity: 1; } .chart-placeholder { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; color: #666; font-family: Menlo, monospace; font-size: 0.8125rem; } .chart-crosshair { position: absolute; width: 1px; background: #000; pointer-events: none; display: none; z-index: 10; } .chart-dot { position: absolute; width: 8px; height: 8px; background: #000; border: 2px solid #fff; border-radius: 50%; transform: translate(-50%, -50%); pointer-events: none; display: none; z-index: 11; box-shadow: 0 0 0 1px #000; } .chart-tooltip { position: absolute; background: #fff; color: #000; border: 1px solid #000; box-shadow: 2px 2px 0px #000; border-radius: 3px; padding: 6px 10px; font-family: Menlo, monospace; font-size: 0.75rem; line-height: 1.35; pointer-events: none; display: none; z-index: 12; white-space: nowrap; } .links a { color: #000; text-decoration: underline; font-family: Menlo, monospace; font-size: 0.8125rem; margin-left: 8px; padding: 2px 4px; } .links a:hover { background-color: #000; color: #fff; text-decoration: none; } .footer { text-align: center; color: #333; font-size: 0.875rem; margin: 2.5rem 0; } .custom-time-range { display: none; align-items: center; gap: 8px; } .custom-time-range.active { display: inline-flex; } </style></head><body> <div class="topbar"> <div class="container"> <div class="top-heading"> <h1>mats <span>Telemetry Engine</span></h1> </div> <div id="stats" class="badge">Loading stats...</div> </div> </div>
<div class="page"> <div class="container"> <div class="controls"> <label for="hostFilter">Host:</label> <input type="text" id="hostFilter" placeholder="Host regex (e.g. .*)" value=".*"> <label for="serviceFilter">Service:</label> <input type="text" id="serviceFilter" placeholder="Service regex (e.g. .*)" value=".*"> <label for="timeRange">Range:</label> <select id="timeRange" onchange="handleTimeRangeChange()"> <option value="900000">Last 15 minutes</option> <option value="3600000" selected>Last 1 hour</option> <option value="21600000">Last 6 hours</option> <option value="86400000">Last 24 hours</option> <option value="604800000">Last 7 days</option> <option value="2592000000">Last 30 days</option> <option value="7776000000">Last 90 days</option> <option value="15552000000">Last 6 months</option> <option value="31536000000">Last 1 year</option> <option value="custom">Custom...</option> </select> <div id="customTimeRange" class="custom-time-range"> <label for="customFrom">From:</label> <input type="datetime-local" id="customFrom"> <label for="customTo">To:</label> <input type="datetime-local" id="customTo"> </div> <button id="queryBtn" onclick="refreshData()">Query</button> <span id="queryStatus" class="query-status"></span> </div>
<div id="charts" class="charts-grid"></div> </div> </div>
<div class="footer"> <a href="https://go.iscode.ca/mats/">mats</a> — metrics and time-series engine </div>
<script> async function fetchStats() { try { const res = await fetch('/api/v1/stats'); const data = await res.json(); let cacheStr = ''; if (data.cache_hits !== undefined) { cacheStr = ` | Cache Hits: ${data.cache_hits} (${data.cache_items || 0} items)`; } document.getElementById('stats').innerText = `Ingested: ${data.ingested} | Dropped Late: ${data.dropped_late} | Dropped Non-Num: ${data.dropped_non_numeric}${cacheStr}`; } catch (e) { document.getElementById('stats').innerText = 'Online'; } }
function formatDateTimeLocal(d) { const pad = (n) => String(n).padStart(2, '0'); const year = d.getFullYear(); const month = pad(d.getMonth() + 1); const day = pad(d.getDate()); const hours = pad(d.getHours()); const minutes = pad(d.getMinutes()); return `${year}-${month}-${day}T${hours}:${minutes}`; }
function getTimeRangeModulus(windowMs) { if (windowMs >= 30 * 86400 * 1000) { return 86400 * 1000; // 1 day for >= 30 days (30d, 90d, 6mo, 1y) } else if (windowMs >= 7 * 86400 * 1000) { return 3600 * 1000; // 1 hour for 7 days } else if (windowMs >= 24 * 3600 * 1000) { return 15 * 60 * 1000; // 15 minutes for 24 hours } else if (windowMs >= 6 * 3600 * 1000) { return 5 * 60 * 1000; // 5 minutes for 6 hours } else { return 60 * 1000; // 1 minute for <= 1 hour } }
function handleTimeRangeChange() { const timeRange = document.getElementById('timeRange'); const customDiv = document.getElementById('customTimeRange'); if (timeRange.value === 'custom') { customDiv.classList.add('active'); const now = new Date(); const customTo = document.getElementById('customTo'); const customFrom = document.getElementById('customFrom'); if (!customTo.value) { customTo.value = formatDateTimeLocal(now); } if (!customFrom.value) { const past = new Date(now.getTime() - 24 * 3600 * 1000); customFrom.value = formatDateTimeLocal(past); } } else { customDiv.classList.remove('active'); } }
function resetQueryBtn() { const queryBtn = document.getElementById('queryBtn'); const queryStatus = document.getElementById('queryStatus'); if (queryBtn) { queryBtn.disabled = false; queryBtn.innerText = 'Query'; } if (queryStatus) { queryStatus.style.display = 'none'; queryStatus.innerHTML = ''; } }
async function refreshData() { const queryBtn = document.getElementById('queryBtn'); const queryStatus = document.getElementById('queryStatus'); const container = document.getElementById('charts');
if (queryBtn) { queryBtn.disabled = true; queryBtn.innerHTML = '<span class="spinner-btn"></span>Loading...'; } if (queryStatus) { queryStatus.innerHTML = '<span class="spinner"></span> Querying telemetry...'; queryStatus.style.display = 'inline-flex'; }
fetchStats(); const host = document.getElementById('hostFilter').value; const service = document.getElementById('serviceFilter').value; const rangeVal = document.getElementById('timeRange').value; let from, to;
if (rangeVal === 'custom') { const fromVal = document.getElementById('customFrom').value; const toVal = document.getElementById('customTo').value; if (!fromVal) { alert('Please specify a "From" date and time.'); resetQueryBtn(); return; } const fromDate = new Date(fromVal); if (isNaN(fromDate.getTime())) { alert('Invalid "From" date and time.'); resetQueryBtn(); return; } from = fromDate.getTime();
if (toVal) { const toDate = new Date(toVal); if (isNaN(toDate.getTime())) { alert('Invalid "To" date and time.'); resetQueryBtn(); return; } to = toDate.getTime(); } else { to = Date.now(); }
if (from >= to) { alert('"From" time must be earlier than "To" time.'); resetQueryBtn(); return; } } else { const windowMs = parseInt(rangeVal, 10); const modulus = getTimeRangeModulus(windowMs); to = Math.floor(Date.now() / modulus) * modulus; from = to - windowMs; }
container.innerHTML = ` <div class="card" style="grid-column: 1/-1; text-align: center; color: #333; font-family: Menlo, monospace; padding: 3rem 1.5rem; background: #fafafa;"> <div class="spinner-large" style="margin-bottom: 16px;"></div> <div style="font-size: 0.9375rem; font-weight: bold; color: #000;">Loading telemetry and resolving series...</div> <div style="font-size: 0.8125rem; color: #666; margin-top: 8px;"> Range: ${new Date(from).toLocaleString()} — ${new Date(to).toLocaleString()} </div> </div> `;
const url = `/api/v1/query?host=${encodeURIComponent(host)}&service=${encodeURIComponent(service)}&from=${from}&to=${to}&skip_empty=1`; updateURLParams(host, service, rangeVal, from, to);
try { const res = await fetch(url); if (!res.ok) { const errText = await res.text(); container.innerHTML = `<div class="card" style="grid-column: 1/-1; color: #000; border: 2px solid #000; background: #fee2e2; font-family: Menlo, monospace; padding: 1rem;">Query failed (${res.status}): ${errText}</div>`; resetQueryBtn(); return; } let series = await res.json();
if (series && series.length > 0) { series = series.filter(s => s.values && s.values.length > 0); }
if (!series || series.length === 0) { container.innerHTML = '<div class="card" style="grid-column: 1/-1; text-align: center; color: #555; font-family: Menlo, monospace; padding: 2rem;">No matching series found in time window.</div>'; resetQueryBtn(); return; }
const maxCards = 60; const totalMatching = series.length; const displaySeries = series.slice(0, maxCards);
if (queryStatus) { queryStatus.innerHTML = `<span class="spinner"></span> Rendering ${displaySeries.length} graph(s)...`; }
container.innerHTML = ''; if (totalMatching > maxCards) { const notice = document.createElement('div'); notice.className = 'card'; notice.style.gridColumn = '1/-1'; notice.style.background = '#fef3c7'; notice.style.border = '1px solid #000'; notice.style.padding = '10px 14px'; notice.style.fontFamily = 'Menlo, monospace'; notice.style.fontSize = '0.8125rem'; notice.innerText = `Showing first ${maxCards} of ${totalMatching} matching series. Refine host/service filters to see specific series.`; container.appendChild(notice); }
for (const s of displaySeries) { const card = document.createElement('div'); card.className = 'card'; const svgUrl = `/api/v1/render?host=${encodeURIComponent('^' + s.host + '$')}&service=${encodeURIComponent('^' + s.service + '$')}&from=${from}&to=${to}&format=svg&w=640&h=220`; const asciiUrl = `/api/v1/render?host=${encodeURIComponent('^' + s.host + '$')}&service=${encodeURIComponent('^' + s.service + '$')}&from=${from}&to=${to}&format=ascii`; const count = s.values ? s.values.length : 0;
card.innerHTML = ` <div class="card-title"> <span>${s.host} / ${s.service} <small class="series-info">(${count} pts)</small></span> <span class="links"> <a href="${svgUrl}" target="_blank">SVG</a> <a href="${asciiUrl}" target="_blank">ASCII</a> </span> </div> <div class="chart-container loaded"> ${renderClientSVG(s, from, to)} <div class="chart-crosshair"></div> <div class="chart-dot"></div> <div class="chart-tooltip"></div> </div> `; container.appendChild(card);
const chartBox = card.querySelector('.chart-container'); const crosshair = card.querySelector('.chart-crosshair'); const dot = card.querySelector('.chart-dot'); const tooltip = card.querySelector('.chart-tooltip'); const infoEl = card.querySelector('.series-info');
if (s.timestamps && s.timestamps.length > 0 && s.values && s.values.length > 0) { setupChartHover(chartBox, crosshair, dot, tooltip, infoEl, s); } }
if (queryBtn) { queryBtn.disabled = false; queryBtn.innerText = 'Query'; }
if (queryStatus) { queryStatus.style.display = 'none'; }
} catch (e) { container.innerHTML = `<div class="card" style="grid-column: 1/-1; color: #000; border: 2px solid #000; background: #fee2e2; font-family: Menlo, monospace; padding: 1rem;">Error fetching query: ${e.message}</div>`; resetQueryBtn(); } }
function findNearestPoint(timestamps, target) { let low = 0; let high = timestamps.length - 1; while (low <= high) { const mid = (low + high) >> 1; if (timestamps[mid] < target) { low = mid + 1; } else if (timestamps[mid] > target) { high = mid - 1; } else { return mid; } } if (low >= timestamps.length) return timestamps.length - 1; if (high < 0) return 0; if (Math.abs(timestamps[low] - target) < Math.abs(timestamps[high] - target)) { return low; } return high; }
function formatValue(v) { if (Number.isInteger(v)) return v.toLocaleString(); if (Math.abs(v) >= 1000) return v.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); if (Math.abs(v) < 0.001 && v !== 0) return v.toExponential(3); return v.toFixed(2); }
function renderClientSVG(s, from, to) { const timestamps = s.timestamps || []; const values = s.values || []; const width = 640; const height = 220;
const title = `${s.host} / ${s.service}`; if (timestamps.length === 0 || values.length === 0) { return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"> <rect width="100%" height="100%" fill="#ffffff" stroke="#000000" stroke-width="1" rx="4"/> <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#555555" font-family="Menlo, monospace" font-size="14">No data</text> </svg>`; }
let minVal = values[0]; let maxVal = values[0]; for (let i = 1; i < values.length; i++) { if (values[i] < minVal) minVal = values[i]; if (values[i] > maxVal) maxVal = values[i]; } if (minVal === maxVal) { minVal -= 1.0; maxVal += 1.0; }
const paddingLeft = 60.0; const paddingRight = 25.0; const paddingTop = 35.0; const paddingBottom = 42.0;
const plotW = width - paddingLeft - paddingRight; const plotH = height - paddingTop - paddingBottom;
const minTS = timestamps[0]; let maxTS = timestamps[timestamps.length - 1]; if (minTS >= maxTS) { maxTS = minTS + 60000; }
let pathD = ''; let firstX = paddingLeft; let lastX = paddingLeft + plotW;
for (let i = 0; i < timestamps.length; i++) { const x = paddingLeft + ((timestamps[i] - minTS) / (maxTS - minTS)) * plotW; const y = paddingTop + plotH - ((values[i] - minVal) / (maxVal - minVal)) * plotH; if (i === 0) { firstX = x; pathD += `M ${x.toFixed(2)},${y.toFixed(2)}`; } else { pathD += ` L ${x.toFixed(2)},${y.toFixed(2)}`; } if (i === timestamps.length - 1) { lastX = x; } }
const areaD = `${pathD} L ${lastX.toFixed(2)},${(paddingTop + plotH).toFixed(2)} L ${firstX.toFixed(2)},${(paddingTop + plotH).toFixed(2)} Z`;
const span = maxTS - minTS; const numTicks = 5; let xTicks = ''; const pad = (n) => (n < 10 ? '0' + n : n);
for (let k = 0; k < numTicks; k++) { const frac = k / (numTicks - 1); const x = paddingLeft + frac * plotW; const tMillis = minTS + frac * (maxTS - minTS); const d = new Date(tMillis);
const timeHMS = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`; const timeHM = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`; const dateStr = `${d.toLocaleString('en-US', { month: 'short', timeZone: 'UTC' })} ${pad(d.getUTCDate())}`; const yearStr = `${d.getUTCFullYear()}`;
let line1 = '', line2 = ''; if (span <= 10 * 60 * 1000) { line1 = timeHMS; line2 = dateStr; } else if (span <= 7 * 24 * 3600 * 1000) { line1 = timeHM; line2 = dateStr; } else { line1 = dateStr; line2 = yearStr; }
const anchor = k === 0 ? 'start' : (k === numTicks - 1 ? 'end' : 'middle');
if (k > 0 && k < numTicks - 1) { xTicks += `<line x1="${x.toFixed(1)}" y1="${paddingTop.toFixed(1)}" x2="${x.toFixed(1)}" y2="${(paddingTop + plotH).toFixed(1)}" stroke="#e0e0e0" stroke-width="1" stroke-dasharray="2 4"/>\n`; } xTicks += `<line x1="${x.toFixed(1)}" y1="${(paddingTop + plotH).toFixed(1)}" x2="${x.toFixed(1)}" y2="${(paddingTop + plotH + 4).toFixed(1)}" stroke="#000000" stroke-width="1"/>\n`; xTicks += `<text x="${x.toFixed(1)}" y="${(paddingTop + plotH + 16).toFixed(1)}" fill="#000000" font-family="Menlo, monospace" font-size="10" text-anchor="${anchor}"> <tspan x="${x.toFixed(1)}" dy="0">${line1}</tspan> <tspan x="${x.toFixed(1)}" dy="12" fill="#444444" font-size="9">${line2}</tspan> </text>\n`; }
const latestVal = values[values.length - 1]; const midVal = (minVal + maxVal) / 2.0;
const gradId = `grad_${Math.random().toString(36).substr(2, 9)}`;
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"> <defs> <linearGradient id="${gradId}" x1="0" y1="0" x2="0" y2="1"> <stop offset="0%" stop-color="#000000" stop-opacity="0.08"/> <stop offset="100%" stop-color="#000000" stop-opacity="0.0"/> </linearGradient> </defs> <rect width="100%" height="100%" fill="#ffffff" stroke="#000000" stroke-width="1" rx="4"/> <text x="16" y="22" fill="#000000" font-family="Arial, sans-serif" font-size="13" font-weight="600">${title}</text> <text x="${(width - paddingRight).toFixed(1)}" y="22" fill="#000000" font-family="Menlo, monospace" font-size="12" font-weight="600" text-anchor="end">Latest: ${formatValue(latestVal)}</text> <!-- Y Axis Grid & Labels --> <line x1="${paddingLeft}" y1="${paddingTop}" x2="${paddingLeft + plotW}" y2="${paddingTop}" stroke="#e0e0e0" stroke-width="1" stroke-dasharray="3 3"/> <text x="${paddingLeft - 8}" y="${paddingTop + 4}" fill="#000000" font-family="Menlo, monospace" font-size="10" text-anchor="end">${formatValue(maxVal)}</text> <line x1="${paddingLeft}" y1="${paddingTop + plotH / 2}" x2="${paddingLeft + plotW}" y2="${paddingTop + plotH / 2}" stroke="#e0e0e0" stroke-width="1" stroke-dasharray="3 3"/> <text x="${paddingLeft - 8}" y="${paddingTop + plotH / 2 + 4}" fill="#444444" font-family="Menlo, monospace" font-size="10" text-anchor="end">${formatValue(midVal)}</text> <line x1="${paddingLeft}" y1="${paddingTop + plotH}" x2="${paddingLeft + plotW}" y2="${paddingTop + plotH}" stroke="#000000" stroke-width="1"/> <text x="${paddingLeft - 8}" y="${paddingTop + plotH + 4}" fill="#000000" font-family="Menlo, monospace" font-size="10" text-anchor="end">${formatValue(minVal)}</text>
<!-- X Axis Time Grid & Labels (UTC) --> ${xTicks} <text x="${paddingLeft - 8}" y="${paddingTop + plotH + 16}" fill="#444444" font-family="Menlo, monospace" font-size="9" text-anchor="end">UTC</text>
<!-- Data Plot --> <path d="${areaD}" fill="url(#${gradId})"/> <path d="${pathD}" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> </svg>`; }
function setupChartHover(chartBox, crosshair, dot, tooltip, infoEl, s) { const timestamps = s.timestamps; const values = s.values; const n = timestamps.length; if (n === 0) return;
const minTS = timestamps[0]; let maxTS = timestamps[n - 1]; if (minTS >= maxTS) { maxTS = minTS + 60000; }
let minVal = values[0]; let maxVal = values[0]; for (let i = 1; i < n; i++) { if (values[i] < minVal) minVal = values[i]; if (values[i] > maxVal) maxVal = values[i]; } if (minVal === maxVal) { minVal -= 1.0; maxVal += 1.0; }
const defaultText = `(${n} pts)`;
const hide = () => { crosshair.style.display = 'none'; dot.style.display = 'none'; tooltip.style.display = 'none'; if (infoEl) infoEl.innerText = defaultText; };
const handleMove = (mouseX, mouseY) => { const rect = chartBox.getBoundingClientRect(); const W_box = rect.width; const H_box = rect.height; if (W_box <= 0 || H_box <= 0) return;
// Matches RenderSVG geometry: viewBox 0 0 640 220 const A = 640.0 / 220.0; let W_svg, H_svg, X_offset, Y_offset;
if (W_box / H_box >= A) { H_svg = H_box; W_svg = H_box * A; X_offset = (W_box - W_svg) / 2.0; Y_offset = 0; } else { W_svg = W_box; H_svg = W_box / A; X_offset = 0; Y_offset = (H_box - H_svg) / 2.0; }
// Plot area within 640x220: paddingLeft 60, plotW 555, paddingTop 35, plotH 143 const xMinPlot = X_offset + (60.0 / 640.0) * W_svg; const xMaxPlot = X_offset + (615.0 / 640.0) * W_svg; const yTopPlot = Y_offset + (35.0 / 220.0) * H_svg; const yBottomPlot = Y_offset + (178.0 / 220.0) * H_svg;
if (mouseX < xMinPlot || mouseX > xMaxPlot || mouseY < 0 || mouseY > H_box) { hide(); return; }
const frac = (mouseX - xMinPlot) / (xMaxPlot - xMinPlot); const tTarget = minTS + frac * (maxTS - minTS);
const idx = findNearestPoint(timestamps, tTarget); const tPt = timestamps[idx]; const vPt = values[idx];
const ptFracX = (tPt - minTS) / (maxTS - minTS); const ptFracY = (vPt - minVal) / (maxVal - minVal);
const xPt = X_offset + ((60.0 + ptFracX * 555.0) / 640.0) * W_svg; const yPt = Y_offset + ((35.0 + 143.0 - ptFracY * 143.0) / 220.0) * H_svg;
crosshair.style.display = 'block'; crosshair.style.left = `${xPt}px`; crosshair.style.top = `${yTopPlot}px`; crosshair.style.height = `${yBottomPlot - yTopPlot}px`;
dot.style.display = 'block'; dot.style.left = `${xPt}px`; dot.style.top = `${yPt}px`;
const d = new Date(tPt); const pad = (num) => String(num).padStart(2, '0'); const utcDate = `${d.getUTCFullYear()}-${pad(d.getUTCMonth()+1)}-${pad(d.getUTCDate())}`; const utcTime = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`; const locTime = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }); const valStr = formatValue(vPt);
tooltip.innerHTML = ` <div style="font-weight: bold; font-size: 0.8125rem; color: #000;">${valStr}</div> <div style="color: #222; margin-top: 3px;">${utcDate} ${utcTime}</div> <div style="color: #666; font-size: 0.6875rem; margin-top: 2px;">Local: ${locTime}</div> `; tooltip.style.display = 'block';
const tipWidth = tooltip.offsetWidth || 160; const tipHeight = tooltip.offsetHeight || 55;
let tipLeft = xPt + 12; if (tipLeft + tipWidth > W_box - 8) { tipLeft = xPt - tipWidth - 12; } let tipTop = yPt - tipHeight / 2; if (tipTop < 6) tipTop = 6; if (tipTop + tipHeight > H_box - 6) tipTop = H_box - tipHeight - 6;
tooltip.style.left = `${tipLeft}px`; tooltip.style.top = `${tipTop}px`;
if (infoEl) { infoEl.innerHTML = `— <strong>${valStr}</strong> at ${utcDate} ${utcTime}`; } };
chartBox.addEventListener('mousemove', (e) => { const rect = chartBox.getBoundingClientRect(); handleMove(e.clientX - rect.left, e.clientY - rect.top); }); chartBox.addEventListener('mouseleave', hide);
chartBox.addEventListener('touchstart', (e) => { if (e.touches && e.touches.length > 0) { const rect = chartBox.getBoundingClientRect(); handleMove(e.touches[0].clientX - rect.left, e.touches[0].clientY - rect.top); } }, { passive: true }); chartBox.addEventListener('touchmove', (e) => { if (e.touches && e.touches.length > 0) { const rect = chartBox.getBoundingClientRect(); handleMove(e.touches[0].clientX - rect.left, e.touches[0].clientY - rect.top); } }, { passive: true }); chartBox.addEventListener('touchend', hide); }
function applyURLParams() { const params = new URLSearchParams(window.location.search); const host = params.get('host'); const service = params.get('service'); const range = params.get('range'); const from = params.get('from'); const to = params.get('to');
if (host !== null && host !== '') { document.getElementById('hostFilter').value = host; } if (service !== null && service !== '') { document.getElementById('serviceFilter').value = service; }
const rangeSelect = document.getElementById('timeRange'); const rangeAliases = { '15m': '900000', '1h': '3600000', '6h': '21600000', '24h': '86400000', '1d': '86400000', '7d': '604800000', '30d': '2592000000', '90d': '7776000000', '6m': '15552000000', '1y': '31536000000', };
if (from !== null && from !== '') { const fromMs = /^\d+$/.test(from) ? parseInt(from, 10) : Date.parse(from); if (!isNaN(fromMs)) { rangeSelect.value = 'custom'; handleTimeRangeChange(); document.getElementById('customFrom').value = formatDateTimeLocal(new Date(fromMs)); if (to !== null && to !== '') { const toMs = /^\d+$/.test(to) ? parseInt(to, 10) : Date.parse(to); if (!isNaN(toMs)) { document.getElementById('customTo').value = formatDateTimeLocal(new Date(toMs)); } } } } else if (range !== null && range !== '') { const mapped = rangeAliases[range.toLowerCase()] || range; if (Array.from(rangeSelect.options).some(opt => opt.value === mapped)) { rangeSelect.value = mapped; handleTimeRangeChange(); } } }
function updateURLParams(host, service, rangeVal, from, to) { const params = new URLSearchParams(); if (host && host !== '.*') { params.set('host', host); } if (service && service !== '.*') { params.set('service', service); } if (rangeVal === 'custom') { params.set('from', String(from)); params.set('to', String(to)); } else if (rangeVal && rangeVal !== '3600000') { params.set('range', rangeVal); } const qs = params.toString(); const newURL = qs ? `${window.location.pathname}?${qs}` : window.location.pathname; window.history.replaceState(null, '', newURL); }
['hostFilter', 'serviceFilter', 'customFrom', 'customTo'].forEach(id => { const el = document.getElementById(id); if (el) { el.addEventListener('keydown', (e) => { if (e.key === 'Enter') refreshData(); }); } });
// Initial load applyURLParams(); refreshData(); setInterval(fetchStats, 5000); </script></body></html>