Подключить OpenTelemetry, Collector и Grafana для оценки 5.

API и worker отдают метрики, логи и трассы. Правила SLO записаны, прогон инцидентов ещё впереди.
This commit is contained in:
2026-11-17 15:23:33 +03:00
parent 14ab803529
commit baee48072c
26 changed files with 1279 additions and 113 deletions
+51 -21
View File
@@ -1,11 +1,13 @@
import logging
import time
import uuid
from contextlib import nullcontext
from starlette.datastructures import MutableHeaders
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from app import telemetry
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
@@ -30,34 +32,62 @@ class RequestContextMiddleware:
scope["state"] = raw_state
raw_state["request_id"] = request_id
path = scope.get("path", "")
method = scope.get("method", "")
started = time.perf_counter()
status_code = 500
record = telemetry.observe_http(path)
route = telemetry.route_template(path)
async def send_wrapper(message: Message) -> None:
nonlocal status_code
if message["type"] == "http.response.start":
status_code = int(message["status"])
response_headers = MutableHeaders(scope=message)
response_headers["X-Request-Id"] = request_id
response_headers["X-Instance-Id"] = INSTANCE_ID
await send(message)
app = scope.get("app")
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
if shutting_down and path not in ("/health/live", "/health/ready"):
response: Response = error_response(503, "service is shutting down", request_id)
await response(scope, receive, send_wrapper)
return
try:
await self.app(scope, receive, send_wrapper)
except AppError as exc:
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
except Exception:
logger.exception("request_id=%s unhandled error path=%s", request_id, path)
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
return
elapsed_ms = (time.perf_counter() - started) * 1000
logger.info(
"request_id=%s method=%s path=%s duration_ms=%.2f",
request_id,
scope.get("method", ""),
path,
elapsed_ms,
parent = telemetry.remote_context(headers.get("traceparent"), headers.get("tracestate"))
span_cm = (
telemetry.span(
"%s %s" % (method, route),
context=parent,
kind="server",
attributes={
"http.request.method": method,
"http.route": route,
"http.request_id": request_id,
},
)
if record
else nullcontext(None)
)
with span_cm as current:
app = scope.get("app")
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
try:
if shutting_down and path not in ("/health/live", "/health/ready"):
response: Response = error_response(503, "service is shutting down", request_id)
await response(scope, receive, send_wrapper)
else:
await self.app(scope, receive, send_wrapper)
except AppError as exc:
status_code = exc.status
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
except Exception:
status_code = 500
logger.exception("request failed request_id=%s route=%s", request_id, route)
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
finally:
if record:
telemetry.finish_http_span(current, status_code)
telemetry.record_http(method, route, status_code, time.perf_counter() - started)
if record:
logger.info(
"request completed request_id=%s method=%s route=%s status=%s duration_ms=%.2f",
request_id,
method,
route,
status_code,
(time.perf_counter() - started) * 1000,
)