Files
ai-agent/backend/telemetry/middleware.py
gabrielvidalandClaude Opus 5.5 b42063f3a1 refactor(deploy): drop the core deploy banner — the blue-green-deploy plugin's app.banner replaces it
- delete backend/deploy_status.py (DeployWatcher's 1 s file poll), GET
  /api/deploy-status, the DeployStep/DeployStatus schemas, the authz/usage
  entries and guests._deploying (guest-job delivery now waits on
  banner.is_maintenance alone)
- _attach_conversation moves to plugins/routes.py (only /api/app-banner uses
  it); its test becomes test_banner_conversation.py
- delete DeployBanner.tsx, fetchDeployStatus/useDeployStatus, the SSE
  `deploy` handler and the French strings only it used; the mock seeds its
  mid-flight deploy as an app.banner instead
- useAppBanner polls while a banner shows (6 s done/failed, 1 min running),
  so a provider's expired snapshot goes away without a webhook

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:54:54 +01:00

224 lines
7.9 KiB
Python

"""Time every HTTP request — a pure ASGI middleware, outside the gate.
Installed *after* ``core.auth.install`` so it wraps the gate: it sees the
request before anything else runs and reads, once the app is done, what the
others left in the shared ``scope`` — FastAPI's matched route (its path
template) and the gate's ``caller`` (``scope["state"]``).
Three things come out of one request:
* a :data:`metrics.HTTP` observation (or, for a stream — an SSE response, a
worker long-poll — the :data:`metrics.STREAMS` gauge while it is open);
* the in-memory minute rollup (:class:`Rollup`) the Hub card's history is
flushed from (``store.TelemetryStore.flush``);
* for a person's ``/api`` call, a count in the day's API usage — what the
Usage dashboard reads as server-side feature use. Never a body, a query
string or an id: the route template is all that is kept."""
from __future__ import annotations
import bisect
import re
import threading
import time
from . import metrics
# Requests that are long by design: their duration says nothing about speed.
LONG_POLLS = frozenset({"/worker-link/poll"})
# /api routes that are plumbing, not a feature someone used.
USAGE_SKIP = frozenset({
"/api/events", "/api/health", "/api/metrics", "/api/telemetry", "/api/me",
"/api/ui-state/{key}", "/api/app-banner",
})
_MOBILE = re.compile(r"Mobi|Android|iPhone|iPod", re.I)
_TABLET = re.compile(r"iPad|Tablet", re.I)
# Milliseconds; a request's latency lands in the first edge it fits under.
EDGES_MS = (5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000)
def ua_device(ua: str) -> str:
"""``phone`` | ``tablet`` | ``desktop`` for a browser, ``script`` for the
rest (the CLI, the mail trigger, Home Assistant, curl)."""
if not ua.startswith("Mozilla/"):
return "script"
if _TABLET.search(ua):
return "tablet"
if _MOBILE.search(ua):
return "phone"
return "desktop"
def caller_label(caller) -> str:
if caller is None:
return "anon"
if getattr(caller, "via_worker", None):
return "worker"
if getattr(caller, "scope", None) == "metrics":
return "metrics"
return "owner" if caller.is_owner else "guest"
def _route(scope: dict, path: str) -> str:
route = scope.get("route")
tpl = getattr(route, "path", None)
if tpl:
return tpl
if path.startswith("/api/"):
return "unmatched"
return "static"
class Hist:
"""A fixed-edge latency histogram: count, errors, sum, max, buckets."""
__slots__ = ("n", "err", "sum", "max", "b")
def __init__(self) -> None:
self.n = 0
self.err = 0
self.sum = 0.0
self.max = 0.0
self.b = [0] * (len(EDGES_MS) + 1)
def add(self, ms: float, err: bool) -> None:
self.n += 1
self.err += err
self.sum += ms
if ms > self.max:
self.max = ms
self.b[bisect.bisect_left(EDGES_MS, ms)] += 1
def merge(self, o: "Hist") -> None:
self.n += o.n
self.err += o.err
self.sum += o.sum
self.max = max(self.max, o.max)
for i, v in enumerate(o.b):
self.b[i] += v
def quantile(self, q: float) -> float | None:
"""Interpolated within its bucket; the top bucket answers its max."""
if not self.n:
return None
rank = q * self.n
seen = 0
lo = 0.0
for i, c in enumerate(self.b):
if c and seen + c >= rank:
hi = EDGES_MS[i] if i < len(EDGES_MS) else self.max
hi = min(hi, self.max) if self.max else hi
return round(lo + (hi - lo) * (rank - seen) / c, 1)
seen += c
lo = EDGES_MS[i] if i < len(EDGES_MS) else lo
return round(self.max, 1)
class Rollup:
"""What the middleware saw since the last flush: per minute the whole
API's latency, per hour each route's, and the day's API use per person.
Swapped out whole by :meth:`take` — the flush never holds the lock
while it writes."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._reset()
def _reset(self) -> None:
self.minutes: dict[int, Hist] = {}
self.hours: dict[tuple[int, str], Hist] = {}
self.usage: dict[tuple[str, str, str, str], int] = {}
def add(self, t: float, key: str, ms: float, err: bool, usage: tuple | None) -> None:
minute = int(t // 60 * 60)
hour = int(t // 3600 * 3600)
with self._lock:
if key.split(" ", 1)[-1].startswith("/api/"):
self.minutes.setdefault(minute, Hist()).add(ms, err)
self.hours.setdefault((hour, key), Hist()).add(ms, err)
if usage:
self.usage[usage] = self.usage.get(usage, 0) + 1
def take(self) -> tuple[dict, dict, dict]:
with self._lock:
out = (self.minutes, self.hours, self.usage)
self._reset()
return out
ROLLUP = Rollup()
class RequestMetrics:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
t0 = time.perf_counter()
status = {"code": 500, "stream": False}
path = scope.get("path") or ""
stream_route = [None]
async def timed_send(message):
if message["type"] == "http.response.start":
status["code"] = message.get("status", 500)
for k, v in message.get("headers") or ():
if k.lower() == b"content-type" and v.startswith(b"text/event-stream"):
status["stream"] = True
stream_route[0] = _route(scope, path)
metrics.STREAMS.labels(stream_route[0]).inc()
break
await send(message)
long_poll = path in LONG_POLLS
if long_poll:
metrics.STREAMS.labels(path).inc()
try:
await self.app(scope, receive, timed_send)
finally:
if long_poll:
metrics.STREAMS.labels(path).dec()
elif stream_route[0] is not None:
metrics.STREAMS.labels(stream_route[0]).dec()
else:
self._observe(scope, path, status["code"], time.perf_counter() - t0)
@staticmethod
def _observe(scope: dict, path: str, code: int, secs: float) -> None:
try:
route = _route(scope, path)
method = scope.get("method", "GET")
state = scope.get("state") or {}
caller = state.get("caller") if isinstance(state, dict) else None
if path.startswith(("/_tunnel/", "/worker-link/")):
who = "worker"
else:
who = caller_label(caller)
metrics.HTTP.labels(route, method, who, f"{code // 100}xx").observe(secs)
usage = None
# A person's use: not a credential acting for them (the screenshot
# bot, the desk phone, a worker's MCP) — their run's CLI is theirs.
scoped = getattr(caller, "scope", None) not in (None, "cli")
if who in ("owner", "guest") and not scoped and route.startswith("/api/") \
and route not in USAGE_SKIP and code < 400:
ua = ""
for k, v in scope.get("headers") or ():
if k == b"user-agent":
ua = v.decode("latin-1")
break
usage = (time.strftime("%Y-%m-%d", time.localtime()), caller.id,
f"{method} {route}", ua_device(ua))
if route != "static":
ROLLUP.add(time.time(), f"{method} {route}", secs * 1000, code >= 500, usage)
except Exception:
pass # telemetry never breaks a request
def install(app) -> None:
"""Add the middleware outermost (call after ``core.auth.install``)."""
app.add_middleware(RequestMetrics)