Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090)

This commit is contained in:
Thomas Karner committed 2026-09-20 23:49:40 +02:00
1 parent 3694cdf207
commit 8a51e3d95e
38 files changed
+2442 -21

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
from .app import create_app
__all__ = ["create_app"]
+54
View File
@@ -0,0 +1,54 @@
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from .. import __version__
from ..config import get_settings
from ..logging_setup import configure_logging
from .routes import health
log = logging.getLogger(__name__)
API_PREFIX = "/api/v1"
@asynccontextmanager
async def lifespan(app: FastAPI):
settings = get_settings()
log.info(
"poorbird api starting",
extra={"version": __version__, "image_root": str(settings.image_root)},
)
if not settings.enroll_secret_is_set:
# Not fatal at Phase 1 -- no device endpoint exists yet -- but it will
# be the first thing to break in Phase 2.
log.warning("POORBIRD_ENROLL_SECRET is not set; device enrollment will refuse requests")
yield
log.info("poorbird api stopping")
def create_app() -> FastAPI:
settings = get_settings()
configure_logging(settings.log_level, settings.log_format)
app = FastAPI(
title="poorBird",
version=__version__,
summary="Ingest, gallery and device management for a radar-triggered bird camera",
lifespan=lifespan,
)
app.include_router(health.router, prefix=API_PREFIX, tags=["health"])
app.include_router(health.root_router)
# Phase 2 mounts the device endpoints here: /enroll, /ingest, /heartbeat,
# /status, /config, /commands/{id}/ack, /firmware/{version}.bin.
# Phase 3 mounts the UI endpoints. See firmware/API.md for the contract.
return app
app = create_app()
+12
View File
@@ -0,0 +1,12 @@
from __future__ import annotations
from collections.abc import Iterator
from sqlalchemy.orm import Session
from ..db import SessionLocal
def get_db() -> Iterator[Session]:
with SessionLocal() as session:
yield session
Whitespace-only changes.
+82
View File
@@ -0,0 +1,82 @@
"""Health.
Two endpoints on purpose:
* ``/api/v1/health`` always answers 200 with detail, because the WebUI banner
wants to *render* a degraded system, not fail to load.
* ``/healthz`` answers 503 when the database is unreachable, because that is
what a proxy or a monitor should act on.
"""
from __future__ import annotations
import shutil
import time
from typing import Any
from fastapi import APIRouter, Response
from sqlalchemy import func, select, text
from ... import __version__
from ...config import get_settings
from ...db import SessionLocal
from ...models import BackupRun, Capture, Device
router = APIRouter()
# Mounted at the root, not under /api/v1: proxies and monitors expect /healthz
# where it has always been.
root_router = APIRouter()
_STARTED = time.monotonic()
def _db_probe() -> tuple[bool, str | None, dict[str, Any]]:
facts: dict[str, Any] = {}
try:
with SessionLocal() as s:
s.execute(text("SELECT 1"))
facts["devices"] = s.scalar(select(func.count()).select_from(Device))
facts["captures"] = s.scalar(select(func.count()).select_from(Capture))
last_backup = s.scalar(select(func.max(BackupRun.finished_at)))
facts["last_backup_at"] = last_backup.isoformat() if last_backup else None
return True, None, facts
except Exception as exc: # noqa: BLE001 - the point is to report, not raise
return False, f"{type(exc).__name__}: {exc}", facts
def _disk() -> dict[str, Any]:
settings = get_settings()
try:
usage = shutil.disk_usage(settings.image_root)
except OSError:
# Not yet created, or not mounted. Both are real conditions to report.
return {"available": False, "path": str(settings.image_root)}
return {
"available": True,
"path": str(settings.image_root),
"total_bytes": usage.total,
"free_bytes": usage.free,
"used_pct": round(100 * usage.used / usage.total, 1) if usage.total else None,
}
@router.get("/health", summary="System health, always 200")
def health() -> dict[str, Any]:
db_ok, db_error, facts = _db_probe()
settings = get_settings()
return {
"status": "ok" if db_ok else "degraded",
"version": __version__,
"uptime_s": round(time.monotonic() - _STARTED, 1),
"database": {"ok": db_ok, "error": db_error, **facts},
"disk": _disk(),
"enroll_secret_configured": settings.enroll_secret_is_set,
}
@root_router.get("/healthz", include_in_schema=False)
def healthz(response: Response) -> dict[str, str]:
db_ok, _, _ = _db_probe()
if not db_ok:
response.status_code = 503
return {"status": "unavailable"}
return {"status": "ok"}