82 lines
2.8 KiB
Python
82 lines
2.8 KiB
Python
import time
|
|
|
|
from opentelemetry import trace
|
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
|
|
|
from infrastructure.observability import telemetry
|
|
|
|
BUSINESS_PREFIX = "/api/v1"
|
|
|
|
KNOWN_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"})
|
|
|
|
|
|
def route_template(scope):
|
|
route = scope.get("route")
|
|
path = getattr(route, "path", None)
|
|
if path is None:
|
|
return "unmatched"
|
|
if scope["path"].startswith(BUSINESS_PREFIX + "/") and not path.startswith(
|
|
BUSINESS_PREFIX + "/"
|
|
):
|
|
return BUSINESS_PREFIX + path
|
|
return path
|
|
|
|
|
|
def normalize_method(method):
|
|
return method if method in KNOWN_METHODS else "OTHER"
|
|
|
|
|
|
class TelemetryMiddleware:
|
|
"""Только бизнес-HTTP: route template, полный ASGI response, без URL/headers/body."""
|
|
|
|
def __init__(self, app):
|
|
self.app = app
|
|
|
|
async def __call__(self, scope, receive, send):
|
|
if scope["type"] != "http" or not scope["path"].startswith(
|
|
BUSINESS_PREFIX + "/"
|
|
):
|
|
await self.app(scope, receive, send)
|
|
return
|
|
headers = {
|
|
key.decode("latin1"): value.decode("latin1")
|
|
for key, value in scope["headers"]
|
|
if key in {b"traceparent", b"tracestate"}
|
|
}
|
|
method = normalize_method(scope["method"])
|
|
started, status = time.perf_counter(), 500
|
|
with telemetry.span(
|
|
"HTTP",
|
|
{"http.request.method": method},
|
|
kind=SpanKind.SERVER,
|
|
context=telemetry.extract(headers),
|
|
root=True,
|
|
) as span:
|
|
|
|
async def send_wrapper(message):
|
|
nonlocal status
|
|
if message["type"] == "http.response.start":
|
|
status = message["status"]
|
|
span_context = trace.get_current_span().get_span_context()
|
|
if span_context.is_valid:
|
|
message.setdefault("headers", []).append(
|
|
(b"x-trace-id", f"{span_context.trace_id:032x}".encode())
|
|
)
|
|
await send(message)
|
|
|
|
try:
|
|
await self.app(scope, receive, send_wrapper)
|
|
finally:
|
|
route = route_template(scope)
|
|
span.update_name(f"{method} {route}")
|
|
span.set_attribute("http.route", route)
|
|
span.set_attribute("http.response.status_code", status)
|
|
request_id = scope.get("state", {}).get("request_id")
|
|
if request_id:
|
|
span.set_attribute("request_id", request_id)
|
|
if status >= 500:
|
|
span.set_status(Status(StatusCode.ERROR))
|
|
telemetry.record_http(
|
|
time.perf_counter() - started, method, route, status
|
|
)
|