Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
dashboard.py · 17.1 KB · 397 lines
1"""Identity-aware operator dashboard, served as one DBBASIC object.
2
3Anonymous visitors see basic server health. Signed-in admins get live
4metrics, inventory, capability posture, and the recent change feed — the
5browser polls the admin APIs directly with the visitor's session cookie, so
6this page needs no data access of its own and shows exactly what the
7caller 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; }
18body { 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; }
21header { display: flex; align-items: baseline; gap: 1rem; margin-bottom: 1.25rem; }
22header h1 { font-size: 1.15rem; margin: 0; }
23header .who { margin-left: auto; color: var(--muted); font-size: 0.85rem; }
24header .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; }
32svg.chart { display: block; width: 100%; height: 120px; background: var(--panel);
33 border: 1px solid var(--line); border-radius: 8px; }
34svg.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); }
39section { margin-top: 1.5rem; }
40section 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); }
49table { width: 100%; border-collapse: collapse; background: var(--panel);
50 border: 1px solid var(--line); border-radius: 8px; overflow: hidden; }
51th, td { text-align: left; font-size: 0.82rem; padding: 0.45rem 0.75rem;
52 border-bottom: 1px solid var(--line); }
53th { color: var(--muted); font-weight: 500; }
54tr:last-child td { border-bottom: 0; }
55td.kind { color: var(--blue); white-space: nowrap; }
56td.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); }
60footer { margin-top: 2rem; color: var(--muted); font-size: 0.75rem; }
61"""
62
63_ADMIN_SCRIPT = """
64const fmt = (n) => typeof n === "number" ? n.toLocaleString() : (n ?? "-");
65const el = (id) => document.getElementById(id);
66
67function 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
74function 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
85async 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
91function 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
105function esc(value) {
106 return String(value ?? "").replace(/[&<>"]/g, (c) =>
107 ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
108}
109
110let changeDetails = [];
111
112function 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
129function 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
138function 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
144function 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 &middot; peak " + max.toFixed(1) + "ms";
156}
157
158async 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 const backups = status.scheduled_backups || {};
202 const backupValue = el("tile-backups").querySelector(".value");
203 const backupProblems = backups.problems || [];
204 backupValue.textContent = !backups.enabled ? "off" : (backups.healthy ? "OK" : "FAILING");
205 backupValue.className = "value " + (!backups.enabled ? "warn" : (backups.healthy ? "ok" : "bad"));
206 const lastGood = (backups.last_good_backup || {}).finished_at;
207 el("tile-backups").querySelector(".sub").textContent = !backups.enabled
208 ? "nothing leaves this box"
209 : (backupProblems.length ? backupProblems[0].message
210 : "last " + (lastGood || "").replace("T", " ").slice(0, 16));
211
212 const users = await fetchJson("/admin/identity/users");
213 setTile("tile-users", fmt(users.count), "registered users");
214
215 const sessions = await fetchJson("/admin/identity/sessions");
216 const active = (sessions.sessions || []).filter((s) => s.active);
217 setTile("tile-sessions", fmt(active.length), "active sessions");
218 el("sessions-body").innerHTML = active.map((s) =>
219 "<tr><td>" + esc(s.label || "-") + "</td><td>" + esc(s.user_id) +
220 "</td><td class=when>" + esc((s.created_at || "").replace("T", " ").slice(0, 19)) +
221 "</td><td class=when>" + esc((s.expires_at || "").replace("T", " ").slice(0, 19)) +
222 "</td></tr>").join("") ||
223 "<tr><td colspan=4 class=when>no active sessions</td></tr>";
224
225 const ops = await fetchJson("/admin/ops?limit=10");
226 el("ops-body").innerHTML = (ops.events || []).map((e) => {
227 const isError = e.kind === "execution_error";
228 const what = isError ? (e.error_type || "error") : (e.event || "auth");
229 const detail = isError
230 ? (e.object_id || "") + " — " + (e.message || "")
231 : [e.identifier || e.user_id || "", e.label || ""].filter(Boolean).join(" · ");
232 return "<tr><td class=" + (isError ? "bad" : "kind") + ">" + esc(what) +
233 "</td><td>" + esc(detail.slice(0, 110)) + "</td><td class=when>" +
234 esc((e.timestamp || "").replace("T", " ").slice(0, 19)) + "</td></tr>";
235 }).join("") || "<tr><td colspan=3 class=when>no ops events yet</td></tr>";
236
237 const changes = await fetchJson("/admin/changes?limit=12");
238 changeDetails = (changes.changes || []).map((change) => change.change || change);
239 const rows = (changes.changes || []).map((change, index) => {
240 const when = (change.timestamp || "").replace("T", " ").slice(0, 19);
241 return "<tr id=change-row-" + index + " style=cursor:pointer " +
242 "onclick=toggleChange(" + index + ")><td class=kind>" + esc(change.kind) +
243 "</td><td>" + esc(change.summary || change.action) +
244 "</td><td>" + esc(describeTarget(change.target)) +
245 "</td><td>" + esc(change.actor) + "</td><td class=when>" + when + "</td></tr>";
246 });
247 el("changes-body").innerHTML = rows.join("") ||
248 "<tr><td colspan=5 class=when>no recent changes</td></tr>";
249 el("updated").textContent = "updated " + new Date().toLocaleTimeString();
250 } catch (error) {
251 el("updated").textContent = "refresh failed: " + error.message;
252 }
253}
254
255refresh();
256setInterval(refresh, 10000);
257"""
258
259
260def _tile(tile_id, label, value="-", sub="", spark=False):
261 spark_svg = (
262 f'<svg class="spark" id="spark-{tile_id.removeprefix("tile-")}" '
263 f'viewBox="0 0 100 22" preserveAspectRatio="none"></svg>'
264 if spark
265 else ""
266 )
267 return (
268 f'<div class="tile" id="{tile_id}"><div class="label">{label}</div>'
269 f'<div class="value">{value}</div><div class="sub">{sub}</div>{spark_svg}</div>'
270 )
271
272
273def GET(request):
274 count = int(_state_manager.get("served", 0) or 0) + 1
275 _state_manager.set("served", count)
276
277 identity = request.get("_identity", {})
278 user_id = identity.get("user_id")
279 is_admin = "admin" in (identity.get("roles") or [])
280 _logger.info(
281 "system_dashboard served",
282 count=count,
283 user_id=user_id or "anonymous",
284 admin=is_admin,
285 )
286
287 if user_id:
288 who = (
289 f"signed in as <strong>{user_id}</strong> &middot; "
290 '<form method="post" action="/logout" style="display:inline">'
291 '<button style="background:none;border:0;color:var(--blue);cursor:pointer;'
292 'padding:0;font:inherit">sign out</button></form>'
293 )
294 else:
295 who = '<a href="/login?next=/dashboard">sign in</a> for live metrics'
296
297 if is_admin:
298 body = f"""
299<div class="grid">
300{_tile("tile-uptime", "Uptime")}
301{_tile("tile-requests", "Requests", spark=True)}
302{_tile("tile-errors", "Errors", spark=True)}
303{_tile("tile-capacity", "In Flight")}
304{_tile("tile-objects", "Objects")}
305{_tile("tile-collections", "Collections")}
306{_tile("tile-users", "Users")}
307{_tile("tile-sessions", "Sessions")}
308{_tile("tile-enforcement", "Enforcement")}
309{_tile("tile-backups", '<a href="/backups" style="color:inherit">Backups</a>')}
310</div>
311<section>
312<h2>Response Time</h2>
313<div class="bars">
314<div class="bar" id="bar-avg"><i></i><span>avg</span></div>
315<div class="bar" id="bar-p50"><i></i><span>p50</span></div>
316<div class="bar" id="bar-p95"><i></i><span>p95</span></div>
317<div class="bar" id="bar-p99"><i></i><span>p99</span></div>
318</div>
319</section>
320<section>
321<h2>Response Time History</h2>
322<svg class="chart" id="history-chart" viewBox="0 0 600 120" preserveAspectRatio="none"></svg>
323<div class="chart-legend" id="chart-note">collecting samples&hellip;</div>
324</section>
325<section>
326<h2>Top Paths</h2>
327<table>
328<thead><tr><th>Path</th><th>Requests</th><th>Errors</th></tr></thead>
329<tbody id="paths-body"><tr><td colspan="3" class="when">loading&hellip;</td></tr></tbody>
330</table>
331</section>
332<section>
333<h2>Ops Events</h2>
334<table>
335<thead><tr><th>What</th><th>Detail</th><th>When</th></tr></thead>
336<tbody id="ops-body"><tr><td colspan="3" class="when">loading&hellip;</td></tr></tbody>
337</table>
338</section>
339<section>
340<h2>Recent HTTP Errors</h2>
341<table>
342<thead><tr><th>Status</th><th>Request</th><th>Duration</th><th>When</th></tr></thead>
343<tbody id="errors-body"><tr><td colspan="4" class="when">loading&hellip;</td></tr></tbody>
344</table>
345</section>
346<section>
347<h2>Active Sessions</h2>
348<table>
349<thead><tr><th>Label</th><th>User</th><th>Created</th><th>Expires</th></tr></thead>
350<tbody id="sessions-body"><tr><td colspan="4" class="when">loading&hellip;</td></tr></tbody>
351</table>
352</section>
353<section>
354<h2>Recent Changes <span style="text-transform:none;letter-spacing:0">(click a row for detail)</span></h2>
355<table>
356<thead><tr><th>Kind</th><th>Summary</th><th>Target</th><th>Actor</th><th>When</th></tr></thead>
357<tbody id="changes-body"><tr><td colspan="5" class="when">loading&hellip;</td></tr></tbody>
358</table>
359</section>
360<footer id="updated">loading&hellip;</footer>
361<script>{_ADMIN_SCRIPT}</script>"""
362 elif user_id:
363 body = (
364 '<div class="hint">You are signed in, but live metrics need an '
365 "admin role. The server itself is healthy if you can read this "
366 "page &mdash; it was rendered by a live object.</div>"
367 )
368 else:
369 body = (
370 '<div class="hint">This dashboard is a running DBBASIC object. '
371 'The server is <span class="ok">healthy</span> if you can read '
372 'this page. <a href="/login?next=/dashboard">Sign in</a> to see '
373 "live metrics, inventory, and the change feed. Curious how this "
374 'page works? It is one Python file with a <code>GET(request)</code> '
375 "method, editable without a deploy.</div>"
376 )
377
378 html = f"""<!doctype html>
379<html lang="en">
380<head>
381<meta charset="utf-8">
382<meta name="viewport" content="width=device-width, initial-scale=1">
383<title>DBBASIC Dashboard</title>
384<style>{_STYLE}</style>
385</head>
386<body>
387<div class="wrap">
388<header>
389<h1>DBBASIC Dashboard</h1>
390<span class="who">{who}</span>
391</header>
392{body}
393</div>
394</body>
395</html>"""
396
397 return {"content_type": "text/html; charset=utf-8", "body": html}