ЛР 3 — БПИ2302 — Щербацевич — на 5
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from app.db import is_dependency_error
|
||||
from app.errors import error_response
|
||||
|
||||
logger = logging.getLogger("app.access")
|
||||
|
||||
|
||||
def _instance_id(request: Request) -> str:
|
||||
settings = getattr(request.app.state, "settings", None)
|
||||
if settings is not None:
|
||||
return settings.instance_id
|
||||
return getattr(request.app.state, "instance_id", "starting")
|
||||
|
||||
|
||||
async def request_context(request: Request, call_next):
|
||||
request_id = uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.perf_counter()
|
||||
status = 500
|
||||
try:
|
||||
accepting = getattr(request.app.state, "accepting", True)
|
||||
if not accepting and request.url.path != "/health/live":
|
||||
response = error_response(503, "unavailable", "Сервер останавливается", request_id)
|
||||
else:
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception as exc:
|
||||
if is_dependency_error(exc):
|
||||
logger.warning("dependency unavailable type=%s", type(exc).__name__)
|
||||
response = error_response(503, "unavailable", "Сервис временно недоступен", request_id)
|
||||
else:
|
||||
logger.error("internal error request_id=%s type=%s", request_id, type(exc).__name__)
|
||||
response = error_response(500, "internal_error", "Внутренняя ошибка", request_id)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = _instance_id(request)
|
||||
status = response.status_code
|
||||
return response
|
||||
finally:
|
||||
elapsed_ms = int((time.perf_counter() - started) * 1000)
|
||||
logger.info(
|
||||
"request method=%s path=%s status=%s request_id=%s duration_ms=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
status,
|
||||
request_id,
|
||||
elapsed_ms,
|
||||
)
|
||||
Reference in New Issue
Block a user