79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, HTTPException, status
|
|
from sqlalchemy import text
|
|
|
|
from app.auth.router import router as auth_router
|
|
from app.chats.router import router as chats_router
|
|
from app.config.settings import settings
|
|
from app.database import models # noqa: F401
|
|
from app.database.base import Base
|
|
from app.database.session import engine
|
|
from app.media.router import router as media_router
|
|
from app.messages.router import router as messages_router
|
|
from app.notifications.router import router as notifications_router
|
|
from app.realtime.router import router as realtime_router
|
|
from app.search.router import router as search_router
|
|
from app.realtime.service import realtime_gateway
|
|
from app.users.router import router as users_router
|
|
from app.utils.redis_client import close_redis_client, get_redis_client
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(_app: FastAPI):
|
|
await realtime_gateway.start()
|
|
if settings.auto_create_tables:
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
yield
|
|
await realtime_gateway.stop()
|
|
await close_redis_client()
|
|
|
|
|
|
app = FastAPI(title=settings.app_name, debug=settings.debug, lifespan=lifespan)
|
|
|
|
|
|
@app.get("/health", tags=["health"])
|
|
async def health() -> dict[str, str]:
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/live", tags=["health"])
|
|
async def health_live() -> dict[str, str]:
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.get("/health/ready", tags=["health"])
|
|
async def health_ready() -> dict[str, str]:
|
|
db_ok = False
|
|
redis_ok = False
|
|
try:
|
|
async with engine.connect() as conn:
|
|
await conn.execute(text("SELECT 1"))
|
|
db_ok = True
|
|
except Exception:
|
|
db_ok = False
|
|
try:
|
|
redis = get_redis_client()
|
|
pong = await redis.ping()
|
|
redis_ok = bool(pong)
|
|
except Exception:
|
|
redis_ok = False
|
|
|
|
if not db_ok or not redis_ok:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
|
detail={"status": "not_ready", "db": db_ok, "redis": redis_ok},
|
|
)
|
|
return {"status": "ready", "db": "ok", "redis": "ok"}
|
|
|
|
|
|
app.include_router(auth_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(users_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(chats_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(messages_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(media_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(notifications_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(realtime_router, prefix=settings.api_v1_prefix)
|
|
app.include_router(search_router, prefix=settings.api_v1_prefix)
|