"""FastAPI application entrypoint. Central instance of the Insight Updater hub: - Dashboard REST API under /api (JWT auth) - Satellite agent API under /api/satellite (X-Api-Key auth) - /health liveness probe """ from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from app.api import api_router from app.core.config import get_settings from app.core.database import init_db from app.core.exceptions import AppError from app.core.logging import get_logger, setup_logging settings = get_settings() logger = get_logger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): # type: ignore[no-untyped-def] setup_logging() logger.info("app.starting", env=settings.app_env) await init_db() await _seed_default_admin() import asyncio from app.services.janitor import run_janitor janitor = asyncio.create_task(run_janitor(), name="job-janitor") yield janitor.cancel() logger.info("app.stopping") async def _seed_default_admin() -> None: """Create the initial admin user if no users exist (dev bootstrap). Password comes from ADMIN_INITIAL_PASSWORD env, default 'admin' (dev only). """ import os from sqlalchemy import func, select from app.core.database import async_session_factory from app.core.security import hash_password from app.models.user import User async with async_session_factory() as db: count = await db.scalar(select(func.count(User.id))) if count and count > 0: return password = os.environ.get("ADMIN_INITIAL_PASSWORD", "admin") db.add( User( username="admin", email=None, full_name="Administrator", password_hash=hash_password(password), is_admin=True, ) ) await db.commit() logger.info("app.default_admin_created", username="admin") app = FastAPI( title=settings.app_name, version="0.2.0", lifespan=lifespan, ) app.add_middleware( CORSMiddleware, allow_origins=settings.cors_origin_list, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.exception_handler(AppError) async def app_error_handler(request: Request, exc: AppError) -> JSONResponse: # noqa: ARG001 return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}) @app.get("/health") async def health() -> dict: return {"status": "ok", "env": settings.app_env, "version": "0.2.0"} app.include_router(api_router)