from __future__ import annotations
import logging
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Any
from fastapi import Body, Depends, FastAPI, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from .auth import Identity, require_admin
from .config import SettingsError, data_dir, public_view
from .service import EtlService
LANDING_HTML = """
InterferenceETL
InterferenceETL
"""
def settings_error(exc: SettingsError) -> JSONResponse:
return JSONResponse(status_code=422, content={"error": exc.key, "field": exc.field, "params": exc.params})
def build_api(service: EtlService) -> FastAPI:
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
service.start()
try:
yield
finally:
service.stop()
api = FastAPI(title="InterferenceETL", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
@api.get("/", include_in_schema=False)
def landing() -> HTMLResponse:
return HTMLResponse(LANDING_HTML)
@api.get("/healthz")
def health() -> dict[str, bool]:
return {"ok": True}
@api.get("/api/status")
def status(_: Identity = Depends(require_admin)) -> dict[str, Any]:
return service.status()
@api.get("/api/settings")
def read_settings(_: Identity = Depends(require_admin)) -> dict[str, Any]:
return public_view(service.settings.get())
@api.put("/api/settings", response_model=None)
def write_settings(payload: dict[str, Any] = Body(...), _: Identity = Depends(require_admin)) -> Any:
try:
return public_view(service.update_settings(payload))
except SettingsError as exc:
return settings_error(exc)
@api.post("/api/checks", response_model=None)
def checks(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> Any:
try:
return service.check_connections(payload)
except SettingsError as exc:
return settings_error(exc)
@api.get("/api/runs")
def runs(page: int = 1, page_size: int = 20, status: str = "", _: Identity = Depends(require_admin)) -> dict[str, Any]:
items, total = service.runs.page(max(1, page), min(max(1, page_size), 200), status)
return {"items": items, "total": total}
@api.post("/api/runs")
def start_run(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> dict[str, bool]:
if not service.settings.configured():
raise HTTPException(status_code=409, detail="not_configured")
if not service.runner.start("manual", bool((payload or {}).get("dry_run"))):
raise HTTPException(status_code=409, detail="busy")
return {"started": True}
@api.post("/api/runs/cancel")
def cancel_run(_: Identity = Depends(require_admin)) -> dict[str, bool]:
return {"cancelled": service.runner.cancel()}
@api.get("/api/runs/{run_id}/log", response_class=PlainTextResponse)
def run_log(run_id: int, _: Identity = Depends(require_admin)) -> str:
if service.runs.get(run_id) is None:
raise HTTPException(status_code=404, detail="not_found")
return service.runner.read_log(run_id)
return api
def create_app() -> FastAPI:
from nicegui import ui
from .theme import ICON_PATH
from .ui import register
service = EtlService(data_dir())
api = build_api(service)
register(service)
ui.run_with(
api,
title="InterferenceETL",
favicon=ICON_PATH,
dark=None,
language="zh-CN",
reconnect_timeout=10,
show_welcome_message=False,
)
return api
class QuietSockets(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
message = record.getMessage()
return not (message.startswith("connection ") or '"WebSocket ' in message)
def main() -> None:
import uvicorn
config = uvicorn.Config(
create_app(),
host=os.getenv("HOST", "0.0.0.0"),
port=int(os.getenv("PORT", "8080")),
access_log=False,
timeout_graceful_shutdown=15,
)
logging.getLogger("uvicorn.error").addFilter(QuietSockets())
uvicorn.Server(config).run()
if __name__ == "__main__":
main()