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

+1
View File
@@ -0,0 +1 @@
__version__ = "0.1.0"
+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"}
+164
View File
@@ -0,0 +1,164 @@
"""Entry points.
``poorbird check`` is the one to reach for first on a fresh machine: it
validates config, storage paths and database connectivity and prints what it
found, without starting anything.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
from . import __version__
from .config import get_settings
from .logging_setup import configure_logging
def _alembic_config():
from alembic.config import Config
candidate = Path(os.environ.get("POORBIRD_ALEMBIC_INI", "alembic.ini"))
if not candidate.is_absolute():
candidate = Path.cwd() / candidate
if not candidate.exists():
raise SystemExit(
f"alembic.ini not found at {candidate}. Run from the server/ directory, "
"or set POORBIRD_ALEMBIC_INI."
)
cfg = Config(str(candidate))
cfg.set_main_option("script_location", str(candidate.parent / "migrations"))
return cfg
def cmd_serve(args: argparse.Namespace) -> int:
import uvicorn
settings = get_settings()
uvicorn.run(
"poorbird.api.app:app",
host=args.host or settings.api_host,
port=args.port or settings.api_port,
reload=args.reload,
log_config=None, # our own stdout logging, see logging_setup
)
return 0
def cmd_worker(_args: argparse.Namespace) -> int:
from .worker import run
return run()
def cmd_migrate(_args: argparse.Namespace) -> int:
from alembic import command
command.upgrade(_alembic_config(), "head")
return 0
def cmd_enqueue(args: argparse.Namespace) -> int:
from .db import SessionLocal
from .worker.queue import enqueue
payload = json.loads(args.payload) if args.payload else {}
with SessionLocal() as session:
job = enqueue(session, args.kind, payload)
session.commit()
print(f"queued job {job.id} ({args.kind})")
return 0
def cmd_check(_args: argparse.Namespace) -> int:
settings = get_settings()
problems: list[str] = []
print(f"poorbird {__version__}")
print(f" python {sys.version.split()[0]}")
# Never print the password.
url = settings.database_url
if "@" in url:
scheme, _, rest = url.partition("://")
url = f"{scheme}://***@{rest.rpartition('@')[2]}"
print(f" database_url {url}")
try:
from sqlalchemy import text
from .db import engine
with engine.connect() as conn:
version = conn.execute(text("SHOW server_version")).scalar()
print(f" database reachable (PostgreSQL {version})")
except Exception as exc: # noqa: BLE001
print(f" database UNREACHABLE: {type(exc).__name__}: {exc}")
problems.append("database unreachable")
try:
from alembic import command
print(" migrations ", end="")
command.current(_alembic_config())
except SystemExit as exc:
print(f"not checked ({exc})")
except Exception as exc: # noqa: BLE001
print(f"error: {type(exc).__name__}: {exc}")
for path in settings.storage_paths():
if not path.exists():
print(f" path {path} MISSING")
problems.append(f"{path} missing")
elif not os.access(path, os.W_OK):
print(f" path {path} NOT WRITABLE")
problems.append(f"{path} not writable")
else:
print(f" path {path} ok")
if not settings.enroll_secret_is_set:
print(" enroll_secret NOT SET (fine for Phase 1, required for Phase 2)")
if problems:
print(f"\n{len(problems)} problem(s): " + "; ".join(problems))
return 1
print("\nall checks passed")
return 0
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="poorbird", description="poorBird server")
parser.add_argument("--version", action="version", version=__version__)
sub = parser.add_subparsers(dest="command", required=True)
p = sub.add_parser("serve", help="run the HTTP API")
p.add_argument("--host")
p.add_argument("--port", type=int)
p.add_argument("--reload", action="store_true", help="development only")
p.set_defaults(func=cmd_serve)
p = sub.add_parser("worker", help="run the job queue worker and scheduler")
p.set_defaults(func=cmd_worker)
p = sub.add_parser("migrate", help="apply migrations (alembic upgrade head)")
p.set_defaults(func=cmd_migrate)
p = sub.add_parser("check", help="validate config, storage and database")
p.set_defaults(func=cmd_check)
p = sub.add_parser("enqueue", help="put a job on the queue (smoke test)")
p.add_argument("kind")
p.add_argument("payload", nargs="?", help="JSON object")
p.set_defaults(func=cmd_enqueue)
args = parser.parse_args(argv)
settings = get_settings()
configure_logging(settings.log_level, settings.log_format)
return args.func(args)
if __name__ == "__main__":
raise SystemExit(main())
+76
View File
@@ -0,0 +1,76 @@
"""Configuration.
Every value comes from the environment (TODO.md Phase 1.2). Nothing is read
from a committed config file, and no path, host or secret is baked into code.
systemd supplies these via ``EnvironmentFile=/etc/poorbird/poorbird.env``; for
local development a ``.env`` in the working directory is picked up as well.
"""
from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from typing import Literal
from pydantic import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="POORBIRD_",
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
# --- database ---------------------------------------------------------
# Loopback TCP with scram-sha-256, deliberately not a Unix socket: a socket
# is the one genuinely container-hostile choice (TODO.md Phase 1.2).
database_url: str = "postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird"
db_pool_size: int = 5
db_echo: bool = False
# --- http -------------------------------------------------------------
api_host: str = "127.0.0.1"
api_port: int = 8080
# --- storage ----------------------------------------------------------
# A small number of explicit top-level directories, never scattered under
# the app dir: these are the future volume mounts.
#
# image_root is the single source of truth for the image path. Caddy reads
# the same value, because the auth-checked handoff (SPEC 3.3) needs the app
# and the proxy to agree on where the bytes live.
image_root: Path = Path("/srv/poorbird/images")
thumb_root: Path = Path("/srv/poorbird/thumbs")
state_dir: Path = Path("/var/lib/poorbird")
# --- devices ----------------------------------------------------------
# Shared bootstrap secret presented by a device in X-Enroll-Secret.
# See firmware/API.md: do NOT rotate this without shipping new firmware,
# or you remove the last-resort recovery path for a mounted camera.
enroll_secret: SecretStr = SecretStr("")
# --- worker -----------------------------------------------------------
worker_poll_interval_s: float = 2.0
worker_batch_size: int = 1
job_max_attempts: int = 3
# --- logging ----------------------------------------------------------
# Always to stdout/stderr. journald catches it now; a log driver would
# catch it later. Never app-managed log files.
log_level: str = "INFO"
log_format: Literal["text", "json"] = "text"
@property
def enroll_secret_is_set(self) -> bool:
return bool(self.enroll_secret.get_secret_value())
def storage_paths(self) -> list[Path]:
return [self.image_root, self.thumb_root, self.state_dir]
@lru_cache
def get_settings() -> Settings:
return Settings()
+35
View File
@@ -0,0 +1,35 @@
"""Engine and session factory.
Synchronous SQLAlchemy, deliberately. At one camera and a few thousand frames a
day the async machinery buys nothing and costs clarity, and the worker's
``FOR UPDATE SKIP LOCKED`` loop is far easier to reason about synchronously.
FastAPI runs ``def`` handlers in a threadpool, so this does not block the loop.
Revisit only if the MJPEG relay (Phase 6) turns out to want it.
"""
from __future__ import annotations
from collections.abc import Iterator
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from .config import get_settings
_settings = get_settings()
engine = create_engine(
_settings.database_url,
pool_size=_settings.db_pool_size,
pool_pre_ping=True,
echo=_settings.db_echo,
future=True,
)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False, future=True)
def session_scope() -> Iterator[Session]:
"""Context-managed session for scripts and the worker."""
with SessionLocal() as session:
yield session
+55
View File
@@ -0,0 +1,55 @@
"""Logging to stdout only.
journald captures stdout for the systemd units today; a container log driver
would capture the same stream unchanged. Nothing writes log files.
"""
from __future__ import annotations
import json
import logging
import sys
from datetime import UTC, datetime
_RESERVED = set(
logging.LogRecord("", 0, "", 0, "", None, None).__dict__
) | {"message", "asctime", "taskName"}
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
"ts": datetime.fromtimestamp(record.created, UTC).isoformat(),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
}
for key, value in record.__dict__.items():
if key not in _RESERVED and not key.startswith("_"):
payload[key] = value
if record.exc_info:
payload["exc"] = self.formatException(record.exc_info)
return json.dumps(payload, default=str)
def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
handler = logging.StreamHandler(sys.stdout)
if fmt == "json":
handler.setFormatter(JsonFormatter())
else:
handler.setFormatter(
logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")
)
root = logging.getLogger()
root.handlers.clear()
root.addHandler(handler)
root.setLevel(level.upper())
# uvicorn installs its own handlers; make them use ours instead.
for name in ("uvicorn", "uvicorn.error", "uvicorn.access"):
lg = logging.getLogger(name)
lg.handlers.clear()
lg.propagate = True
logging.getLogger("apscheduler").setLevel("WARNING")
+29
View File
@@ -0,0 +1,29 @@
"""All models, imported here so ``Base.metadata`` is complete.
Alembic's env.py and the drift test both rely on importing this one module.
"""
from .base import Base
from .captures import Capture, Observation, Tag, Taxon, capture_tags
from .devices import Device, DeviceCommand, DeviceStatus, Firmware
from .ops import AuditLog, BackupRun, Job, Setting
from .users import Session, User
__all__ = [
"AuditLog",
"BackupRun",
"Base",
"Capture",
"Device",
"DeviceCommand",
"DeviceStatus",
"Firmware",
"Job",
"Observation",
"Session",
"Setting",
"Tag",
"Taxon",
"User",
"capture_tags",
]
+19
View File
@@ -0,0 +1,19 @@
from __future__ import annotations
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase
# Explicit names for every constraint. Without this, Alembic autogenerate
# cannot drop or alter constraints Postgres named for itself, and migrations
# start needing hand-written DDL.
NAMING_CONVENTION = {
"ix": "ix_%(table_name)s_%(column_0_N_name)s",
"uq": "uq_%(table_name)s_%(column_0_N_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING_CONVENTION)
+190
View File
@@ -0,0 +1,190 @@
"""Captures, observations, taxonomy and tags.
Two structural decisions from SPEC 3, both load-bearing:
1. ``captures`` 1--n ``observations``. One photo can hold two species, and can
legitimately hold none (a false trigger, an empty frame). A single
``species`` column on the image would have to be undone later.
2. Human labels and model predictions share one table, separated by
``source``. The edit UI is therefore already the training-data pipeline for
any future detection model, with no migration when that day comes.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
Index,
Integer,
String,
Table,
Text,
Column,
Uuid,
func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
# API.md sends 'radar'; SPEC 3 predates the LD2410 decision and says 'pir'.
TRIGGERS = ("radar", "manual", "timer", "stream_grab")
class Capture(Base):
__tablename__ = "captures"
__table_args__ = (
CheckConstraint("trigger IN " + str(TRIGGERS), name="trigger_valid"),
Index("ix_captures_device_received", "device_id", "received_at"),
Index("ix_captures_burst", "burst_id", "burst_index"),
Index("ix_captures_triage", "kept", "reviewed", "received_at"),
)
# UUID rather than a serial, because it is also the filename:
# /srv/poorbird/images/2026/09/08/<uuid>.jpg (SPEC 3.3).
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
path: Mapped[str] = mapped_column(Text)
thumb_path: Mapped[str | None] = mapped_column(Text)
sha256: Mapped[str] = mapped_column(String(64), index=True)
width: Mapped[int | None] = mapped_column(Integer)
height: Mapped[int | None] = mapped_column(Integer)
bytes: Mapped[int] = mapped_column(BigInteger)
# NULL when the device clock was unsynced. X-Captured-At: 0 means unsynced,
# NOT 1970 -- never store an epoch date for it (API.md).
captured_at_device: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# SPEC C7: authoritative, always.
received_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
trigger: Mapped[str] = mapped_column(String(16))
burst_id: Mapped[str | None] = mapped_column(String(64))
burst_index: Mapped[int | None] = mapped_column(Integer)
burst_count: Mapped[int | None] = mapped_column(Integer)
# SPEC 0 / API.md: this frame was captured BEFORE the trigger fired, out of
# the PSRAM ring. Usually the good ones -- the bird is still arriving.
pre_trigger: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
frame_seq: Mapped[int | None] = mapped_column(Integer)
radar_state: Mapped[int | None] = mapped_column(Integer) # 0 none 1 moving 2 stationary 3 both
radar_distance_cm: Mapped[int | None] = mapped_column(Integer)
radar_energy: Mapped[int | None] = mapped_column(Integer)
battery_mv: Mapped[int | None] = mapped_column(Integer)
rssi: Mapped[int | None] = mapped_column(Integer)
temp_c: Mapped[float | None] = mapped_column(Float)
reviewed: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
# Soft reject. Drives retention -- see TODO Phase 5 and open question 8.
kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
observations: Mapped[list[Observation]] = relationship(
back_populates="capture", cascade="all, delete-orphan"
)
tags: Mapped[list[Tag]] = relationship(secondary="capture_tags", back_populates="captures")
class Observation(Base):
__tablename__ = "observations"
__table_args__ = (
CheckConstraint("age IN ('adult', 'juvenile', 'unknown')", name="age_valid"),
CheckConstraint("sex IN ('male', 'female', 'unknown')", name="sex_valid"),
CheckConstraint(
"behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')",
name="behaviour_valid",
),
CheckConstraint(
"certainty IN ('certain', 'probable', 'uncertain')", name="certainty_valid"
),
CheckConstraint("source IN ('human', 'model')", name="source_valid"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
capture_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("captures.id", ondelete="CASCADE"), index=True
)
taxon_id: Mapped[int | None] = mapped_column(ForeignKey("taxa.id", ondelete="RESTRICT"))
individuals: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
age: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
sex: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
behaviour: Mapped[str | None] = mapped_column(String(16))
certainty: Mapped[str] = mapped_column(
String(16), default="certain", server_default="'certain'"
)
notes: Mapped[str | None] = mapped_column(Text)
source: Mapped[str] = mapped_column(String(8), default="human", server_default="'human'")
# Populated only when source = 'model'. Schema is ready; the pipeline is
# explicitly not built (SPEC Option C).
model_version: Mapped[str | None] = mapped_column(String(64))
confidence: Mapped[float | None] = mapped_column(Float)
bbox: Mapped[dict | None] = mapped_column(JSONB)
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
)
capture: Mapped[Capture] = relationship(back_populates="observations")
taxon: Mapped[Taxon | None] = relationship()
class Taxon(Base):
"""Seeded, never free text.
This is what makes "species, biologically" real rather than a string
column that accumulates Kohlmeise, kohlmeise, Parus major and Kohlmeise?
as four distinct species (SPEC 3.2).
"""
__tablename__ = "taxa"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
gbif_key: Mapped[int | None] = mapped_column(BigInteger, unique=True)
scientific_name: Mapped[str] = mapped_column(String(128), unique=True)
name_de: Mapped[str | None] = mapped_column(String(128), index=True)
name_en: Mapped[str | None] = mapped_column(String(128), index=True)
family: Mapped[str | None] = mapped_column(String(64))
# "order" is reserved in SQL; SQLAlchemy quotes it.
order: Mapped[str | None] = mapped_column("order", String(64))
iucn_status: Mapped[str | None] = mapped_column(String(8))
# Ranks the autocomplete. The local garden list comes first.
is_local_common: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
class Tag(Base):
__tablename__ = "tags"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
label: Mapped[str] = mapped_column(String(64), unique=True)
colour: Mapped[str | None] = mapped_column(String(16))
captures: Mapped[list[Capture]] = relationship(secondary="capture_tags", back_populates="tags")
capture_tags = Table(
"capture_tags",
Base.metadata,
Column("capture_id", ForeignKey("captures.id", ondelete="CASCADE"), primary_key=True),
Column("tag_id", ForeignKey("tags.id", ondelete="CASCADE"), primary_key=True),
)
+227
View File
@@ -0,0 +1,227 @@
"""Devices, their command queue, their telemetry and the firmware images.
Field names follow firmware/API.md, which is the contract the firmware
actually implements. Where SPEC.md 3 and API.md disagree, API.md wins and the
difference is noted inline.
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
Index,
Integer,
String,
Text,
func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
COMMAND_TYPES = (
"apply_config",
"capture_now",
"report_status",
"wake_and_hold",
"sleep_now",
"stream_start",
"stream_stop",
"ota_update",
"reboot",
)
STATUS_REASONS = (
"heartbeat",
"periodic",
"after_event",
"before_sleep",
"before_night_sleep",
"on_request",
)
class Device(Base):
__tablename__ = "devices"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
# eFuse MAC in hex. Survives reflashing, which is what makes it an
# identity rather than a name (API.md, Enrollment).
device_uid: Mapped[str] = mapped_column(String(32), unique=True, index=True)
name: Mapped[str] = mapped_column(String(64))
mac: Mapped[str | None] = mapped_column(String(32))
hw_revision: Mapped[str | None] = mapped_column(String(64))
fw_version: Mapped[str | None] = mapped_column(String(32))
# Only the hash is stored. The token is high-entropy, so a fast hash is
# defensible here (API.md).
token_hash: Mapped[str | None] = mapped_column(String(128))
# Per-device re-enrollment credential, so a rotated token cannot strand a
# camera that has no USB access once mounted (SPEC 0).
reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128))
# --- last-known conditions, denormalised from device_status for the list view
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
battery_mv: Mapped[int | None] = mapped_column(Integer)
battery_pct: Mapped[int | None] = mapped_column(Integer)
# false means NOT MEASURED, not empty. No divider is wired by default.
# Render as an em dash, never as a low-battery alarm (API.md, SPEC 0).
battery_valid: Mapped[bool] = mapped_column(Boolean, default=False)
rssi: Mapped[int | None] = mapped_column(Integer)
temp_c: Mapped[float | None] = mapped_column(Float)
# Reported every heartbeat so the UI can show command latency honestly (SPEC 0).
awake: Mapped[bool] = mapped_column(Boolean, default=True)
# --- settings surface
# One JSONB document rather than forty columns. This mirrors GET /config
# exactly: every key is optional and the device merges and clamps partial
# documents, so a strict column-per-key schema would be a migration every
# time the firmware gains a tunable. The UI edits it as a form; validation
# lives in a Pydantic model, not in the DDL.
config: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
# The only thing the device compares. Bump on every config change.
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
heartbeat_interval_s: Mapped[int] = mapped_column(Integer, default=300, server_default="300")
status_interval_s: Mapped[int] = mapped_column(Integer, default=900, server_default="900")
responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
commands: Mapped[list[DeviceCommand]] = relationship(
back_populates="device", cascade="all, delete-orphan"
)
class DeviceCommand(Base):
"""SPEC C1: the device is never pushed to, it drains this queue.
Commands ride along on the /ingest and /heartbeat response, so a capture
that was going to happen anyway also delivers the queue at no extra cost.
/status deliberately returns nothing actionable (API.md).
"""
__tablename__ = "device_commands"
__table_args__ = (
CheckConstraint(
"type IN " + str(COMMAND_TYPES),
name="type_valid",
),
CheckConstraint(
"ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')",
name="ack_status_valid",
),
Index("ix_device_commands_pending", "device_id", "created_at"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
type: Mapped[str] = mapped_column(String(32))
payload: Mapped[dict | None] = mapped_column(JSONB)
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
ack_status: Mapped[str | None] = mapped_column(String(16))
result: Mapped[str | None] = mapped_column(Text)
expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
device: Mapped[Device] = relationship(back_populates="commands")
class Firmware(Base):
__tablename__ = "firmware"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
version: Mapped[str] = mapped_column(String(32), unique=True)
semver: Mapped[str | None] = mapped_column(String(32))
file_path: Mapped[str] = mapped_column(Text)
sha256: Mapped[str] = mapped_column(String(64))
size_bytes: Mapped[int] = mapped_column(BigInteger)
release_notes: Mapped[str | None] = mapped_column(Text)
# SPEC C6 / API.md: the device refuses to flash below this.
min_battery_pct: Mapped[int] = mapped_column(Integer, default=50, server_default="50")
uploaded_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
uploaded_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
is_target: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
class DeviceStatus(Base):
"""Time series, one row per conditions report (SPEC 0).
The flat columns are the ones worth querying and charting. ``raw`` keeps
the whole posted body so nothing is lost when the firmware grows a field
before the server learns about it.
"""
__tablename__ = "device_status"
__table_args__ = (
CheckConstraint("reason IN " + str(STATUS_REASONS), name="reason_valid"),
Index("ix_device_status_device_at", "device_id", "at"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
reason: Mapped[str] = mapped_column(String(32))
battery_mv: Mapped[int | None] = mapped_column(Integer)
battery_pct: Mapped[int | None] = mapped_column(Integer)
battery_valid: Mapped[bool | None] = mapped_column(Boolean)
awake_ms: Mapped[int | None] = mapped_column(BigInteger)
boot_count: Mapped[int | None] = mapped_column(Integer)
wake_cause: Mapped[str | None] = mapped_column(String(16))
last_sleep_s: Mapped[int | None] = mapped_column(Integer)
total_sleep_s: Mapped[int | None] = mapped_column(BigInteger)
# The device's opinion, not the truth: these live in RTC memory and reset
# on power loss. `captures` is authoritative. Their real value is the GAP
# between captured and delivered, which is an upload-health signal.
captured_today: Mapped[int | None] = mapped_column(Integer)
delivered_today: Mapped[int | None] = mapped_column(Integer)
failed_today: Mapped[int | None] = mapped_column(Integer)
events_today: Mapped[int | None] = mapped_column(Integer)
# Days since epoch, local time; stays 0 until the clock syncs, so the
# pre-sync bucket is a phantom day. Do not chart it (API.md).
day_index: Mapped[int | None] = mapped_column(Integer)
is_night: Mapped[bool | None] = mapped_column(Boolean)
nightlight_on: Mapped[bool | None] = mapped_column(Boolean)
cam_profile: Mapped[str | None] = mapped_column(String(16))
# 0 here means no valid frame was decoded at any rate: wiring or a dead
# module, and worth an alert (API.md).
radar_baud: Mapped[int | None] = mapped_column(Integer)
radar_uart_ok: Mapped[bool | None] = mapped_column(Boolean)
stream_active: Mapped[bool | None] = mapped_column(Boolean)
rssi: Mapped[int | None] = mapped_column(Integer)
ip: Mapped[str | None] = mapped_column(String(45))
free_heap: Mapped[int | None] = mapped_column(BigInteger)
free_psram: Mapped[int | None] = mapped_column(BigInteger)
ring_depth: Mapped[int | None] = mapped_column(Integer)
time_synced: Mapped[bool | None] = mapped_column(Boolean)
device_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
fw_version: Mapped[str | None] = mapped_column(String(32))
config_version: Mapped[int | None] = mapped_column(Integer)
raw: Mapped[dict | None] = mapped_column(JSONB)
+112
View File
@@ -0,0 +1,112 @@
"""Operational tables: settings, audit log, backup runs, and the job queue."""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import (
BigInteger,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
Text,
func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
JOB_STATUSES = ("queued", "running", "done", "failed")
class Setting(Base):
"""SPEC 3.4. "Fully configurable" needs a boundary or it never finishes.
Server scope: retention policy, thumbnail size, backup schedule + target,
alarm thresholds and channels, default theme, default locale, session
lifetime. Anything not on that list is a code change, deliberately.
Backup schedule lives here rather than in a systemd timer, which is why
scheduling runs in the worker (TODO Phase 1.2).
"""
__tablename__ = "settings"
__table_args__ = (CheckConstraint("scope IN ('server', 'device')", name="scope_valid"),)
key: Mapped[str] = mapped_column(String(64), primary_key=True)
value: Mapped[str | None] = mapped_column(Text)
value_type: Mapped[str] = mapped_column(String(16), default="str", server_default="'str'")
scope: Mapped[str] = mapped_column(String(16), default="server", server_default="'server'")
updated_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
)
class AuditLog(Base):
__tablename__ = "audit_log"
__table_args__ = (Index("ix_audit_log_entity", "entity", "entity_id", "at"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
action: Mapped[str] = mapped_column(String(64))
entity: Mapped[str] = mapped_column(String(64))
entity_id: Mapped[str | None] = mapped_column(String(64))
before: Mapped[dict | None] = mapped_column(JSONB)
after: Mapped[dict | None] = mapped_column(JSONB)
ip: Mapped[str | None] = mapped_column(String(45))
class BackupRun(Base):
__tablename__ = "backup_runs"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
started_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
status: Mapped[str] = mapped_column(String(16), default="running")
bytes: Mapped[int | None] = mapped_column(BigInteger)
snapshot_id: Mapped[str | None] = mapped_column(String(64))
# A backup you have never restored is a hypothesis: set by the monthly
# restore test (TODO Phase 5).
restore_tested_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
error: Mapped[str | None] = mapped_column(Text)
class Job(Base):
"""Postgres-backed queue, claimed with FOR UPDATE SKIP LOCKED. No Redis.
This second writer is the concrete reason SPEC C8 pushed past SQLite.
"""
__tablename__ = "jobs"
__table_args__ = (
CheckConstraint("status IN " + str(JOB_STATUSES), name="status_valid"),
# The claim query's covering index.
Index("ix_jobs_claimable", "status", "run_at", "priority"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
kind: Mapped[str] = mapped_column(String(64))
payload: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
status: Mapped[str] = mapped_column(String(16), default="queued", server_default="'queued'")
priority: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
run_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
max_attempts: Mapped[int] = mapped_column(Integer, default=3, server_default="3")
locked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
locked_by: Mapped[str | None] = mapped_column(String(128))
last_error: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+65
View File
@@ -0,0 +1,65 @@
"""Users and sessions.
Devices are NOT users (SPEC 3.1). A device authenticates with a bearer token
scoped to /ingest, /heartbeat, /status, /config, /commands/*/ack, /firmware/*
and /stream/*. It can never read the gallery.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
String,
Uuid,
func,
)
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
ROLES = ("admin", "editor", "viewer")
THEMES = ("light", "dark", "blue")
class User(Base):
__tablename__ = "users"
__table_args__ = (
CheckConstraint("role IN " + str(ROLES), name="role_valid"),
CheckConstraint("theme IN " + str(THEMES), name="theme_valid"),
)
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(64), unique=True)
email: Mapped[str | None] = mapped_column(String(255))
# Argon2id. Populated in Phase 3; nothing writes it yet.
password_hash: Mapped[str | None] = mapped_column(String(255))
role: Mapped[str] = mapped_column(String(16), default="viewer", server_default="'viewer'")
totp_secret: Mapped[str | None] = mapped_column(String(64))
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
theme: Mapped[str] = mapped_column(String(16), default="light", server_default="'light'")
locale: Mapped[str] = mapped_column(String(8), default="de", server_default="'de'")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class Session(Base):
__tablename__ = "sessions"
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
ip: Mapped[str | None] = mapped_column(String(45))
user_agent: Mapped[str | None] = mapped_column(String(255))
+3
View File
@@ -0,0 +1,3 @@
from .main import run
__all__ = ["run"]
+63
View File
@@ -0,0 +1,63 @@
"""Job handlers.
A handler takes a session and a payload, and either returns (success) or
raises (retry, then park). Register with ``@handler("kind")``.
Phase 2 adds ``thumbnail``. Phase 5 adds ``backup``, ``retention`` and
``restore_test``.
"""
from __future__ import annotations
import logging
from collections.abc import Callable
from typing import Any
from sqlalchemy import text
from sqlalchemy.orm import Session
log = logging.getLogger(__name__)
Handler = Callable[[Session, dict[str, Any]], None]
HANDLERS: dict[str, Handler] = {}
def handler(kind: str) -> Callable[[Handler], Handler]:
def register(fn: Handler) -> Handler:
if kind in HANDLERS:
raise RuntimeError(f"duplicate handler for {kind!r}")
HANDLERS[kind] = fn
return fn
return register
@handler("noop")
def _noop(session: Session, payload: dict[str, Any]) -> None:
"""Smoke test for the queue. `poorbird enqueue noop` exercises the path."""
log.info("noop job ran", extra={"payload": payload})
@handler("prune_expired_commands")
def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None:
"""Expire commands the device never came back for.
A queued wake_and_hold from three days ago should not fire the moment a
camera reconnects after an outage.
"""
result = session.execute(
text(
"""
UPDATE device_commands
SET ack_status = 'failed',
acked_at = now(),
result = 'expired before delivery'
WHERE expires_at IS NOT NULL
AND expires_at < now()
AND acked_at IS NULL
"""
)
)
session.commit()
if result.rowcount:
log.info("expired stale device commands", extra={"count": result.rowcount})
+122
View File
@@ -0,0 +1,122 @@
"""Worker process: job queue consumer plus the scheduler.
Scheduling lives here rather than in systemd timers. SPEC 3.4 makes the backup
schedule and the retention policy UI-editable server settings, and a
UI-editable timer would mean the app writing unit files and calling
``daemon-reload`` behind a polkit rule. In-app, a schedule is a settings row.
(TODO Phase 1.2.)
"""
from __future__ import annotations
import logging
import signal
import threading
from typing import Any
from apscheduler.schedulers.background import BackgroundScheduler
from ..config import get_settings
from ..db import SessionLocal
from ..logging_setup import configure_logging
from . import queue
from .handlers import HANDLERS
log = logging.getLogger(__name__)
_stop = threading.Event()
def _run_one(job: dict[str, Any]) -> None:
kind = job["kind"]
fn = HANDLERS.get(kind)
with SessionLocal() as session:
if fn is None:
queue.fail(session, job["id"], f"no handler registered for {kind!r}")
log.error("unknown job kind", extra={"kind": kind, "job_id": job["id"]})
return
try:
fn(session, job["payload"] or {})
except Exception as exc: # noqa: BLE001 - a handler must not kill the worker
session.rollback()
log.exception("job failed", extra={"kind": kind, "job_id": job["id"]})
queue.fail(session, job["id"], f"{type(exc).__name__}: {exc}")
else:
queue.complete(session, job["id"])
log.info("job done", extra={"kind": kind, "job_id": job["id"]})
def _build_scheduler() -> BackgroundScheduler:
"""Periodic work, enqueued rather than executed inline.
The scheduler only ever *enqueues*. That keeps every unit of work in one
place -- the queue -- where it is visible, retried and auditable, instead
of some jobs running inside a timer callback where a failure disappears.
"""
scheduler = BackgroundScheduler(timezone="UTC")
def _enqueue(kind: str) -> None:
with SessionLocal() as session:
queue.enqueue(session, kind)
session.commit()
scheduler.add_job(
lambda: _enqueue("prune_expired_commands"),
"interval",
minutes=15,
id="prune_expired_commands",
max_instances=1,
coalesce=True,
)
def _reclaim() -> None:
with SessionLocal() as session:
queue.requeue_stale(session)
scheduler.add_job(
_reclaim, "interval", minutes=5, id="requeue_stale", max_instances=1, coalesce=True
)
# Phase 5 adds: backup (schedule from the settings table), retention,
# restore_test (monthly).
return scheduler
def run() -> int:
settings = get_settings()
configure_logging(settings.log_level, settings.log_format)
def _handle_signal(signum: int, _frame: Any) -> None:
log.info("shutdown requested", extra={"signal": signum})
_stop.set()
signal.signal(signal.SIGTERM, _handle_signal)
signal.signal(signal.SIGINT, _handle_signal)
scheduler = _build_scheduler()
scheduler.start()
log.info(
"poorbird worker started",
extra={"worker": queue.WORKER_ID, "handlers": sorted(HANDLERS)},
)
try:
while not _stop.is_set():
try:
with SessionLocal() as session:
job = queue.claim(session)
except Exception: # noqa: BLE001 - a DB blip must not end the worker
log.exception("could not reach the database; backing off")
_stop.wait(5.0)
continue
if job is None:
_stop.wait(settings.worker_poll_interval_s)
continue
_run_one(job)
finally:
scheduler.shutdown(wait=False)
log.info("poorbird worker stopped")
return 0
+132
View File
@@ -0,0 +1,132 @@
"""The job queue.
One statement claims a job: an UPDATE whose WHERE clause is a
``FOR UPDATE SKIP LOCKED`` subselect. Two workers racing for the same row
never block each other -- the loser skips to the next row rather than waiting.
This is the entire reason no Redis is needed (SPEC 6).
"""
from __future__ import annotations
import logging
import os
import socket
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import text
from sqlalchemy.orm import Session
from ..models import Job
log = logging.getLogger(__name__)
WORKER_ID = f"{socket.gethostname()}:{os.getpid()}"
_CLAIM_SQL = text(
"""
UPDATE jobs
SET status = 'running',
locked_at = now(),
locked_by = :worker,
attempts = attempts + 1
WHERE id = (
SELECT id
FROM jobs
WHERE status = 'queued'
AND run_at <= now()
ORDER BY priority DESC, run_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, kind, payload, attempts, max_attempts
"""
)
def enqueue(
session: Session,
kind: str,
payload: dict[str, Any] | None = None,
*,
priority: int = 0,
delay_s: float = 0,
max_attempts: int | None = None,
) -> Job:
job = Job(
kind=kind,
payload=payload or {},
priority=priority,
run_at=datetime.now(UTC) + timedelta(seconds=delay_s),
)
if max_attempts is not None:
job.max_attempts = max_attempts
session.add(job)
session.flush()
return job
def claim(session: Session) -> dict[str, Any] | None:
"""Claim one job, or return None. Commits so the lock is released promptly."""
row = session.execute(_CLAIM_SQL, {"worker": WORKER_ID}).mappings().first()
session.commit()
return dict(row) if row else None
def complete(session: Session, job_id: int) -> None:
session.execute(
text(
"UPDATE jobs SET status = 'done', finished_at = now(), "
"last_error = NULL WHERE id = :id"
),
{"id": job_id},
)
session.commit()
def fail(session: Session, job_id: int, error: str, *, retry_in_s: float = 60) -> None:
"""Retry with a delay until max_attempts, then park the job as failed."""
session.execute(
text(
"""
UPDATE jobs
SET status = CASE WHEN attempts >= max_attempts
THEN 'failed' ELSE 'queued' END,
finished_at = CASE WHEN attempts >= max_attempts
THEN now() ELSE NULL END,
run_at = CASE WHEN attempts >= max_attempts
THEN run_at
ELSE now() + make_interval(secs => :retry) END,
locked_at = NULL,
locked_by = NULL,
last_error = :error
WHERE id = :id
"""
),
{"id": job_id, "error": error[:4000], "retry": retry_in_s},
)
session.commit()
def requeue_stale(session: Session, older_than_s: int = 900) -> int:
"""Reclaim jobs whose worker died mid-run.
A SIGKILL or a power cut leaves rows in 'running' with nobody holding
them. Nothing else would ever pick those up.
"""
result = session.execute(
text(
"""
UPDATE jobs
SET status = 'queued', locked_at = NULL, locked_by = NULL,
last_error = 'reclaimed: worker vanished'
WHERE status = 'running'
AND locked_at < now() - make_interval(secs => :age)
"""
),
{"age": older_than_s},
)
session.commit()
if result.rowcount:
log.warning("reclaimed stale jobs", extra={"count": result.rowcount})
return result.rowcount or 0