forked from mtusi2026/mtusi2026lab6
Создала общий модуль OTel для API и worker
This commit is contained in:
+53
-21
@@ -12,11 +12,13 @@ from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from .api import attachments, auth, chats, health, messages, users
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
# --- Логирование: структурный stdout, без содержимого сообщений ---
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
@@ -24,14 +26,10 @@ logging.basicConfig(
|
||||
)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
# X-Instance-Id: стабильный в пределах жизни процесса. Значение приходит
|
||||
# из env INSTANCE_ID (задаётся Dockerfile/Compose) либо генерируется один раз.
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами
|
||||
init_pool()
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
@@ -44,12 +42,37 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab5",
|
||||
version="1.5.0",
|
||||
title="MTUCI Messenger — lab6",
|
||||
version="1.6.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
# OTel инициализация и FastAPI auto-instrumentation.
|
||||
init_telemetry("messenger-api", "1.6.0")
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
|
||||
# --- Метрики HTTP из контракта observability.md ---
|
||||
_http_counter = meter("messenger").create_counter(
|
||||
"http_requests_total",
|
||||
description="HTTP requests count",
|
||||
unit="1",
|
||||
)
|
||||
_http_hist = meter("messenger").create_histogram(
|
||||
"http_request_duration_seconds",
|
||||
description="HTTP request duration",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
# Хелпер: убираем реальные UUID из маршрута → route template.
|
||||
import re as _re
|
||||
_ROUTE_UUID_RE = _re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
|
||||
|
||||
def _route_template(path: str) -> str:
|
||||
return _ROUTE_UUID_RE.sub("{id}", path)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
@@ -64,15 +87,31 @@ app.openapi = custom_openapi
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог."""
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог + метрики."""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
path = request.url.path
|
||||
route = _route_template(path)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
|
||||
# Только low-cardinality labels: method, route template, status class.
|
||||
_http_counter.add(
|
||||
1,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
_http_hist.record(
|
||||
duration_s,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
||||
request.method, path, response.status_code,
|
||||
@@ -81,7 +120,7 @@ async def observability_middleware(request: Request, call_next):
|
||||
return response
|
||||
|
||||
|
||||
# Словарь HTTP-кодов → кодов ошибок из контракта
|
||||
# --- Обработчики ошибок (без изменений с lab5) ---
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
@@ -96,22 +135,17 @@ _ERROR_CODES = {
|
||||
|
||||
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
"""Basic — только для POST /api/v1/auth/sessions; остальное — Bearer."""
|
||||
if path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def _error_response(
|
||||
status_code: int, message: str, request_id: str, path: str = ""
|
||||
) -> JSONResponse:
|
||||
def _error_response(status_code: int, message: str, request_id: str,
|
||||
path: str = "") -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
# Контракт: X-Request-Id и X-Instance-Id обязательны во ВСЕХ ответах,
|
||||
# включая 500, которые формируются в обход middleware (exception handlers
|
||||
# срабатывают ПОСЛЕ call_next). Проставляем их здесь явно.
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return JSONResponse(
|
||||
@@ -136,7 +170,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
@@ -179,12 +212,11 @@ if __name__ == "__main__":
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info"
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn."""
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
|
||||
Reference in New Issue
Block a user