askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
dashboard.py · 16.4 KB · 386 lines
| 1 | """Identity-aware operator dashboard, served as one DBBASIC object. |
| 2 | |
| 3 | Anonymous visitors see basic server health. Signed-in admins get live |
| 4 | metrics, inventory, capability posture, and the recent change feed — the |
| 5 | browser polls the admin APIs directly with the visitor's session cookie, so |
| 6 | this page needs no data access of its own and shows exactly what the |
| 7 | caller is allowed to see. |
| 8 | """ |
| 9 | |
| 10 | _STYLE = """ |
| 11 | :root { |
| 12 | color-scheme: dark; |
| 13 | --bg: #0b0b10; --panel: #17171f; --line: #2b2b37; |
| 14 | --text: #f4f4f7; --muted: #a2a2ad; |
| 15 | --green: #52d273; --blue: #5aa7ff; --amber: #f1b747; --red: #ff6b6b; |
| 16 | } |
| 17 | * { box-sizing: border-box; } |
| 18 | body { margin: 0; background: var(--bg); color: var(--text); |
| 19 | font: 15px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; } |
| 20 | .wrap { max-width: 1100px; margin: 0 auto; padding: 1.5rem; } |
| 21 | header { display: flex; align-items: baseline; gap: 1rem; margin-bottom: 1.25rem; } |
| 22 | header h1 { font-size: 1.15rem; margin: 0; } |
| 23 | header .who { margin-left: auto; color: var(--muted); font-size: 0.85rem; } |
| 24 | header .who a { color: var(--blue); text-decoration: none; } |
| 25 | .grid { display: grid; gap: 0.75rem; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); } |
| 26 | .tile { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 0.75rem 0.9rem; } |
| 27 | .tile .label { font-size: 0.7rem; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); } |
| 28 | .tile .value { font-size: 1.35rem; font-weight: 600; margin-top: 0.15rem; } |
| 29 | .tile .sub { font-size: 0.75rem; color: var(--muted); } |
| 30 | .tile svg.spark { display: block; width: 100%; height: 22px; margin-top: 0.35rem; } |
| 31 | .tile svg.spark polyline { fill: none; stroke: var(--blue); stroke-width: 1.5; } |
| 32 | svg.chart { display: block; width: 100%; height: 120px; background: var(--panel); |
| 33 | border: 1px solid var(--line); border-radius: 8px; } |
| 34 | svg.chart polyline { fill: none; stroke-width: 1.5; } |
| 35 | .chart-legend { font-size: 0.72rem; color: var(--muted); margin-top: 0.35rem; } |
| 36 | .chart-legend b { font-weight: 500; } |
| 37 | .legend-p95 { color: var(--blue); } .legend-p50 { color: var(--green); } |
| 38 | .ok { color: var(--green); } .warn { color: var(--amber); } .bad { color: var(--red); } |
| 39 | section { margin-top: 1.5rem; } |
| 40 | section h2 { font-size: 0.8rem; letter-spacing: 0.06em; text-transform: uppercase; |
| 41 | color: var(--muted); margin: 0 0 0.6rem; } |
| 42 | .bars { display: flex; gap: 1.25rem; align-items: flex-end; height: 76px; |
| 43 | background: var(--panel); border: 1px solid var(--line); border-radius: 8px; |
| 44 | padding: 0.75rem 1rem 0.5rem; } |
| 45 | .bar { display: flex; flex-direction: column; justify-content: flex-end; align-items: center; |
| 46 | gap: 0.3rem; width: 64px; height: 100%; } |
| 47 | .bar i { display: block; width: 100%; background: var(--blue); border-radius: 3px 3px 0 0; min-height: 2px; } |
| 48 | .bar span { font-size: 0.68rem; color: var(--muted); } |
| 49 | table { width: 100%; border-collapse: collapse; background: var(--panel); |
| 50 | border: 1px solid var(--line); border-radius: 8px; overflow: hidden; } |
| 51 | th, td { text-align: left; font-size: 0.82rem; padding: 0.45rem 0.75rem; |
| 52 | border-bottom: 1px solid var(--line); } |
| 53 | th { color: var(--muted); font-weight: 500; } |
| 54 | tr:last-child td { border-bottom: 0; } |
| 55 | td.kind { color: var(--blue); white-space: nowrap; } |
| 56 | td.when { color: var(--muted); white-space: nowrap; } |
| 57 | .hint { color: var(--muted); font-size: 0.85rem; background: var(--panel); |
| 58 | border: 1px solid var(--line); border-radius: 8px; padding: 0.9rem 1rem; } |
| 59 | .hint a { color: var(--blue); } |
| 60 | footer { margin-top: 2rem; color: var(--muted); font-size: 0.75rem; } |
| 61 | """ |
| 62 | |
| 63 | _ADMIN_SCRIPT = """ |
| 64 | const fmt = (n) => typeof n === "number" ? n.toLocaleString() : (n ?? "-"); |
| 65 | const el = (id) => document.getElementById(id); |
| 66 | |
| 67 | function setTile(id, value, sub) { |
| 68 | const tile = el(id); |
| 69 | if (!tile) return; |
| 70 | tile.querySelector(".value").textContent = value; |
| 71 | if (sub !== undefined) tile.querySelector(".sub").textContent = sub; |
| 72 | } |
| 73 | |
| 74 | function renderBars(times) { |
| 75 | const keys = ["avg", "p50", "p95", "p99"]; |
| 76 | const max = Math.max(...keys.map((k) => times[k] || 0), 1); |
| 77 | for (const key of keys) { |
| 78 | const bar = el("bar-" + key); |
| 79 | if (!bar) continue; |
| 80 | bar.querySelector("i").style.height = Math.max(3, (times[key] || 0) / max * 52) + "px"; |
| 81 | bar.querySelector("span").textContent = key + " " + (times[key] ?? 0) + "ms"; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | async function fetchJson(url) { |
| 86 | const response = await fetch(url, { headers: { Accept: "application/json" } }); |
| 87 | if (!response.ok) throw new Error(url + " -> " + response.status); |
| 88 | return response.json(); |
| 89 | } |
| 90 | |
| 91 | function describeTarget(target) { |
| 92 | if (!target) return ""; |
| 93 | if (typeof target === "string") return target; |
| 94 | if (target.object_id) { |
| 95 | return target.object_id + (target.version_id ? " v" + target.version_id : ""); |
| 96 | } |
| 97 | if (target.collection) { |
| 98 | return target.collection + (target.record_id ? "/" + target.record_id : ""); |
| 99 | } |
| 100 | if (target.package_id) return target.package_id; |
| 101 | if (target.file) return target.file; |
| 102 | return Object.values(target).filter((v) => typeof v === "string").join(" "); |
| 103 | } |
| 104 | |
| 105 | function esc(value) { |
| 106 | return String(value ?? "").replace(/[&<>"]/g, (c) => |
| 107 | ({ "&": "&", "<": "<", ">": ">", '"': """ }[c])); |
| 108 | } |
| 109 | |
| 110 | let changeDetails = []; |
| 111 | |
| 112 | function toggleChange(index) { |
| 113 | const detail = el("change-detail-" + index); |
| 114 | if (detail) { detail.remove(); return; } |
| 115 | const row = el("change-row-" + index); |
| 116 | if (!row) return; |
| 117 | const detailRow = document.createElement("tr"); |
| 118 | detailRow.id = "change-detail-" + index; |
| 119 | const cell = document.createElement("td"); |
| 120 | cell.colSpan = 5; |
| 121 | const pre = document.createElement("pre"); |
| 122 | pre.style.cssText = "margin:0;font-size:0.72rem;color:var(--muted);white-space:pre-wrap;"; |
| 123 | pre.textContent = JSON.stringify(changeDetails[index], null, 2); |
| 124 | cell.appendChild(pre); |
| 125 | detailRow.appendChild(cell); |
| 126 | row.after(detailRow); |
| 127 | } |
| 128 | |
| 129 | function polylinePoints(values, width, height, maxValue) { |
| 130 | const numbers = values.map((v) => (typeof v === "number" && isFinite(v) ? v : 0)); |
| 131 | const max = maxValue ?? Math.max(...numbers, 0.001); |
| 132 | const step = numbers.length > 1 ? width / (numbers.length - 1) : width; |
| 133 | return numbers.map((v, i) => |
| 134 | (i * step).toFixed(1) + "," + (height - 2 - (v / max) * (height - 4)).toFixed(1) |
| 135 | ).join(" "); |
| 136 | } |
| 137 | |
| 138 | function renderSpark(id, values) { |
| 139 | const host = el(id); |
| 140 | if (!host || values.length < 2) return; |
| 141 | host.innerHTML = "<polyline points=\\"" + polylinePoints(values, 100, 22) + "\\"/>"; |
| 142 | } |
| 143 | |
| 144 | function renderHistoryChart(history) { |
| 145 | const chart = el("history-chart"); |
| 146 | if (!chart || history.length < 2) return; |
| 147 | const p95 = history.map((row) => row.p95_ms); |
| 148 | const p50 = history.map((row) => row.p50_ms); |
| 149 | const max = Math.max(...p95.map((v) => v || 0), ...p50.map((v) => v || 0), 1); |
| 150 | chart.innerHTML = |
| 151 | "<polyline style=\\"stroke:var(--green)\\" points=\\"" + polylinePoints(p50, 600, 120, max) + "\\"/>" + |
| 152 | "<polyline style=\\"stroke:var(--blue)\\" points=\\"" + polylinePoints(p95, 600, 120, max) + "\\"/>"; |
| 153 | el("chart-note").innerHTML = |
| 154 | "<b class=legend-p95>p95</b> / <b class=legend-p50>p50</b> over last " + |
| 155 | history.length + " samples · peak " + max.toFixed(1) + "ms"; |
| 156 | } |
| 157 | |
| 158 | async function refresh() { |
| 159 | try { |
| 160 | const health = await fetchJson("/health?metrics=true&history=true"); |
| 161 | setTile("tile-uptime", health.uptime, "pid " + health.pid); |
| 162 | setTile("tile-requests", fmt(health.requests), health.rps + " req/s"); |
| 163 | const errValue = el("tile-errors").querySelector(".value"); |
| 164 | errValue.textContent = fmt(health.errors); |
| 165 | errValue.className = "value " + (health.errors > 0 ? "bad" : "ok"); |
| 166 | el("tile-errors").querySelector(".sub").textContent = |
| 167 | (health.error_rate * 100).toFixed(1) + "% error rate"; |
| 168 | setTile("tile-capacity", |
| 169 | health.capacity.requests.in_flight + "/" + health.capacity.requests.max, |
| 170 | "exec " + health.capacity.object_executions.in_flight + "/" + |
| 171 | health.capacity.object_executions.max); |
| 172 | renderBars(health.response_time_ms || {}); |
| 173 | |
| 174 | const history = health.history || []; |
| 175 | renderSpark("spark-requests", history.map((row) => row.rps)); |
| 176 | renderSpark("spark-errors", history.map((row) => row.error_rate)); |
| 177 | renderHistoryChart(history); |
| 178 | |
| 179 | const topPaths = ((health.metrics || {}).top_paths || []).slice(0, 8); |
| 180 | el("paths-body").innerHTML = topPaths.map((p) => |
| 181 | "<tr><td>" + esc(p.path) + "</td><td>" + fmt(p.requests) + |
| 182 | "</td><td class=" + (p.errors > 0 ? "bad" : "when") + ">" + fmt(p.errors) + "</td></tr>" |
| 183 | ).join("") || "<tr><td colspan=3 class=when>no traffic yet</td></tr>"; |
| 184 | |
| 185 | const httpErrors = ((health.metrics || {}).recent_errors || []).slice(-8).reverse(); |
| 186 | el("errors-body").innerHTML = httpErrors.map((e) => |
| 187 | "<tr><td class=" + (e.status >= 500 ? "bad" : "warn") + ">" + esc(e.status) + |
| 188 | "</td><td>" + esc(e.method) + " " + esc(e.path) + "</td><td class=when>" + |
| 189 | esc(e.duration_ms) + "ms</td><td class=when>" + |
| 190 | esc((e.timestamp || "").replace("T", " ").slice(0, 19)) + "</td></tr>" |
| 191 | ).join("") || "<tr><td colspan=4 class=when>no 4xx/5xx recorded</td></tr>"; |
| 192 | |
| 193 | const status = await fetchJson("/admin/status"); |
| 194 | const inv = status.inventory || {}; |
| 195 | setTile("tile-objects", fmt(inv.objects), inv.packages + " packages"); |
| 196 | setTile("tile-collections", fmt(inv.collections), inv.schemas + " schemas"); |
| 197 | const enforced = (status.permissions || {}).enforcement_enabled; |
| 198 | const enfValue = el("tile-enforcement").querySelector(".value"); |
| 199 | enfValue.textContent = enforced ? "ON" : "off"; |
| 200 | enfValue.className = "value " + (enforced ? "ok" : "warn"); |
| 201 | |
| 202 | const users = await fetchJson("/admin/identity/users"); |
| 203 | setTile("tile-users", fmt(users.count), "registered users"); |
| 204 | |
| 205 | const sessions = await fetchJson("/admin/identity/sessions"); |
| 206 | const active = (sessions.sessions || []).filter((s) => s.active); |
| 207 | setTile("tile-sessions", fmt(active.length), "active sessions"); |
| 208 | el("sessions-body").innerHTML = active.map((s) => |
| 209 | "<tr><td>" + esc(s.label || "-") + "</td><td>" + esc(s.user_id) + |
| 210 | "</td><td class=when>" + esc((s.created_at || "").replace("T", " ").slice(0, 19)) + |
| 211 | "</td><td class=when>" + esc((s.expires_at || "").replace("T", " ").slice(0, 19)) + |
| 212 | "</td></tr>").join("") || |
| 213 | "<tr><td colspan=4 class=when>no active sessions</td></tr>"; |
| 214 | |
| 215 | const ops = await fetchJson("/admin/ops?limit=10"); |
| 216 | el("ops-body").innerHTML = (ops.events || []).map((e) => { |
| 217 | const isError = e.kind === "execution_error"; |
| 218 | const what = isError ? (e.error_type || "error") : (e.event || "auth"); |
| 219 | const detail = isError |
| 220 | ? (e.object_id || "") + " — " + (e.message || "") |
| 221 | : [e.identifier || e.user_id || "", e.label || ""].filter(Boolean).join(" · "); |
| 222 | return "<tr><td class=" + (isError ? "bad" : "kind") + ">" + esc(what) + |
| 223 | "</td><td>" + esc(detail.slice(0, 110)) + "</td><td class=when>" + |
| 224 | esc((e.timestamp || "").replace("T", " ").slice(0, 19)) + "</td></tr>"; |
| 225 | }).join("") || "<tr><td colspan=3 class=when>no ops events yet</td></tr>"; |
| 226 | |
| 227 | const changes = await fetchJson("/admin/changes?limit=12"); |
| 228 | changeDetails = (changes.changes || []).map((change) => change.change || change); |
| 229 | const rows = (changes.changes || []).map((change, index) => { |
| 230 | const when = (change.timestamp || "").replace("T", " ").slice(0, 19); |
| 231 | return "<tr id=change-row-" + index + " style=cursor:pointer " + |
| 232 | "onclick=toggleChange(" + index + ")><td class=kind>" + esc(change.kind) + |
| 233 | "</td><td>" + esc(change.summary || change.action) + |
| 234 | "</td><td>" + esc(describeTarget(change.target)) + |
| 235 | "</td><td>" + esc(change.actor) + "</td><td class=when>" + when + "</td></tr>"; |
| 236 | }); |
| 237 | el("changes-body").innerHTML = rows.join("") || |
| 238 | "<tr><td colspan=5 class=when>no recent changes</td></tr>"; |
| 239 | el("updated").textContent = "updated " + new Date().toLocaleTimeString(); |
| 240 | } catch (error) { |
| 241 | el("updated").textContent = "refresh failed: " + error.message; |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | refresh(); |
| 246 | setInterval(refresh, 10000); |
| 247 | """ |
| 248 | |
| 249 | |
| 250 | def _tile(tile_id, label, value="-", sub="", spark=False): |
| 251 | spark_svg = ( |
| 252 | f'<svg class="spark" id="spark-{tile_id.removeprefix("tile-")}" ' |
| 253 | f'viewBox="0 0 100 22" preserveAspectRatio="none"></svg>' |
| 254 | if spark |
| 255 | else "" |
| 256 | ) |
| 257 | return ( |
| 258 | f'<div class="tile" id="{tile_id}"><div class="label">{label}</div>' |
| 259 | f'<div class="value">{value}</div><div class="sub">{sub}</div>{spark_svg}</div>' |
| 260 | ) |
| 261 | |
| 262 | |
| 263 | def GET(request): |
| 264 | count = int(_state_manager.get("served", 0) or 0) + 1 |
| 265 | _state_manager.set("served", count) |
| 266 | |
| 267 | identity = request.get("_identity", {}) |
| 268 | user_id = identity.get("user_id") |
| 269 | is_admin = "admin" in (identity.get("roles") or []) |
| 270 | _logger.info( |
| 271 | "system_dashboard served", |
| 272 | count=count, |
| 273 | user_id=user_id or "anonymous", |
| 274 | admin=is_admin, |
| 275 | ) |
| 276 | |
| 277 | if user_id: |
| 278 | who = ( |
| 279 | f"signed in as <strong>{user_id}</strong> · " |
| 280 | '<form method="post" action="/logout" style="display:inline">' |
| 281 | '<button style="background:none;border:0;color:var(--blue);cursor:pointer;' |
| 282 | 'padding:0;font:inherit">sign out</button></form>' |
| 283 | ) |
| 284 | else: |
| 285 | who = '<a href="/login?next=/dashboard">sign in</a> for live metrics' |
| 286 | |
| 287 | if is_admin: |
| 288 | body = f""" |
| 289 | <div class="grid"> |
| 290 | {_tile("tile-uptime", "Uptime")} |
| 291 | {_tile("tile-requests", "Requests", spark=True)} |
| 292 | {_tile("tile-errors", "Errors", spark=True)} |
| 293 | {_tile("tile-capacity", "In Flight")} |
| 294 | {_tile("tile-objects", "Objects")} |
| 295 | {_tile("tile-collections", "Collections")} |
| 296 | {_tile("tile-users", "Users")} |
| 297 | {_tile("tile-sessions", "Sessions")} |
| 298 | {_tile("tile-enforcement", "Enforcement")} |
| 299 | </div> |
| 300 | <section> |
| 301 | <h2>Response Time</h2> |
| 302 | <div class="bars"> |
| 303 | <div class="bar" id="bar-avg"><i></i><span>avg</span></div> |
| 304 | <div class="bar" id="bar-p50"><i></i><span>p50</span></div> |
| 305 | <div class="bar" id="bar-p95"><i></i><span>p95</span></div> |
| 306 | <div class="bar" id="bar-p99"><i></i><span>p99</span></div> |
| 307 | </div> |
| 308 | </section> |
| 309 | <section> |
| 310 | <h2>Response Time History</h2> |
| 311 | <svg class="chart" id="history-chart" viewBox="0 0 600 120" preserveAspectRatio="none"></svg> |
| 312 | <div class="chart-legend" id="chart-note">collecting samples…</div> |
| 313 | </section> |
| 314 | <section> |
| 315 | <h2>Top Paths</h2> |
| 316 | <table> |
| 317 | <thead><tr><th>Path</th><th>Requests</th><th>Errors</th></tr></thead> |
| 318 | <tbody id="paths-body"><tr><td colspan="3" class="when">loading…</td></tr></tbody> |
| 319 | </table> |
| 320 | </section> |
| 321 | <section> |
| 322 | <h2>Ops Events</h2> |
| 323 | <table> |
| 324 | <thead><tr><th>What</th><th>Detail</th><th>When</th></tr></thead> |
| 325 | <tbody id="ops-body"><tr><td colspan="3" class="when">loading…</td></tr></tbody> |
| 326 | </table> |
| 327 | </section> |
| 328 | <section> |
| 329 | <h2>Recent HTTP Errors</h2> |
| 330 | <table> |
| 331 | <thead><tr><th>Status</th><th>Request</th><th>Duration</th><th>When</th></tr></thead> |
| 332 | <tbody id="errors-body"><tr><td colspan="4" class="when">loading…</td></tr></tbody> |
| 333 | </table> |
| 334 | </section> |
| 335 | <section> |
| 336 | <h2>Active Sessions</h2> |
| 337 | <table> |
| 338 | <thead><tr><th>Label</th><th>User</th><th>Created</th><th>Expires</th></tr></thead> |
| 339 | <tbody id="sessions-body"><tr><td colspan="4" class="when">loading…</td></tr></tbody> |
| 340 | </table> |
| 341 | </section> |
| 342 | <section> |
| 343 | <h2>Recent Changes <span style="text-transform:none;letter-spacing:0">(click a row for detail)</span></h2> |
| 344 | <table> |
| 345 | <thead><tr><th>Kind</th><th>Summary</th><th>Target</th><th>Actor</th><th>When</th></tr></thead> |
| 346 | <tbody id="changes-body"><tr><td colspan="5" class="when">loading…</td></tr></tbody> |
| 347 | </table> |
| 348 | </section> |
| 349 | <footer id="updated">loading…</footer> |
| 350 | <script>{_ADMIN_SCRIPT}</script>""" |
| 351 | elif user_id: |
| 352 | body = ( |
| 353 | '<div class="hint">You are signed in, but live metrics need an ' |
| 354 | "admin role. The server itself is healthy if you can read this " |
| 355 | "page — it was rendered by a live object.</div>" |
| 356 | ) |
| 357 | else: |
| 358 | body = ( |
| 359 | '<div class="hint">This dashboard is a running DBBASIC object. ' |
| 360 | 'The server is <span class="ok">healthy</span> if you can read ' |
| 361 | 'this page. <a href="/login?next=/dashboard">Sign in</a> to see ' |
| 362 | "live metrics, inventory, and the change feed. Curious how this " |
| 363 | 'page works? It is one Python file with a <code>GET(request)</code> ' |
| 364 | "method, editable without a deploy.</div>" |
| 365 | ) |
| 366 | |
| 367 | html = f"""<!doctype html> |
| 368 | <html lang="en"> |
| 369 | <head> |
| 370 | <meta charset="utf-8"> |
| 371 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 372 | <title>DBBASIC Dashboard</title> |
| 373 | <style>{_STYLE}</style> |
| 374 | </head> |
| 375 | <body> |
| 376 | <div class="wrap"> |
| 377 | <header> |
| 378 | <h1>DBBASIC Dashboard</h1> |
| 379 | <span class="who">{who}</span> |
| 380 | </header> |
| 381 | {body} |
| 382 | </div> |
| 383 | </body> |
| 384 | </html>""" |
| 385 | |
| 386 | return {"content_type": "text/html; charset=utf-8", "body": html} |