Files
mtusi2026lab5/app/middleware.py
T
dawudukandCursor 9046d5206d Перенести рабочую базу lab4 в skeleton лабораторной 5.
Исходники, миграции, Dockerfile и стенд lab4 нужны как основа асинхронной обработки вложений.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-09 00:48:22 +03:00

64 lines
2.5 KiB
Python

import logging
import time
import uuid
from starlette.datastructures import MutableHeaders
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
class RequestContextMiddleware:
"""Pure ASGI middleware so upload handlers can read the body stream themselves."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
headers = {key.decode("latin1").lower(): value.decode("latin1") for key, value in scope.get("headers", [])}
request_id = headers.get("x-request-id") or str(uuid.uuid4())
raw_state = scope.get("state")
if not isinstance(raw_state, dict):
raw_state = {}
scope["state"] = raw_state
raw_state["request_id"] = request_id
path = scope.get("path", "")
started = time.perf_counter()
async def send_wrapper(message: Message) -> None:
if message["type"] == "http.response.start":
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,
)