- GET /api/metrics: per-route latency, event-loop lag, SSE fan-out, watcher ticks, memo builds, delta vs full reads, runs by origin (prometheus-client, own registry). Owner, or Prometheus with METRICS_TOKEN (scope 'metrics'). - POST /api/telemetry: web vitals, JS errors, update lag, feature events from the browser, bounded and checked. - telemetry.db: per-minute hub history, hourly per-route, usage per day (forever) and raw events (90 d). - GET /api/telemetry/hub and /api/telemetry/usage for the two pages. - /api/spawn stamps meta.origin (app | script | child | mcp | …). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
124 lines
4.8 KiB
Python
124 lines
4.8 KiB
Python
"""``POST /api/telemetry`` — what a browser reports, checked and taken in.
|
|
|
|
The client (frontend ``lib/telemetry/``) batches for ~30 s and sends on
|
|
``visibilitychange``/``pagehide`` with ``navigator.sendBeacon``. One batch:
|
|
|
|
{"device": "phone", "surface": "pwa",
|
|
"vitals": [{"name": "LCP", "value": 1840, "page": "/conversation/:id"}],
|
|
"errors": [{"message": "…", "source": "app.js:12", "stack": "…", "page": "/"}],
|
|
"events": [{"t": 1764000000.1, "kind": "view", "name": "page.home"},
|
|
{"t": …, "kind": "event", "name": "split.open", "props": {"n": 2}}],
|
|
"counters": {"longTasks": {"/": 3}, "reconnects": 1, "resyncs": 0}}
|
|
|
|
Everything is bounded: :data:`MAX_ITEMS` per list, names and pages by shape,
|
|
a message/stack by length, ``props`` to a few scalars. Anything else is
|
|
dropped, silently — a bad beacon is never worth an error page."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import time
|
|
|
|
from . import metrics
|
|
|
|
MAX_ITEMS = 200
|
|
VITALS = {"LCP", "INP", "CLS", "FCP", "TTFB", "update"}
|
|
_NAME_RE = re.compile(r"^[a-z][a-zA-Z0-9_.:\-]{0,63}$")
|
|
_PROP_KEY = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]{0,23}$")
|
|
MAX_PROPS = 6
|
|
|
|
|
|
def _props(p) -> str | None:
|
|
"""Up to :data:`MAX_PROPS` scalar props (short strings, numbers, bools)."""
|
|
if not isinstance(p, dict):
|
|
return None
|
|
out = {}
|
|
for k, v in list(p.items())[:MAX_PROPS]:
|
|
if not isinstance(k, str) or not _PROP_KEY.match(k):
|
|
continue
|
|
if isinstance(v, bool) or isinstance(v, (int, float)):
|
|
out[k] = v
|
|
elif isinstance(v, str):
|
|
out[k] = v[:40]
|
|
return json.dumps(out, separators=(",", ":")) if out else None
|
|
|
|
|
|
def take(store, uid: str, body: dict, now: float | None = None) -> dict:
|
|
"""Fold one beacon into the Prometheus registry and ``telemetry.db``;
|
|
returns how many of each it kept."""
|
|
now = now or time.time()
|
|
device = metrics.device_label(body.get("device"))
|
|
surface = body.get("surface") if body.get("surface") in ("pwa", "tab") else "tab"
|
|
kept = {"vitals": 0, "errors": 0, "events": 0}
|
|
|
|
vit_rows = []
|
|
for v in (body.get("vitals") or [])[:MAX_ITEMS]:
|
|
if not isinstance(v, dict) or v.get("name") not in VITALS:
|
|
continue
|
|
try:
|
|
value = float(v.get("value"))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if not 0 <= value < 600_000:
|
|
continue
|
|
page = metrics.page_label(v.get("page"))
|
|
name = v["name"]
|
|
if name == "CLS":
|
|
metrics.WEB_CLS.labels(page, device).observe(value)
|
|
elif name == "update":
|
|
metrics.WEB_UPDATE_LAG.labels(device).observe(value / 1000)
|
|
else:
|
|
metrics.WEB_VITAL.labels(name, page, device).observe(value / 1000)
|
|
vit_rows.append((now, uid, page, device, name, round(value, 3)))
|
|
store.add_vitals(vit_rows)
|
|
kept["vitals"] = len(vit_rows)
|
|
|
|
err_rows = []
|
|
day = time.strftime("%Y-%m-%d", time.localtime(now))
|
|
for e in (body.get("errors") or [])[:20]:
|
|
if not isinstance(e, dict) or not isinstance(e.get("message"), str):
|
|
continue
|
|
page = metrics.page_label(e.get("page"))
|
|
metrics.WEB_ERRORS.labels(page).inc()
|
|
src = e.get("source")
|
|
stack = e.get("stack")
|
|
err_rows.append({
|
|
"day": day, "t": now, "uid": uid, "device": device, "page": page,
|
|
"message": e["message"][:300],
|
|
"source": src[:200] if isinstance(src, str) else None,
|
|
"stack": stack[:2000] if isinstance(stack, str) else None})
|
|
store.add_errors(err_rows)
|
|
kept["errors"] = len(err_rows)
|
|
|
|
ev_rows = []
|
|
for e in (body.get("events") or [])[:MAX_ITEMS]:
|
|
if not isinstance(e, dict) or e.get("kind") not in ("view", "event"):
|
|
continue
|
|
name = e.get("name")
|
|
if not isinstance(name, str) or not _NAME_RE.match(name):
|
|
continue
|
|
try:
|
|
t = float(e.get("t") or now)
|
|
except (TypeError, ValueError):
|
|
t = now
|
|
if not now - 86400 < t <= now + 60: # a stale or clock-skewed batch: now
|
|
t = now
|
|
ev_rows.append((t, uid, device, surface, e["kind"], name, _props(e.get("props"))))
|
|
metrics.USAGE_EVENTS.labels(e["kind"]).inc()
|
|
store.add_events(ev_rows)
|
|
kept["events"] = len(ev_rows)
|
|
|
|
c = body.get("counters") or {}
|
|
if isinstance(c, dict):
|
|
lt = c.get("longTasks")
|
|
if isinstance(lt, dict):
|
|
for page, n in list(lt.items())[:20]:
|
|
if isinstance(n, int) and 0 < n < 10_000:
|
|
metrics.WEB_LONG_TASKS.labels(metrics.page_label(page), device).inc(n)
|
|
for k in ("reconnects", "resyncs", "fullReads"):
|
|
n = c.get(k)
|
|
if isinstance(n, int) and 0 < n < 10_000:
|
|
metrics.WEB_STREAM.labels(k).inc(n)
|
|
return kept
|