Files
gabrielvidalandClaude Opus 5.5 72a4f84902 feat(telemetry): the hub's own metrics, a browser beacon and usage events
- 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>
2026-11-24 16:24:24 +01:00

73 lines
2.1 KiB
Python

"""Event-loop lag: the one number that says "the hub is stuck".
Every :data:`TICK` seconds a coroutine asks to be woken after :data:`TICK`
and measures how late it actually was. That overshoot is time the loop spent
on something else — a big body encoded on the loop thread, a sync call that
slipped in — during which *nothing* is served, ``/api/health`` included (the
symptom of every lag incident, CLAUDE.md → Performance).
The same tick samples the sync-handler thread pool and the SSE subscriber
count, and keeps the minute's lag for the Hub card (``store.flush``)."""
from __future__ import annotations
import asyncio
import threading
from . import metrics
TICK = 0.5
class LagWindow:
"""The current minute's lag samples (ms), taken by :meth:`take`."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._samples: list[float] = []
self.sse = 0
self.busy = 0
def add(self, ms: float) -> None:
with self._lock:
self._samples.append(ms)
def take(self) -> list[float]:
with self._lock:
out, self._samples = self._samples, []
return out
WINDOW = LagWindow()
def _sample_pools(hub) -> None:
try:
import anyio.to_thread
lim = anyio.to_thread.current_default_thread_limiter()
metrics.THREADS_BUSY.set(lim.borrowed_tokens)
metrics.THREADS_SIZE.set(lim.total_tokens)
WINDOW.busy = max(WINDOW.busy, int(lim.borrowed_tokens))
except Exception:
pass
if hub is not None:
n = hub.subscriber_count()
metrics.SSE_SUBSCRIBERS.set(n)
WINDOW.sse = max(WINDOW.sse, n)
async def watch(hub=None) -> None:
"""Run forever on the server's loop (started from the lifespan)."""
loop = asyncio.get_running_loop()
while True:
t0 = loop.time()
await asyncio.sleep(TICK)
late = max(0.0, loop.time() - t0 - TICK)
metrics.LOOP_LAG.observe(late)
WINDOW.add(late * 1000)
_sample_pools(hub)
def start(hub=None) -> asyncio.Task:
return asyncio.get_running_loop().create_task(watch(hub), name="telemetry-loop-lag")