Files
GTI_GERENCIADOR_FISCAL/central/app/main.py
T

55 lines
2.4 KiB
Python

"""FastAPI application factory."""
import logging
import sys
from collections.abc import Callable
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from .config import settings
from .db import SessionLocal, database_is_available
from .api import router
from .agent_distribution import router as agent_distribution_router
from .control_api import router as control_api_router
from .web import router as web_router
from .version import GTI_FISCAL_VERSION
logging.basicConfig(level=getattr(logging, settings.log_level.upper(), logging.INFO))
logger = logging.getLogger("gti_fiscal_hub")
def create_app(database_probe: Callable[[], bool] = database_is_available, session_factory=SessionLocal, bootstrap_token: str | None = None) -> FastAPI:
app = FastAPI(title="GTI Fiscal Hub", version=GTI_FISCAL_VERSION)
if settings.environment == "production" and settings.agent_dev_token:
raise RuntimeError("AGENT_DEV_TOKEN must not be set when APP_ENV=production (register real Agents with central/scripts/register_agent.py)")
logger.info("starting GTI Fiscal Hub (environment=%s)", settings.environment)
@app.get("/health")
def health() -> dict[str, str]:
if not database_probe():
logger.warning("health check failed: postgres unavailable")
raise HTTPException(status_code=503, detail="postgres unavailable")
return {"status": "ok"}
@app.get("/version")
def version() -> dict[str, str]:
from .classification import DECISION_VERSION, ENGINE_VERSION
from .version import API_COMPAT_MAJOR_MINOR, GTI_FISCAL_VERSION
return {"version": GTI_FISCAL_VERSION, "api_compat": API_COMPAT_MAJOR_MINOR, "engine_version": ENGINE_VERSION, "decision_version": DECISION_VERSION}
app.include_router(router(session_factory, settings.agent_dev_token if bootstrap_token is None else bootstrap_token))
app.include_router(control_api_router(session_factory))
app.include_router(agent_distribution_router(session_factory))
app.include_router(web_router(session_factory))
if settings.official_refresh_enabled and session_factory is SessionLocal and "pytest" not in sys.modules:
@app.on_event("startup")
def _start_official_refresh():
from .datasets.updater import start_scheduler
start_scheduler(session_factory)
app.mount("/static", StaticFiles(directory="central/static"), name="static")
return app
app = create_app()