Backend API: auth, projects/images/annotations, R2 presign, tracing, thumbnails, pagination, tests, docs
This commit is contained in:
parent
5c5deed2f5
commit
f8ed08b854
49 changed files with 2626 additions and 0 deletions
52
shared/traffic.py
Normal file
52
shared/traffic.py
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
"""Phase-1 traffic layer: in-process per-route counters + slow-request log.
|
||||
|
||||
Future (Phase-2, no API change): export these counters to Prometheus/Grafana and
|
||||
add R2 Class A/B accounting per project. Routers stay untouched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
|
||||
from shared.logger import get_logger
|
||||
from src.core.config import get_settings
|
||||
|
||||
log = get_logger("danable.traffic")
|
||||
|
||||
_counters: dict[str, dict[str, float]] = defaultdict(lambda: {"count": 0, "errors": 0, "total_ms": 0.0})
|
||||
_started_at = time.time()
|
||||
|
||||
|
||||
def get_snapshot() -> dict:
|
||||
routes = {
|
||||
route: {"count": int(v["count"]), "errors": int(v["errors"]),
|
||||
"avg_ms": round(v["total_ms"] / v["count"], 2) if v["count"] else 0.0}
|
||||
for route, v in _counters.items()
|
||||
}
|
||||
return {"uptime_s": round(time.time() - _started_at, 1), "routes": routes}
|
||||
|
||||
|
||||
class TrafficMiddleware(BaseHTTPMiddleware):
|
||||
"""Count every request; count 5xx as errors. Zero deps, safe to keep always on."""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
route = f"{request.method} {request.url.path}"
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
response = await call_next(request)
|
||||
if response.status_code >= 500:
|
||||
_counters[route]["errors"] += 1
|
||||
return response
|
||||
except Exception:
|
||||
_counters[route]["errors"] += 1
|
||||
raise
|
||||
finally:
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
_counters[route]["count"] += 1
|
||||
_counters[route]["total_ms"] += elapsed_ms
|
||||
slow_ms = get_settings().traffic.get("log_slow_ms", 800)
|
||||
if elapsed_ms > slow_ms:
|
||||
log.warning("slow request route=%s ms=%.0f", route, elapsed_ms)
|
||||
Loading…
Add table
Add a link
Reference in a new issue