from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from sqlalchemy import text from app.api.v1.router import api_router from app.core.config import get_settings from app.db.session import Base, SessionLocal, engine from app.seed.demo import seed_demo_data def ensure_runtime_indexes() -> None: index_statements = [ "CREATE INDEX IF NOT EXISTS ix_ip_addresses_address ON ip_addresses (address)", "CREATE INDEX IF NOT EXISTS ix_traffic_flows_node_updated ON traffic_flows (node_id, updated_at)", "CREATE INDEX IF NOT EXISTS ix_traffic_flows_source_updated ON traffic_flows (source_ip, updated_at)", "CREATE INDEX IF NOT EXISTS ix_traffic_flows_destination_updated ON traffic_flows (destination_ip, updated_at)", "CREATE INDEX IF NOT EXISTS ix_traffic_flows_destination_port_updated ON traffic_flows (destination_port, updated_at)", "CREATE INDEX IF NOT EXISTS ix_traffic_flows_state_updated ON traffic_flows (state, updated_at)", ] with engine.begin() as connection: for statement in index_statements: connection.execute(text(statement)) def create_app() -> FastAPI: settings = get_settings() app = FastAPI( title=settings.project_name, description="SDN-like network and security control plane for Proxmox VE.", version="0.1.0", docs_url="/api/docs", openapi_url="/api/openapi.json", ) app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.cors_origins], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.on_event("startup") def startup() -> None: Base.metadata.create_all(bind=engine) ensure_runtime_indexes() with SessionLocal() as db: seed_demo_data(db) @app.get("/healthz") def healthz() -> dict[str, str]: return {"status": "ok"} app.include_router(api_router, prefix="/api/v1") return app app = create_app()