feat: add PostgreSQL fallback for sessions and graceful degradation on Redis failure
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-10-22 16:49:19 +03:00
parent cca293dcb1
commit 566b02d850
9 changed files with 479 additions and 128 deletions
+35 -24
View File
@@ -1,37 +1,22 @@
import uuid
from fastapi import FastAPI, Request, HTTPException
import logging
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from app.routers import auth, chats
from app.redis_client import get_redis
logger = logging.getLogger(__name__)
app = FastAPI()
app.include_router(auth.router)
app.include_router(chats.router)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
# Генерируем или берем request_id один раз и сохраняем в state запроса
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
# Fallback для совершенно необработанных исключений
return JSONResponse(
status_code=500,
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
headers={"X-Request-Id": request_id}
)
# Гарантируем наличие заголовка в успешном ответе
response.headers["X-Request-Id"] = request.state.request_id
return response
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
# Берем тот же request_id, что был создан в middleware
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"}
@@ -49,7 +34,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
# Берем тот же request_id, что был создан в middleware
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
detail = exc.detail if isinstance(exc.detail, dict) else {"code": "internal_error", "message": str(exc.detail)}
@@ -70,10 +54,37 @@ async def http_exception_handler(request: Request, exc: HTTPException):
headers=headers
)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
request.state.request_id = request_id
try:
response = await call_next(request)
except Exception:
return JSONResponse(
status_code=500,
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
headers={"X-Request-Id": request_id}
)
response.headers["X-Request-Id"] = request.state.request_id
return response
@app.get("/health/live")
async def liveness():
return {"status": "ok"}
@app.get("/health/ready")
async def readiness():
async def readiness(redis_client = Depends(get_redis)):
"""
Контракт строго требует {"status": "ok"}.
Если Redis недоступен, мы логируем это, но возвращаем "ok",
так как приложение работает (используется fallback в PostgreSQL).
"""
try:
await redis_client.ping()
except Exception as e:
logger.warning(f"Redis health check failed, but PostgreSQL fallback is active: {e}")
return {"status": "ok"}