feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -151,6 +151,7 @@ from k1link.web.e47_semantic_slam_api import build_e47_semantic_slam_router
|
||||
from k1link.web.environment_api import build_environment_router
|
||||
from k1link.web.frontend_assets import ControlStationStaticFiles, frontend_build_id
|
||||
from k1link.web.response_compression import ResponseCompressionMiddleware
|
||||
from k1link.web.runtime_http_timing import RuntimeHttpTimingMiddleware
|
||||
from k1link.web.l3_pointpillars_visual_api import (
|
||||
build_l3_pointpillars_visual_router,
|
||||
)
|
||||
@@ -1008,6 +1009,8 @@ app = FastAPI(
|
||||
)
|
||||
app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compresslevel=5)
|
||||
|
||||
app.add_middleware(RuntimeHttpTimingMiddleware)
|
||||
|
||||
|
||||
app.include_router(fleet_router)
|
||||
app.include_router(equipment_router)
|
||||
|
||||
@@ -62,6 +62,11 @@ class RenameRequest(BaseModel):
|
||||
|
||||
router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"])
|
||||
|
||||
from .fleet_router_api import register as register_router_equipment
|
||||
register_router_equipment(router, local_operator)
|
||||
from .fleet_network_api import register as register_network_profiles
|
||||
register_network_profiles(router, local_operator)
|
||||
|
||||
|
||||
class BoardLayoutChange(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
@@ -154,16 +159,19 @@ def observation_configuration_write(vehicle_id: str, body: ObservationConfigurat
|
||||
@router.get("/{vehicle_id}/monitor")
|
||||
def board_monitor(vehicle_id: str, response: Response,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)],
|
||||
metric: str = "cpu.usage", window: int = 900, end: float | None = None):
|
||||
metric: str | None = None, window: int | None = None,
|
||||
end: float | None = None):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
try:
|
||||
if metric is not None or window is not None or end is not None:
|
||||
raise ValueError("Historical operator queries are unavailable")
|
||||
with fleet.lock:
|
||||
node_id = fleet.find(vehicle_id)["node_id"]
|
||||
return fleet.monitor.query(node_id, metric, window, end)
|
||||
return fleet.monitor.query(node_id)
|
||||
except PairingError as error:
|
||||
raise HTTPException(404, str(error)) from None
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Выберите доступный период и показатель.") from None
|
||||
raise HTTPException(400, "Доступны только текущие показатели БК.") from None
|
||||
|
||||
|
||||
@router.get("")
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Operator-only network profile actions, separate from compute contours."""
|
||||
from typing import Annotated, Literal
|
||||
from fastapi import Depends, HTTPException, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from k1link.fleet.registry import FleetRegistry
|
||||
|
||||
class ImportProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
document: str = Field(min_length=1, max_length=16384)
|
||||
name: str = Field(default="", max_length=80)
|
||||
network_interface: str | None = Field(default=None, max_length=20)
|
||||
|
||||
class SelectProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
provider: Literal["tailscale", "wireguard"]
|
||||
profile_id: str | None = Field(default=None, max_length=80)
|
||||
expected_revision: int = Field(ge=0, lt=2**53, strict=True)
|
||||
|
||||
|
||||
def register(router, local_operator):
|
||||
@router.get("/network-profiles")
|
||||
def listing(fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
return {"items": fleet.network_profiles.listing()}
|
||||
|
||||
@router.post("/network-profiles/import")
|
||||
def import_profile(body: ImportProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
return fleet.network_profiles.import_file(body.document, body.name, body.network_interface)
|
||||
except (ValueError, OSError) as error:
|
||||
raise HTTPException(409, str(error) if isinstance(error, ValueError) else "Не удалось подготовить подключение.") from None
|
||||
|
||||
@router.get("/{vehicle_id}/network-profile")
|
||||
def view(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
with fleet.lock:
|
||||
try:
|
||||
node_id = fleet.find(vehicle_id)["node_id"]
|
||||
except ValueError as error:
|
||||
raise HTTPException(404, str(error)) from None
|
||||
return fleet.network_profiles.view(node_id)
|
||||
|
||||
@router.put("/{vehicle_id}/network-profile")
|
||||
def apply(vehicle_id: str, body: SelectProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
return fleet.network_profiles.start(vehicle_id, body.provider, body.profile_id, body.expected_revision)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
@@ -6,20 +6,17 @@ from k1link.fleet.trust import PairingError
|
||||
from .fleet_api import local_operator
|
||||
|
||||
router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"])
|
||||
|
||||
def node(fleet, vehicle):
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle)
|
||||
if row["enrollment"] != "paired":
|
||||
raise ValueError("Борт не привязан.")
|
||||
return row["node_id"]
|
||||
from .rover_socket import register
|
||||
register(router)
|
||||
from .rover_diagnostics_api import register as register_diagnostics
|
||||
register_diagnostics(router)
|
||||
|
||||
@router.get("/{vehicle_id}/rover")
|
||||
def rover_state(vehicle_id: str, response: Response,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
try:
|
||||
return fleet.rover_control.view(node(fleet, vehicle_id))
|
||||
return fleet.rover_channel.operator(vehicle_id, "view")
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -27,9 +24,7 @@ def rover_state(vehicle_id: str, response: Response,
|
||||
def rover_arm(vehicle_id: str, body: dict,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
# Admission and node resolution must not race a computer replacement.
|
||||
with fleet.lock:
|
||||
return fleet.rover_control.arm(node(fleet, vehicle_id), body)
|
||||
return fleet.rover_channel.operator(vehicle_id, "arm", body)
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -37,7 +32,6 @@ def rover_arm(vehicle_id: str, body: dict,
|
||||
def rover_command(vehicle_id: str, body: dict,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
with fleet.lock:
|
||||
return fleet.rover_control.command(node(fleet, vehicle_id), body)
|
||||
return fleet.rover_channel.operator(vehicle_id, "command", body)
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Local operator DEV controls and full onboard-file streaming."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, HTTPException, Query
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
|
||||
from ..fleet.trust import PairingError
|
||||
from .fleet_api import local_operator
|
||||
|
||||
|
||||
def register(router):
|
||||
def recorder(fleet, vehicle):
|
||||
try:
|
||||
return fleet.rover_channel.operator(vehicle, "diagnostics")
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics")
|
||||
def view(vehicle_id: str, after: int = Query(0, ge=0), fleet=Depends(local_operator)):
|
||||
return recorder(fleet, vehicle_id).view(after)
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/runtime")
|
||||
def runtime(vehicle_id: str, fleet=Depends(local_operator)):
|
||||
from .rover_runtime_diagnostics import snapshot
|
||||
|
||||
recorder(fleet, vehicle_id)
|
||||
result = snapshot()
|
||||
result["observation"] = fleet.rover_channel.operator(vehicle_id, "observation_evidence")
|
||||
return Response(json.dumps(result), media_type="application/json",
|
||||
headers={"Cache-Control": "no-store"})
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics")
|
||||
def configure(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
if set(body)-{"enabled", "options", "local_options"} or type(body.get("enabled")) is not bool:
|
||||
raise HTTPException(400, "Invalid DEV mode")
|
||||
try:
|
||||
return recorder(fleet, vehicle_id).set_enabled(
|
||||
body["enabled"], body.get("options"), body.get("local_options"))
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics/events")
|
||||
def events(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
try:
|
||||
recorder(fleet, vehicle_id).browser(body)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(400, "Invalid diagnostic events") from None
|
||||
return {"accepted": True}
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics/local")
|
||||
def local_configure(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
if set(body)-{"enabled", "duration_s", "capture_id"} or type(body.get("enabled")) is not bool:
|
||||
raise HTTPException(400, "Invalid local diagnostic mode")
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
if body["enabled"]:
|
||||
capture.trace.local.start(duration=body.get("duration_s", 900), previous_id=body.get("capture_id"))
|
||||
capture.trace.local.add("local_capture_context", context=capture.context, board_capture_id=capture.trace.id)
|
||||
return capture.trace.local.snapshot(limit=0)
|
||||
return capture.trace.local.stop(body.get("capture_id"))
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/local")
|
||||
def local_view(vehicle_id: str, capture_id: str = Query(..., pattern=r"^[a-f0-9]{32}$"),
|
||||
after: int = Query(0, ge=0), limit: int = Query(200, ge=0, le=500), fleet=Depends(local_operator)):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
return capture.trace.local.page(capture_id, after, limit)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/local/export")
|
||||
def local_export(vehicle_id: str,
|
||||
capture_id: str = Query(..., pattern=r"^[a-f0-9]{32}$"),
|
||||
fleet=Depends(local_operator)):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
page = capture.trace.local.page(capture_id, limit=capture.trace.local.MAX_ROWS)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
rows = page.pop("frames")
|
||||
metadata = {"schema": "missioncore.operator-capture/v1", **page}
|
||||
text = "\n".join(json.dumps(row, ensure_ascii=False, allow_nan=False)
|
||||
for row in [metadata, *rows]) + "\n"
|
||||
return Response(text, media_type="application/x-ndjson", headers={
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Disposition": f'attachment; filename="rover-operator-{capture_id}.jsonl"',
|
||||
})
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics/local/events")
|
||||
def local_events(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
try:
|
||||
accepted = recorder(fleet, vehicle_id).browser(body, local=True)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(400, "Invalid local diagnostic events") from None
|
||||
return {"accepted": bool(accepted)}
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/export")
|
||||
async def export(
|
||||
vehicle_id: str,
|
||||
format: Literal["raw", "chunks"] = "raw",
|
||||
capture_id: str | None = Query(None, pattern=r"^[a-f0-9]{32}$"),
|
||||
offset: int = Query(0, ge=0),
|
||||
total_bytes: int | None = Query(None, ge=0),
|
||||
snapshot: str | None = Query(None, pattern=r"^[a-f0-9]{64}$"),
|
||||
fleet=Depends(local_operator),
|
||||
):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
if capture_id is not None and capture_id != capture.trace.id:
|
||||
raise HTTPException(409, "Запись изменилась. Повторите сохранение нужной сессии.")
|
||||
if offset and capture_id is None:
|
||||
raise HTTPException(400, "Missing capture identity")
|
||||
try:
|
||||
token = capture.export.start(
|
||||
capture.trace.id, offset=offset, total=total_bytes, snapshot=snapshot
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
try:
|
||||
first = await asyncio.to_thread(capture.export.take, token)
|
||||
if format == "chunks" and (not first.get("sha256") or not first.get("snapshot")):
|
||||
raise HTTPException(409, "Для продолжения выгрузки обновите бортовой модуль VESC.")
|
||||
except BaseException as error:
|
||||
capture.export.finish(token)
|
||||
if isinstance(error, TimeoutError):
|
||||
raise HTTPException(503, str(error)) from None
|
||||
raise
|
||||
filename = first.get("file", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", filename):
|
||||
filename = f"rover-{capture.trace.id}.jsonl"
|
||||
headers = {
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Disposition": f'attachment; filename="{filename}"',
|
||||
}
|
||||
if format == "raw":
|
||||
headers["Content-Length"] = str(first["total_bytes"] - offset)
|
||||
return StreamingResponse(
|
||||
capture.export.stream_async(first, framed=format == "chunks"),
|
||||
media_type="application/x-ndjson",
|
||||
headers=headers,
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Bounded read-only thread locations for local operator runtime diagnosis.
|
||||
|
||||
No frame locals, source lines, request bodies, keys or persistent profiler are
|
||||
exposed. A native sampler can correlate native_id with these Python locations.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import PurePath
|
||||
|
||||
from .runtime_http_timing import http_timings
|
||||
|
||||
|
||||
def snapshot() -> dict:
|
||||
started = time.monotonic()
|
||||
threads = {thread.ident: thread for thread in threading.enumerate()}
|
||||
frames = sys._current_frames()
|
||||
rows = []
|
||||
try:
|
||||
for ident, frame in sorted(frames.items())[:128]:
|
||||
thread = threads.get(ident)
|
||||
stack = []
|
||||
while frame is not None and len(stack) < 24:
|
||||
code = frame.f_code
|
||||
stack.append({"file": PurePath(code.co_filename).name[:128],
|
||||
"function": code.co_name[:128], "line": frame.f_lineno})
|
||||
frame = frame.f_back
|
||||
rows.append({"native_id": thread.native_id if thread else None,
|
||||
"name": thread.name[:128] if thread else "unregistered",
|
||||
"stack": stack, "truncated": frame is not None})
|
||||
finally:
|
||||
# Do not retain application frames (and their locals) beyond this call.
|
||||
frames.clear()
|
||||
del frame
|
||||
return {"schema": "missioncore.runtime-threads/v1", "pid": os.getpid(),
|
||||
"monotonic_ms": started * 1000, "duration_ms": (time.monotonic()-started)*1000,
|
||||
"thread_count": len(threads), "truncated": len(threads) > 128,
|
||||
"threads": rows, "http": http_timings.snapshot()}
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Independent local operator transport; the existing control authority is unchanged."""
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import secrets
|
||||
import time
|
||||
from contextlib import suppress
|
||||
|
||||
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
|
||||
|
||||
from k1link.fleet.trust import PairingError
|
||||
|
||||
from .fleet_api import local_operator
|
||||
|
||||
|
||||
def register(router):
|
||||
@router.websocket("/{vehicle_id}/rover-channel")
|
||||
async def channel(socket: WebSocket, vehicle_id: str):
|
||||
try:
|
||||
fleet = local_operator(socket)
|
||||
# WebSocket browser handshakes must have the exact local origin.
|
||||
if socket.headers.get("origin") != f"http://{socket.headers.get('host', '')}":
|
||||
raise HTTPException(403)
|
||||
fleet.rover_channel.operator(vehicle_id, "view")
|
||||
except (HTTPException, ValueError, PairingError):
|
||||
await socket.close(code=1008)
|
||||
return
|
||||
trace=fleet.rover_channel.operator(vehicle_id,"diagnostics").trace
|
||||
await socket.accept()
|
||||
socket_id = secrets.token_hex(8)
|
||||
trace.add("operator_socket_opened", socket_id=socket_id)
|
||||
fleet.rover_channel.operator(vehicle_id, "observation_evidence", "operator_socket_opened")
|
||||
owned = None
|
||||
sending = asyncio.Lock()
|
||||
|
||||
async def send(value):
|
||||
async with sending:
|
||||
await socket.send_json({**value, "socket_id": socket_id})
|
||||
|
||||
async def receive():
|
||||
nonlocal owned
|
||||
window, count = time.monotonic(), 0
|
||||
while True:
|
||||
raw = await socket.receive_text()
|
||||
now = time.monotonic()
|
||||
if now - window >= 1:
|
||||
window, count = now, 0
|
||||
count += 1
|
||||
if len(raw) > 4096 or count > 64:
|
||||
await socket.close(code=1008)
|
||||
return
|
||||
try:
|
||||
message = json.loads(raw)
|
||||
if (not isinstance(message, dict)
|
||||
or set(message) != {"id", "action", "body", "expires_ms"}
|
||||
or type(message["id"]) is not int
|
||||
or not 0 < message["id"] < 2**53
|
||||
or message["action"] not in ("arm", "command", "hold")
|
||||
or not isinstance(message["body"], dict)
|
||||
or type(message["expires_ms"]) not in (int, float)
|
||||
or not math.isfinite(message["expires_ms"])):
|
||||
raise ValueError
|
||||
except (ValueError, TypeError):
|
||||
await socket.close(code=1008)
|
||||
return
|
||||
# A delayed local/browser send cannot become fresh motion on
|
||||
# arrival. Clock samples are sent below; receipt never extends it.
|
||||
remaining = message["expires_ms"] - time.monotonic() * 1000
|
||||
trace.add("operator_socket_received", socket_id=socket_id, request_id=message["id"],
|
||||
action=message["action"], session_id=message["body"].get("session_id"),
|
||||
sequence=message["body"].get("sequence"), received_ms=now*1000,
|
||||
expires_ms=message["expires_ms"], remaining_ms=remaining, bytes=len(raw))
|
||||
if not 0 < remaining <= 400:
|
||||
trace.add("operator_socket_rejected",reason="expired",action=message["action"],remaining_ms=remaining,session_id=owned,socket_id=socket_id)
|
||||
await send({"type": "reply", "id": message["id"], "status": 408,
|
||||
"error": "Команда устарела до передачи на борт."})
|
||||
continue
|
||||
try:
|
||||
if message["action"] in ("command", "hold") and message["body"].get("session_id") != owned:
|
||||
raise ValueError("Управление не принадлежит этому окну.")
|
||||
dispatch_started = time.monotonic()
|
||||
result = fleet.rover_channel.operator(vehicle_id, message["action"], message["body"], expires_at=message["expires_ms"]/1000)
|
||||
if message["action"] == "arm":
|
||||
owned = result["session_id"]
|
||||
trace.add("operator_socket_applied", socket_id=socket_id, request_id=message["id"],
|
||||
session_id=owned, sequence=message["body"].get("sequence"),
|
||||
action=message["action"], dispatch_ms=(time.monotonic()-dispatch_started)*1000)
|
||||
# The ack carries a post-operation view. The browser must
|
||||
# not apply its cached pre-arm controlling=false snapshot
|
||||
# to the newly acknowledged session before the next push.
|
||||
await send({"type": "reply", "id": message["id"], "value": result,
|
||||
"state": fleet.rover_channel.operator(vehicle_id, "view"),
|
||||
"clock_ms": time.monotonic()*1000})
|
||||
except (ValueError, PairingError) as error:
|
||||
trace.add("operator_socket_rejected",reason=str(error)[:512],action=message["action"],session_id=owned,socket_id=socket_id)
|
||||
await send({"type": "reply", "id": message["id"], "status": 409, "error": str(error)})
|
||||
|
||||
reader = asyncio.create_task(receive())
|
||||
next_state = 0.
|
||||
try:
|
||||
while not reader.done():
|
||||
if owned:
|
||||
# Native process timer, independent of hidden browser JS.
|
||||
# Only an explicit hold can produce fresh neutral frames.
|
||||
fleet.rover_channel.operator(vehicle_id, "maintain_neutral", {"session_id": owned})
|
||||
if time.monotonic() < next_state:
|
||||
await asyncio.wait({reader}, timeout=.1)
|
||||
continue
|
||||
next_state = time.monotonic()+.2
|
||||
value = fleet.rover_channel.operator(vehicle_id, "view")
|
||||
await send({"type": "state", "value": value, "clock_ms": time.monotonic() * 1000})
|
||||
await asyncio.wait({reader}, timeout=.1)
|
||||
await reader
|
||||
except (WebSocketDisconnect, OSError, RuntimeError, ValueError, PairingError) as error:
|
||||
trace.add("operator_socket_closed",error_type=type(error).__name__,close_code=getattr(error,"code",None),session_id=owned,socket_id=socket_id)
|
||||
finally:
|
||||
with suppress(ValueError, PairingError):
|
||||
fleet.rover_channel.operator(vehicle_id, "observation_evidence", "operator_socket_closed")
|
||||
reader.cancel()
|
||||
with suppress(asyncio.CancelledError, WebSocketDisconnect, OSError, RuntimeError):
|
||||
await reader
|
||||
if owned:
|
||||
with suppress(ValueError, PairingError):
|
||||
fleet.rover_channel.operator(vehicle_id, "disconnect", {"session_id": owned})
|
||||
with suppress(WebSocketDisconnect, OSError, RuntimeError):
|
||||
await socket.close()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Bounded, expiring HTTP timing metadata; no bodies, query strings or client IDs."""
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
|
||||
class HttpTimingWindow:
|
||||
def __init__(self, clock=time.monotonic):
|
||||
self.clock = clock
|
||||
self.lock = threading.Lock()
|
||||
self.rows = deque(maxlen=256)
|
||||
|
||||
def add(self, row):
|
||||
with self.lock:
|
||||
self.rows.append(row)
|
||||
self._expire(self.clock() * 1000)
|
||||
|
||||
def _expire(self, now_ms):
|
||||
while self.rows and now_ms - self.rows[0]["ended_mono_ms"] >= 30_000:
|
||||
self.rows.popleft()
|
||||
|
||||
def snapshot(self):
|
||||
with self.lock:
|
||||
self._expire(self.clock() * 1000)
|
||||
return [dict(row) for row in self.rows]
|
||||
|
||||
|
||||
http_timings = HttpTimingWindow()
|
||||
|
||||
|
||||
class RuntimeHttpTimingMiddleware:
|
||||
def __init__(self, app: ASGIApp, window=http_timings):
|
||||
self.app, self.window = app, window
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
started = self.window.clock() * 1000
|
||||
status, size, first, complete = 500, 0, None, False
|
||||
|
||||
async def measured_send(message):
|
||||
nonlocal status, size, first, complete
|
||||
if message["type"] == "http.response.start":
|
||||
status = message["status"]
|
||||
first = self.window.clock() * 1000 - started
|
||||
elif message["type"] == "http.response.body":
|
||||
size += len(message.get("body", b""))
|
||||
await send(message)
|
||||
if message["type"] == "http.response.body" and not message.get("more_body", False):
|
||||
complete = True
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, measured_send)
|
||||
finally:
|
||||
ended = self.window.clock() * 1000
|
||||
# Only the registered route template is retained. The raw path can
|
||||
# contain filenames, tokens or other user data even without a query.
|
||||
route = getattr(scope.get("route"), "path", None)
|
||||
route = (route[:240] if isinstance(route, str) and route.startswith("/api/")
|
||||
else "<other>")
|
||||
method = scope.get("method")
|
||||
if method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}:
|
||||
method = "<other>"
|
||||
self.window.add({"route": route, "method": method, "status": status,
|
||||
"duration_ms": ended - started, "response_start_ms": first,
|
||||
"ended_mono_ms": ended, "bytes": size, "complete": complete})
|
||||
Reference in New Issue
Block a user