refactor: full SSR dashboard, minimal SSE DOM patches, poll-based refresh

This commit is contained in:
M1
2026-03-16 21:14:45 +04:00
parent 878829111f
commit 2f7273604b
6 changed files with 299 additions and 376 deletions
+107 -192
View File
@@ -1,24 +1,35 @@
<%~ include('./partials/head', { title: 'Monitor', scripts: ['/dashboard/query-builder.js'] }) %>
<%~ include('./partials/nav', { nav: 'monitors' }) %>
<%
const m = it.monitor;
const pings = it.pings || [];
const lastPing = pings[0];
const upPings = pings.filter(p => p.up);
const latencies = pings.filter(p => p.latency_ms != null).map(p => p.latency_ms);
const avgLatency = latencies.length ? Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length) : null;
const uptime = pings.length ? Math.round((upPings.length / pings.length) * 100) : null;
const barPings = pings.slice(0, 60).reverse();
const chartPings = pings.slice().reverse();
%>
<main class="max-w-7xl mx-auto px-8 py-8">
<div class="mb-6">
<a href="/dashboard/home" class="text-sm text-gray-500 hover:text-gray-300 transition-colors">&larr; Back</a>
</div>
<div id="loading" class="text-center py-16 text-gray-600">Loading...</div>
<div id="content" class="hidden">
<div id="content">
<!-- Header -->
<div class="flex items-center justify-between mb-8">
<div>
<div class="flex items-center gap-3">
<span id="status-dot"></span>
<h2 id="monitor-name" class="text-xl font-semibold text-gray-100"></h2>
<span id="status-dot"><%~ lastPing ? (lastPing.up ? '<span class="inline-block w-2.5 h-2.5 rounded-full bg-green-400 mr-2" title="Up"></span>' : '<span class="inline-block w-2.5 h-2.5 rounded-full bg-red-400 mr-2" title="Down"></span>') : '<span class="inline-block w-2.5 h-2.5 rounded-full bg-gray-600 mr-2" title="Unknown"></span>' %></span>
<h2 id="monitor-name" class="text-xl font-semibold text-gray-100"><%= m.name %></h2>
</div>
<p id="monitor-url" class="text-sm text-gray-500 mt-1"></p>
<p id="monitor-url" class="text-sm text-gray-500 mt-1"><%= m.url %></p>
</div>
<div class="flex items-center gap-3">
<button id="toggle-btn" class="text-sm px-4 py-2 rounded-lg border border-gray-700 hover:border-gray-600 transition-colors"></button>
<button id="toggle-btn" class="text-sm px-4 py-2 rounded-lg border transition-colors <%= m.enabled ? 'border-gray-700 hover:border-gray-600 text-gray-300' : 'border-green-800 hover:border-green-700 text-green-400' %>"><%= m.enabled ? 'Pause' : 'Resume' %></button>
<button id="delete-btn" class="text-sm px-4 py-2 rounded-lg border border-red-900/50 text-red-400 hover:bg-red-900/20 transition-colors">Delete</button>
</div>
</div>
@@ -27,32 +38,40 @@
<div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-8">
<div class="bg-gray-900 border border-gray-800 rounded-xl p-4">
<div class="text-xs text-gray-500 mb-1">Status</div>
<div id="stat-status" class="text-lg font-semibold"></div>
<div id="stat-status" class="text-lg font-semibold"><%~ lastPing ? (lastPing.up ? '<span class="text-green-400">Up</span>' : '<span class="text-red-400">Down</span>') : '<span class="text-gray-500">—</span>' %></div>
</div>
<div class="bg-gray-900 border border-gray-800 rounded-xl p-4">
<div class="text-xs text-gray-500 mb-1">Avg Latency</div>
<div id="stat-latency" class="text-lg font-semibold text-gray-200"></div>
<div id="stat-latency" class="text-lg font-semibold text-gray-200"><%= avgLatency != null ? avgLatency + 'ms' : '—' %></div>
</div>
<div class="bg-gray-900 border border-gray-800 rounded-xl p-4">
<div class="text-xs text-gray-500 mb-1">Uptime</div>
<div id="stat-uptime" class="text-lg font-semibold text-gray-200"></div>
<div id="stat-uptime" class="text-lg font-semibold text-gray-200"><%= uptime != null ? uptime + '%' : '—' %></div>
</div>
<div class="bg-gray-900 border border-gray-800 rounded-xl p-4">
<div class="text-xs text-gray-500 mb-1">Last Ping</div>
<div id="stat-last" class="text-lg font-semibold text-gray-200"></div>
<div id="stat-last" class="text-lg font-semibold text-gray-200"><%~ lastPing ? it.timeAgoSSR(lastPing.checked_at) : '—' %></div>
</div>
</div>
<!-- Status history chart -->
<!-- Latency chart -->
<div class="bg-gray-900 border border-gray-800 rounded-xl p-4 mb-8">
<h3 class="text-sm text-gray-400 mb-3">Response Time</h3>
<div id="latency-chart" class="h-32"></div>
<div id="latency-chart" class="h-32"><%~ it.latencyChartSSR(chartPings) %></div>
</div>
<!-- Status bar (up/down timeline) -->
<!-- Status bar -->
<div class="bg-gray-900 border border-gray-800 rounded-xl p-4 mb-8">
<h3 class="text-sm text-gray-400 mb-3">Status History</h3>
<div id="status-bar" class="flex gap-0.5 h-8 rounded overflow-hidden"></div>
<div id="status-bar" class="flex gap-0.5 h-8 rounded overflow-hidden">
<% if (barPings.length > 0) { %>
<% barPings.forEach(function(c) { %>
<div class="flex-1 <%= c.up ? 'bg-green-500/70' : 'bg-red-500/70' %>" title="<%= new Date(c.checked_at).toLocaleString() %> — <%= c.up ? 'Up' : 'Down' %> <%= c.latency_ms ? c.latency_ms + 'ms' : '' %>"></div>
<% }) %>
<% } else { %>
<div class="flex-1 bg-gray-800 text-center text-xs text-gray-600 leading-8">No data</div>
<% } %>
</div>
</div>
<!-- Recent pings table -->
@@ -71,7 +90,17 @@
<th class="text-left px-4 py-2 font-medium">Error</th>
</tr>
</thead>
<tbody id="pings-table" class="divide-y divide-gray-800/50"></tbody>
<tbody id="pings-table" class="divide-y divide-gray-800/50">
<% pings.slice(0, 30).forEach(function(c) { %>
<tr class="hover:bg-gray-800/50">
<td class="px-4 py-2"><%~ c.up ? '<span class="text-green-400">Up</span>' : '<span class="text-red-400">Down</span>' %></td>
<td class="px-4 py-2 text-gray-300"><%= c.status_code != null ? c.status_code : '—' %></td>
<td class="px-4 py-2 text-gray-300"><%= c.latency_ms != null ? c.latency_ms + 'ms' : '—' %></td>
<td class="px-4 py-2 text-gray-500"><%~ it.timeAgoSSR(c.checked_at) %></td>
<td class="px-4 py-2 text-red-400/70 text-xs truncate max-w-[200px]"><%= c.error ? c.error : '' %></td>
</tr>
<% }) %>
</tbody>
</table>
</div>
</div>
@@ -83,7 +112,7 @@
<div>
<label class="block text-sm text-gray-400 mb-1.5">Name</label>
<input id="edit-name" type="text"
<input id="edit-name" type="text" value="<%= m.name %>"
class="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2.5 text-gray-100 focus:outline-none focus:border-blue-500">
</div>
@@ -92,10 +121,11 @@
<div class="flex gap-2">
<select id="edit-method"
class="bg-gray-800 border border-gray-700 rounded-lg px-3 py-2.5 text-gray-100 focus:outline-none focus:border-blue-500 font-mono text-sm">
<option>GET</option><option>POST</option><option>PUT</option>
<option>PATCH</option><option>DELETE</option><option>HEAD</option><option>OPTIONS</option>
<% ['GET','POST','PUT','PATCH','DELETE','HEAD','OPTIONS'].forEach(function(method) { %>
<option <%= (m.method || 'GET') === method ? 'selected' : '' %>><%= method %></option>
<% }) %>
</select>
<input id="edit-url" type="url"
<input id="edit-url" type="url" value="<%= m.url %>"
class="flex-1 bg-gray-800 border border-gray-700 rounded-lg px-4 py-2.5 text-gray-100 focus:outline-none focus:border-blue-500">
</div>
</div>
@@ -105,35 +135,39 @@
<label class="text-sm text-gray-400">Headers <span class="text-gray-600">(optional)</span></label>
<button type="button" id="edit-add-header" class="text-xs text-blue-400 hover:text-blue-300 transition-colors">+ Add header</button>
</div>
<div id="edit-headers-list" class="space-y-2"></div>
<div id="edit-headers-list" class="space-y-2">
<% if (m.request_headers && typeof m.request_headers === 'object') {
Object.entries(m.request_headers).forEach(function([k, v]) { %>
<div class="header-row flex gap-2">
<input type="text" value="<%= k %>" placeholder="Header name" class="hk flex-1 bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500 text-sm">
<input type="text" value="<%= v %>" placeholder="Value" class="hv flex-1 bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500 text-sm">
<button type="button" onclick="this.parentElement.remove()" class="px-2 text-gray-600 hover:text-red-400 transition-colors text-sm">✕</button>
</div>
<% }) } %>
</div>
</div>
<div id="edit-body-section" class="hidden">
<div id="edit-body-section" class="<%= ['GET','HEAD','OPTIONS'].includes(m.method || 'GET') ? 'hidden' : '' %>">
<label class="block text-sm text-gray-400 mb-1.5">Request Body <span class="text-gray-600">(optional)</span></label>
<textarea id="edit-request-body" rows="4" placeholder='{"key": "value"}'
class="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2.5 text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500 font-mono text-sm resize-y"></textarea>
class="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2.5 text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500 font-mono text-sm resize-y"><%= m.request_body || '' %></textarea>
</div>
<div class="flex gap-4">
<div class="flex-1">
<label class="block text-sm text-gray-400 mb-1.5">Interval</label>
<select id="edit-interval" class="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2.5 text-gray-100 focus:outline-none focus:border-blue-500">
<option value="10">10 seconds</option>
<option value="30">30 seconds</option>
<option value="60">1 minute</option>
<option value="300">5 minutes</option>
<option value="600">10 minutes</option>
<option value="1800">30 minutes</option>
<option value="3600">1 hour</option>
<% [['10','10 seconds'],['30','30 seconds'],['60','1 minute'],['300','5 minutes'],['600','10 minutes'],['1800','30 minutes'],['3600','1 hour']].forEach(function([val, label]) { %>
<option value="<%= val %>" <%= String(m.interval_s) === val ? 'selected' : '' %>><%= label %></option>
<% }) %>
</select>
</div>
<div class="flex-1">
<label class="block text-sm text-gray-400 mb-1.5">Timeout</label>
<select id="edit-timeout" class="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2.5 text-gray-100 focus:outline-none focus:border-blue-500">
<option value="5000">5 seconds</option>
<option value="10000">10 seconds</option>
<option value="30000">30 seconds</option>
<option value="60000">60 seconds</option>
<% [['5000','5 seconds'],['10000','10 seconds'],['30000','30 seconds'],['60000','60 seconds']].forEach(function([val, label]) { %>
<option value="<%= val %>" <%= String(m.timeout_ms || 30000) === val ? 'selected' : '' %>><%= label %></option>
<% }) %>
</select>
</div>
</div>
@@ -153,12 +187,13 @@
<script>
const monitorId = window.location.pathname.split('/').pop();
let editQuery = null;
const monitorId = '<%= m.id %>';
let editQuery = <%~ JSON.stringify(m.query || null) %>;
const editQb = new QueryBuilder(document.getElementById('edit-query-builder'), (q) => {
editQuery = q;
});
editQb.setQuery(editQuery);
// Method/body visibility
const editMethod = document.getElementById('edit-method');
@@ -184,144 +219,18 @@
container.appendChild(row);
}
async function load() {
try {
const data = await api(`/monitors/${monitorId}`);
document.getElementById('loading').classList.add('hidden');
document.getElementById('content').classList.remove('hidden');
// Toggle button
document.getElementById('toggle-btn').onclick = async () => {
await api(`/monitors/${monitorId}/toggle`, { method: 'POST' });
location.reload();
};
const results = data.results || [];
const lastPing = results[0];
// Header
document.getElementById('monitor-name').textContent = data.name;
document.getElementById('monitor-url').textContent = data.url;
document.getElementById('status-dot').innerHTML = statusBadge(lastPing?.up);
// Toggle button
const toggleBtn = document.getElementById('toggle-btn');
toggleBtn.textContent = data.enabled ? 'Pause' : 'Resume';
toggleBtn.className = `text-sm px-4 py-2 rounded-lg border transition-colors ${data.enabled ? 'border-gray-700 hover:border-gray-600 text-gray-300' : 'border-green-800 hover:border-green-700 text-green-400'}`;
toggleBtn.onclick = async () => {
await api(`/monitors/${monitorId}/toggle`, { method: 'POST' });
load();
};
// Delete button
document.getElementById('delete-btn').onclick = async () => {
if (!confirm('Delete this monitor and all its ping history?')) return;
await api(`/monitors/${monitorId}`, { method: 'DELETE' });
window.location.href = '/dashboard/home';
};
// Stats
const upPings = results.filter(r => r.up);
const latencies = results.filter(r => r.latency_ms != null).map(r => r.latency_ms);
const avgLatency = latencies.length ? Math.round(latencies.reduce((a, b) => a + b, 0) / latencies.length) : null;
const uptime = results.length ? Math.round((upPings.length / results.length) * 100) : null;
// Seed running stats for SSE incremental updates
_totalPings = results.length;
_upPings = upPings.length;
_latencies = results.filter(r => r.latency_ms != null).slice(-100).map(r => ({ ms: r.latency_ms, up: r.up }));
document.getElementById('stat-status').innerHTML = lastPing
? (lastPing.up ? '<span class="text-green-400">Up</span>' : '<span class="text-red-400">Down</span>')
: '<span class="text-gray-500">—</span>';
document.getElementById('stat-latency').textContent = avgLatency != null ? `${avgLatency}ms` : '—';
document.getElementById('stat-uptime').textContent = uptime != null ? `${uptime}%` : '—';
document.getElementById('stat-last').innerHTML = lastPing ? timeAgo(lastPing.checked_at) : '—';
// Latency chart
renderLatencyChart(results.slice().reverse());
// Status bar
const statusBar = document.getElementById('status-bar');
const barPings = results.slice(0, 60).reverse();
statusBar.innerHTML = barPings.map(c =>
`<div class="flex-1 ${c.up ? 'bg-green-500/70' : 'bg-red-500/70'}" title="${new Date(c.checked_at).toLocaleString()} — ${c.up ? 'Up' : 'Down'} ${c.latency_ms ? c.latency_ms + 'ms' : ''}"></div>`
).join('') || '<div class="flex-1 bg-gray-800 text-center text-xs text-gray-600 leading-8">No data</div>';
// Pings table
document.getElementById('pings-table').innerHTML = results.slice(0, 30).map(c => `
<tr class="hover:bg-gray-800/50">
<td class="px-4 py-2">${c.up ? '<span class="text-green-400">Up</span>' : '<span class="text-red-400">Down</span>'}</td>
<td class="px-4 py-2 text-gray-300">${c.status_code ?? '—'}</td>
<td class="px-4 py-2 text-gray-300">${c.latency_ms != null ? c.latency_ms + 'ms' : '—'}</td>
<td class="px-4 py-2 text-gray-500">${timeAgo(c.checked_at)}</td>
<td class="px-4 py-2 text-red-400/70 text-xs truncate max-w-[200px]">${c.error ? escapeHtml(c.error) : ''}</td>
</tr>
`).join('');
// Edit form
document.getElementById('edit-name').value = data.name;
document.getElementById('edit-url').value = data.url;
document.getElementById('edit-method').value = data.method || 'GET';
document.getElementById('edit-interval').value = String(data.interval_s);
document.getElementById('edit-timeout').value = String(data.timeout_ms || 30000);
document.getElementById('edit-request-body').value = data.request_body || '';
updateEditBodyVisibility();
const headersList = document.getElementById('edit-headers-list');
headersList.innerHTML = '';
if (data.request_headers && typeof data.request_headers === 'object') {
Object.entries(data.request_headers).forEach(([k, v]) => addHeaderRow(headersList, k, v));
}
editQuery = data.query;
editQb.setQuery(data.query);
} catch (e) {
document.getElementById('loading').innerHTML = `<span class="text-red-400">${escapeHtml(e.message)}</span>`;
}
}
function renderLatencyChart(pings) {
const container = document.getElementById('latency-chart');
const data = pings.filter(c => c.latency_ms != null);
if (data.length < 2) {
container.innerHTML = '<div class="h-full flex items-center justify-center text-gray-600 text-sm">Not enough data</div>';
return;
}
const values = data.map(c => c.latency_ms);
const ups = data.map(c => c.up);
const max = Math.max(...values, 1);
const min = Math.min(...values, 0);
const range = max - min || 1;
const w = container.clientWidth || 600;
const h = 128;
const step = w / Math.max(values.length - 1, 1);
const points = values.map((v, i) => {
const x = i * step;
const y = h - ((v - min) / range) * (h - 16) - 8;
return [x, y];
});
const pathD = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p[0]},${p[1]}`).join(' ');
const areaD = pathD + ` L${points[points.length - 1][0]},${h} L${points[0][0]},${h} Z`;
// Dots for down events
const dots = points.map((p, i) =>
!ups[i] ? `<circle cx="${p[0]}" cy="${p[1]}" r="3" fill="#f87171"/>` : ''
).join('');
container.innerHTML = `
<svg width="${w}" height="${h}" class="w-full">
<defs>
<linearGradient id="areaGrad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#3b82f6" stop-opacity="0.15"/>
<stop offset="100%" stop-color="#3b82f6" stop-opacity="0"/>
</linearGradient>
</defs>
<path d="${areaD}" fill="url(#areaGrad)"/>
<path d="${pathD}" fill="none" stroke="#3b82f6" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
${dots}
<text x="4" y="12" fill="#6b7280" font-size="10">${max}ms</text>
<text x="4" y="${h - 2}" fill="#6b7280" font-size="10">${min}ms</text>
</svg>
`;
}
// Delete button
document.getElementById('delete-btn').onclick = async () => {
if (!confirm('Delete this monitor and all its ping history?')) return;
await api(`/monitors/${monitorId}`, { method: 'DELETE' });
window.location.href = '/dashboard/home';
};
// Edit form submission
document.getElementById('edit-form').addEventListener('submit', async (e) => {
@@ -349,29 +258,26 @@
body.request_body = rb || null;
if (editQuery) body.query = editQuery;
await api(`/monitors/${monitorId}`, { method: 'PATCH', body });
load();
location.reload();
} catch (err) {
errEl.textContent = err.message;
errEl.classList.remove('hidden');
}
});
load();
// No interval poll — SSE handles all live updates
// Track running stats for SSE incremental updates
let _totalPings = <%= pings.length %>, _upPings = <%= upPings.length %>;
let _latencySum = <%= latencies.reduce((a, b) => a + b, 0) %>, _latencyCount = <%= latencies.length %>;
// Track running stats in memory for incremental updates
let _totalPings = 0, _upPings = 0, _latencies = []; // _latencies: [{ms, up}]
// SSE: live ping updates
const id = window.location.pathname.split('/').pop();
watchMonitor(id, (ping) => {
// ── Stats ───────────────────────────────────────────────────
// SSE: live ping updates (minimal DOM patches only — no chart re-render)
watchMonitor(monitorId, (ping) => {
// Stats
_totalPings++;
if (ping.up) _upPings++;
if (ping.latency_ms != null) {
_latencies.push({ ms: ping.latency_ms, up: ping.up });
if (_latencies.length > 100) _latencies.shift();
const avg = Math.round(_latencies.reduce((a,b)=>a+b.ms,0) / _latencies.length);
_latencySum += ping.latency_ms;
_latencyCount++;
const avg = Math.round(_latencySum / _latencyCount);
document.getElementById('stat-latency').textContent = avg + 'ms';
}
@@ -379,13 +285,16 @@
document.getElementById('stat-status').innerHTML = ping.up
? '<span class="text-green-400">Up</span>'
: '<span class="text-red-400">Down</span>';
document.getElementById('status-dot').innerHTML = ping.up
? '<span class="inline-block w-2.5 h-2.5 rounded-full bg-green-400 mr-2" title="Up"></span>'
: '<span class="inline-block w-2.5 h-2.5 rounded-full bg-red-400 mr-2" title="Down"></span>';
if (_totalPings > 0) {
const pct = Math.round((_upPings / _totalPings) * 100);
document.getElementById('stat-uptime').textContent = pct + '%';
}
// ── Status history bar — prepend a segment ───────────────────
// Status history bar — append new segment
const bar = document.getElementById('status-bar');
if (bar) {
const seg = document.createElement('div');
@@ -395,12 +304,7 @@
while (bar.children.length > 60) bar.removeChild(bar.lastChild);
}
// ── Latency chart ─────────────────────────────────────────────
if (ping.latency_ms != null) {
renderLatencyChart(_latencies.map(e => ({ latency_ms: e.ms, up: e.up, checked_at: '' })));
}
// ── Ping table ───────────────────────────────────────────────
// Ping table — prepend plain HTML row
const tbody = document.getElementById('pings-table');
if (tbody) {
const tr = document.createElement('tr');
@@ -416,6 +320,17 @@
while (tbody.children.length > 100) tbody.removeChild(tbody.lastChild);
}
});
// Poll every 30s to refresh the latency chart from server
setInterval(async () => {
try {
const res = await fetch(`/dashboard/monitors/${monitorId}/chart`, { credentials: 'same-origin' });
if (res.ok) {
const html = await res.text();
document.getElementById('latency-chart').innerHTML = html;
}
} catch {}
}, 30000);
</script>
<%~ include('./partials/foot') %>