71 lines
3.0 KiB
Python
71 lines
3.0 KiB
Python
import os
|
|
import uuid
|
|
import logging
|
|
import traceback
|
|
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)
|
|
|
|
# Уникальный ID для этой реплики (генерируется при старте или берется из env)
|
|
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8])
|
|
|
|
@app.middleware("http")
|
|
async def add_instance_and_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 as e:
|
|
# <--- ДОБАВИТЬ ЭТО: Печатаем настоящую ошибку в логи
|
|
logger.error(f"Unhandled exception: {e}")
|
|
traceback.print_exc()
|
|
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
|
|
)
|
|
|
|
response.headers["X-Request-Id"] = request.state.request_id
|
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
return response
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
request_id = getattr(request.state, "request_id", str(uuid.uuid4()))
|
|
first_error = exc.errors()[0] if exc.errors() else {"msg": "Invalid request"}
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content={"error": {"code": "invalid_request", "message": first_error.get("msg", "Invalid request"), "request_id": request_id}},
|
|
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
|
|
)
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request: Request, exc: HTTPException):
|
|
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)}
|
|
clean_error = {"code": detail.get("code", "internal_error"), "message": detail.get("message", "Unknown error"), "request_id": request_id}
|
|
headers = {"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
|
|
if exc.headers: headers.update(exc.headers)
|
|
return JSONResponse(status_code=exc.status_code, content={"error": clean_error}, headers=headers)
|
|
|
|
@app.get("/health/live")
|
|
async def liveness():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/health/ready")
|
|
async def readiness(redis_client = Depends(get_redis)):
|
|
try:
|
|
await redis_client.ping()
|
|
except Exception as e:
|
|
logger.warning(f"Redis health check failed, PostgreSQL fallback is active: {e}")
|
|
return {"status": "ok"} |