Перенесла файлы проекта из предыдущей лабораторной работы
This commit is contained in:
+269
@@ -0,0 +1,269 @@
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from opentelemetry import trace as _otel_trace
|
||||
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
|
||||
|
||||
|
||||
# Базовый логгер: реальный формат выставляет telemetry.install_log_format()
|
||||
# при вызове init_telemetry(). Здесь — минимальный fallback для импорта.
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool()
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
os.environ.get("SESSION_STORE", "postgres"),
|
||||
INSTANCE_ID,
|
||||
)
|
||||
yield
|
||||
close_pool()
|
||||
logger.info("event=shutdown_complete instance_id=%s", INSTANCE_ID)
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
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")
|
||||
|
||||
|
||||
# --- Метрики HTTP ---
|
||||
_http_counter = meter("messenger").create_counter(
|
||||
"http_requests_total",
|
||||
description="HTTP requests count",
|
||||
unit="1",
|
||||
)
|
||||
# Явные границы бакетов в СЕКУНДАХ, с разрешением в миллисекундном диапазоне
|
||||
# и вокруг порога SLO 2s (upload p95 alert). Дефолтные экспоненциальные
|
||||
# бакеты (0, 5, 10, 25, …) грубы: миллисекундные запросы попадали в один
|
||||
# широкий bucket, а histogram_quantile интерполировал ложные секунды.
|
||||
_HTTP_DURATION_BUCKETS = [
|
||||
0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.02, 0.03, 0.05,
|
||||
0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0,
|
||||
]
|
||||
_http_hist = meter("messenger").create_histogram(
|
||||
"http_request_duration_seconds",
|
||||
description="HTTP request duration",
|
||||
unit="s",
|
||||
explicit_bucket_boundaries_advisory=_HTTP_DURATION_BUCKETS,
|
||||
)
|
||||
|
||||
# Фильтр: убираем реальные 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:
|
||||
return app.openapi_schema
|
||||
schema = get_openapi(title=app.title, version=app.version, routes=app.routes)
|
||||
app.openapi_schema = schema
|
||||
return schema
|
||||
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
# Отдельный tracer для событийного span в middleware. Он создаётся как child
|
||||
# SERVER span, который создаёт OTel FastAPI instrumentation ниже.
|
||||
# ВАЖНО: FastAPIInstrumentor.instrument_app(app) вызывается ПОСЛЕ объявления
|
||||
# middleware, поэтому OTel ASGI middleware оказывается внешним: он извлекает
|
||||
# W3C traceparent из входящих headers, продолжает внешний trace и создаёт
|
||||
# SERVER span. Наш middleware выполняется внутри него, создаёт http.request
|
||||
# как INTERNAL child, и логи/метрики берут корректный trace_id.
|
||||
_http_tracer = tracer("app.http")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурированный лог + метрики.
|
||||
|
||||
Лог event=http пишется ВНУТРИ активного span (`http.request`), он
|
||||
child SERVER span от OTel auto-instrumentation, поэтому trace_id
|
||||
корректно связывает лог с внешним trace.
|
||||
"""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
route = _route_template(request.url.path)
|
||||
|
||||
# http.request — INTERNAL child текущего (SERVER) span, созданного OTel
|
||||
# auto-instrumentation. Parent берётся из активного контекста: входящий
|
||||
# traceparent уже извлечён ASGI middleware.
|
||||
with _http_tracer.start_as_current_span(
|
||||
"http.request",
|
||||
attributes={
|
||||
"http.method": request.method,
|
||||
"http.route": route,
|
||||
},
|
||||
) as span:
|
||||
response = await call_next(request)
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
_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},
|
||||
)
|
||||
span.set_attribute("http.status_class", status_class)
|
||||
span.set_attribute("http.status_code", response.status_code)
|
||||
|
||||
# Лог ВНУТРИ span → record.trace_id валидный, Loki получает
|
||||
# корреляцию с Tempo.
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s "
|
||||
"request_id=%s instance_id=%s",
|
||||
request.method, request.url.path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
# FastAPI auto-instrumentation ДОЛЖНА быть установлена ПОСЛЕ пользовательского
|
||||
# @app.middleware("http"), чтобы оказаться внешним middleware и создать SERVER
|
||||
# span с корректным parent из входного traceparent. Этот вызов также
|
||||
# инструментирует httpx/requests client-вызовы внутри приложения.
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
|
||||
# --- Обработчики ошибок (без изменений) ---
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
503: "unavailable",
|
||||
500: "internal_error",
|
||||
}
|
||||
|
||||
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
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:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
message = exc.detail if isinstance(exc.detail, str) else "Ошибка"
|
||||
return _error_response(exc.status_code, message, request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
return _error_response(400, "Неверный запрос", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
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)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(RuntimeError)
|
||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
text = str(exc)
|
||||
if "db_unavailable" in text:
|
||||
logger.error("event=db_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
if "redis_unavailable" in text:
|
||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
if "s3_unavailable" in text:
|
||||
logger.error("event=s3_unavailable request_id=%s", request_id)
|
||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||
logger.error("event=runtime_error type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unhandled_exception_handler(request: Request, exc: Exception):
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=unhandled_exception type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
return _error_response(500, "Внутренняя ошибка", request_id, request.url.path)
|
||||
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
app.include_router(attachments.router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = uvicorn.Config(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
server.run()
|
||||
Reference in New Issue
Block a user