93 lines
3.2 KiB
Python
93 lines
3.2 KiB
Python
import os
|
|
import uuid
|
|
import logging
|
|
import traceback
|
|
import asyncio
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.exceptions import RequestValidationError
|
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
from app.routers import auth, chats, attachments
|
|
from app.database import AsyncSessionLocal
|
|
from app.broker import relay_outbox
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
# Запускаем фоновый relay при старте приложения
|
|
task = asyncio.create_task(run_relay())
|
|
yield
|
|
# Останавливаем при завершении
|
|
task.cancel()
|
|
|
|
async def run_relay():
|
|
while True:
|
|
try:
|
|
async with AsyncSessionLocal() as db:
|
|
await relay_outbox(db)
|
|
await asyncio.sleep(1) # Проверяем outbox каждую секунду
|
|
except Exception as e:
|
|
logger.error(f"Relay loop crashed: {e}")
|
|
await asyncio.sleep(5)
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
|
|
app.include_router(auth.router)
|
|
app.include_router(chats.router)
|
|
app.include_router(attachments.router)
|
|
|
|
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(StarletteHTTPException)
|
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
|
detail = exc.detail
|
|
if isinstance(detail, dict):
|
|
code = detail.get("code", "internal_error")
|
|
message = detail.get("message", str(detail))
|
|
else:
|
|
code = "internal_error"
|
|
message = str(detail)
|
|
|
|
return JSONResponse(
|
|
status_code=exc.status_code,
|
|
content={"error": {"code": code, "message": message, "request_id": request.state.request_id}},
|
|
headers=exc.headers
|
|
)
|
|
|
|
@app.exception_handler(RequestValidationError)
|
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
|
return JSONResponse(
|
|
status_code=400,
|
|
content={"error": {"code": "invalid_request", "message": "Validation error", "request_id": request.state.request_id}},
|
|
headers={"X-Request-Id": request.state.request_id, "X-Instance-Id": INSTANCE_ID}
|
|
)
|
|
|
|
@app.get("/health/live")
|
|
async def health_live():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/health/ready")
|
|
async def health_ready():
|
|
return {"status": "ok"} |