Перенесла полный код из предыдущей лабораторной работы

This commit is contained in:
vasyukova
2026-10-24 19:01:13 +03:00
parent 470d9d6f1e
commit 84908b7d7c
57 changed files with 6946 additions and 8 deletions
+192
View File
@@ -0,0 +1,192 @@
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 .api import attachments, auth, chats, health, messages, users
from .storage.db import init_pool, close_pool
# --- Логирование: структурированный stdout, без содержимого сообщений ---
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
)
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 с таймаутами
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 — lab5",
version="1.5.0",
lifespan=lifespan,
swagger_ui_parameters={"persistAuthorization": True},
)
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
@app.middleware("http")
async def observability_middleware(request: Request, call_next):
"""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)
path = request.url.path
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,
duration_ms, request_id, INSTANCE_ID,
)
return response
# Словарь HTTP-кодов → кодов ошибок из контракта
_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:
"""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:
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(
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):
"""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)
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 "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):
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn."""
logger.info("event=sigterm_received signal=%s", signum)
server.should_exit = True
signal.signal(signal.SIGTERM, _handle_sigterm)
server.run()