53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
|
|
from collections.abc import AsyncIterator
|
||
|
|
from contextlib import asynccontextmanager
|
||
|
|
|
||
|
|
from fastapi import FastAPI, Request
|
||
|
|
from fastapi.responses import JSONResponse
|
||
|
|
from slowapi.errors import RateLimitExceeded
|
||
|
|
from slowapi.middleware import SlowAPIMiddleware
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
from app.db import close_pool, get_pool
|
||
|
|
from app.health import router as health_router
|
||
|
|
from app.logging_setup import configure_logging
|
||
|
|
from app.rate_limit import limiter
|
||
|
|
from app.routers.auth import router as auth_router
|
||
|
|
from app.routers.push import router as push_router
|
||
|
|
from app.routers.views import router as views_router
|
||
|
|
|
||
|
|
|
||
|
|
@asynccontextmanager
|
||
|
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||
|
|
configure_logging()
|
||
|
|
await get_pool()
|
||
|
|
try:
|
||
|
|
yield
|
||
|
|
finally:
|
||
|
|
await close_pool()
|
||
|
|
|
||
|
|
|
||
|
|
def _rate_limit_handler(request: Request, exc: Exception) -> JSONResponse:
|
||
|
|
_ = request, exc
|
||
|
|
return JSONResponse(status_code=429, content={"detail": "rate limit exceeded"})
|
||
|
|
|
||
|
|
|
||
|
|
def create_app(role: str) -> FastAPI:
|
||
|
|
settings = get_settings()
|
||
|
|
app = FastAPI(
|
||
|
|
title=f"fleet-platform [{role}]",
|
||
|
|
version=settings.app_git_sha,
|
||
|
|
lifespan=lifespan,
|
||
|
|
)
|
||
|
|
app.state.limiter = limiter
|
||
|
|
app.add_exception_handler(RateLimitExceeded, _rate_limit_handler)
|
||
|
|
app.add_middleware(SlowAPIMiddleware)
|
||
|
|
|
||
|
|
app.include_router(health_router)
|
||
|
|
|
||
|
|
if role == "gateway":
|
||
|
|
app.include_router(auth_router)
|
||
|
|
app.include_router(push_router)
|
||
|
|
app.include_router(views_router)
|
||
|
|
|
||
|
|
return app
|