diff --git a/TODO.md b/TODO.md index a3a68be..3896079 100644 --- a/TODO.md +++ b/TODO.md @@ -28,7 +28,7 @@ Anything here that contradicts SPEC means SPEC needs an edit, not a workaround. | Firmware | Written, compiles, **never run on hardware**. Known gaps below. | | Device↔server contract | Specified in full (`firmware/API.md`). Nothing implements the server half. | | Data model | Designed (SPEC §3) + §0 additions. No migration written. | -| Server | **Nothing exists.** | +| Server | Phase 1 skeleton in [`server/`](server/) — config, schema, health, job queue, scheduler, systemd units. **Not yet run against a real PostgreSQL.** | | WebUI | **Nothing exists.** | --- @@ -75,38 +75,46 @@ SPEC §10 Q3, restated as a radar question. Everything downstream assumes this w Target host: the x86 Linux thin client. No containers — packages and systemd units. -- [ ] Base install: static IP (or DHCP reservation) and **hardcode that address in firmware** — more reliable than mDNS +Skeleton written — see [`server/README.md`](server/README.md) to run it, and +[`server/deploy/INSTALL.md`](server/deploy/INSTALL.md) to deploy it. What is +written vs. what still needs doing on the real host: + +- [x] Python venv layout, FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Alembic — `server/` +- [x] systemd units `poorbird-api.service` + `poorbird-worker.service`, `After=postgresql.service`, restart policies, sandboxing +- [x] Caddyfile with DNS-01 TLS, the `:8080` plain-HTTP camera listener and the auth-checked image handoff +- [x] `poorbird check` — validates config, paths and DB before anything starts +- [ ] **Run it against a real PostgreSQL** — nothing here has executed yet; `pytest` and `poorbird check` are the first two commands +- [ ] Base install on the thin client: static IP (or DHCP reservation) and **hardcode that address in firmware** — more reliable than mDNS - [ ] PostgreSQL 17 from the distro or PGDG repo; dedicated role + database; **loopback TCP with `scram-sha-256`, not a Unix socket** (see 1.2) -- [ ] Python 3.13 venv under `/opt/poorbird`, FastAPI + Pydantic v2 + SQLAlchemy 2.0 + Alembic -- [ ] systemd units: `poorbird-api.service`, `poorbird-worker.service`, both `After=postgresql.service` with restart policies -- [ ] Caddy as a host package; automatic TLS via **DNS-01** so a LAN-only hostname gets a valid cert with no port forwarding +- [ ] Caddy DNS provider plugin build (`caddy add-package …`) and a real hostname - [ ] Tailscale for remote access -- [ ] Image store at `/srv/poorbird/images/YYYY/MM/DD/.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) +- [ ] Image store at `/srv/poorbird/images/YYYY/MM/DD/.jpg`, thumbs alongside as `_400.webp` (SPEC §3.3) — paths configured, writer is Phase 2 - [ ] journald log retention capped, disk usage alarmed ### 1.1 Schema — SPEC §3 plus the §0 additions -- [ ] Initial Alembic migration covering SPEC §3 verbatim -- [ ] `captures.pre_trigger BOOL` — was this frame captured *before* the trigger fired -- [ ] `devices.awake BOOL` — reported every heartbeat, so the UI can show command latency honestly -- [ ] `devices.reenroll_secret_hash` -- [ ] `device_status` time-series table (full column list in SPEC §0) -- [ ] `devices` settings surface: `cam_day`, `cam_night` (full OV2640 parameter sets), night window + behaviour, nightlight mode + brightness, battery calibration, `config_version` -- [ ] Job queue on Postgres with `FOR UPDATE SKIP LOCKED` — thumbnails, retention, backup, exports. **No Redis.** +- [x] Initial Alembic migration covering SPEC §3, guarded by a schema-drift test +- [x] `captures.pre_trigger BOOL` — was this frame captured *before* the trigger fired +- [x] `devices.awake BOOL` — reported every heartbeat, so the UI can show command latency honestly +- [x] `devices.reenroll_secret_hash` +- [x] `device_status` time-series table (SPEC §0 columns, plus `raw` JSONB so nothing is lost) +- [x] `devices` settings surface — **one JSONB `config` column, not forty**: `GET /config` is ~40 optional keys the firmware merges and clamps, so a column per key means a migration per firmware tunable. Validation moves to a Pydantic model. Promote an individual key to a column only if it ever needs querying across devices. +- [x] Job queue on Postgres with `FOR UPDATE SKIP LOCKED` — **No Redis.** Handlers for thumbnails / retention / backup arrive with their phases. +- [ ] Seed `taxa` (Phase 3) and the `settings` defaults ### 1.2 Staying container-ready Not building containers now. Just not painting into a corner. Each of these is cheap today and most are the better native choice regardless. -- [ ] **All config from environment**, via systemd `EnvironmentFile=/etc/poorbird/poorbird.env`. No paths, hosts or secrets baked into code or committed config. That file becomes a compose `.env` unchanged. -- [ ] **Postgres over loopback TCP**, not a Unix socket — the one genuinely container-hostile choice, and the only real change from a purely native design -- [ ] **All mutable state in a few explicit top-level directories** (`/srv/poorbird/images`, `/srv/poorbird/thumbs`, `/var/lib/poorbird`), never scattered under the app dir. These are the future volume mounts. -- [ ] **Log to stdout/stderr.** journald catches it now, a log driver would catch it later. Simpler than app-managed log files either way. -- [ ] **Migrations as a standalone idempotent command** (`alembic upgrade head`), run from `ExecStartPre` — never at app import time -- [ ] **One env var for the image root**, read by both the app and the Caddy config, since the auth-checked handoff needs them to agree on the path -- [ ] **Scheduled jobs run in the worker, not as systemd timers** — decided. APScheduler with a SQLAlchemy jobstore on the existing Postgres. Not primarily for portability: SPEC §3.4 makes *backup schedule + target* and *retention policy* UI-editable server settings, and a UI-editable systemd timer means the app writing unit files and calling `daemon-reload` behind a polkit or sudoers rule. In-app, the schedule is just a settings row. Timers stay the better answer for anything that is **not** UI-configurable — if such a job appears, use one. -- [ ] Keep API and worker as separate processes — already the plan, and it maps 1:1 to two services later +- [x] **All config from environment**, via systemd `EnvironmentFile=/etc/poorbird/poorbird.env`. No paths, hosts or secrets baked into code or committed config. That file becomes a compose `.env` unchanged. +- [x] **Postgres over loopback TCP**, not a Unix socket — the one genuinely container-hostile choice, and the only real change from a purely native design +- [x] **All mutable state in a few explicit top-level directories** (`/srv/poorbird/images`, `/srv/poorbird/thumbs`, `/var/lib/poorbird`), never scattered under the app dir. These are the future volume mounts. +- [x] **Log to stdout/stderr.** journald catches it now, a log driver would catch it later. Simpler than app-managed log files either way. +- [x] **Migrations as a standalone idempotent command** (`poorbird migrate`), run from `ExecStartPre` on the API unit only — never at app import time, and never from two units at once +- [x] **One env var for the image root**, read by both the app and the Caddy config, since the auth-checked handoff needs them to agree on the path +- [x] **Scheduled jobs run in the worker, not as systemd timers** — decided. APScheduler with a SQLAlchemy jobstore on the existing Postgres. Not primarily for portability: SPEC §3.4 makes *backup schedule + target* and *retention policy* UI-editable server settings, and a UI-editable systemd timer means the app writing unit files and calling `daemon-reload` behind a polkit or sudoers rule. In-app, the schedule is just a settings row. Timers stay the better answer for anything that is **not** UI-configurable — if such a job appears, use one. +- [x] Keep API and worker as separate processes — maps 1:1 to two services later **Deliberately not doing now:** writing Dockerfiles or a compose file speculatively. That means maintaining two deployment paths to prove a point. diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..fb710db --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,10 @@ +.venv/ +venv/ +__pycache__/ +*.py[cod] +*.egg-info/ +build/ +dist/ +.pytest_cache/ +.ruff_cache/ +.env diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..9d7e0cd --- /dev/null +++ b/server/README.md @@ -0,0 +1,129 @@ +# poorBird server + +Phase 1 skeleton: configuration, schema, health, job queue and scheduler. +There are **no device endpoints yet** — `/enroll`, `/ingest`, `/heartbeat`, +`/status` and `/config` are Phase 2. The contract they must satisfy is +[`../firmware/API.md`](../firmware/API.md). + +Stack per SPEC §6, deployed natively per [`../TODO.md`](../TODO.md) Phase 1.2: +FastAPI + PostgreSQL 17 + SQLAlchemy 2.0 + Alembic, run as systemd units +behind Caddy. No containers — but nothing here blocks them either. + +--- + +## Try it on any Linux machine + +Needs Python ≥ 3.11 and a PostgreSQL you can reach. Production targets 3.13; +the floor is lower so this runs on a stock Debian 12 or Ubuntu 24.04 box. + +```bash +sudo apt install -y python3-venv postgresql + +sudo -u postgres psql <<'SQL' +CREATE ROLE poorbird LOGIN PASSWORD 'poorbird'; +CREATE DATABASE poorbird OWNER poorbird; +SQL + +cd server +python3 -m venv .venv && . .venv/bin/activate +pip install -e '.[dev]' + +cat > .env <<'ENV' +POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:poorbird@127.0.0.1:5432/poorbird +POORBIRD_IMAGE_ROOT=/tmp/poorbird/images +POORBIRD_THUMB_ROOT=/tmp/poorbird/thumbs +POORBIRD_STATE_DIR=/tmp/poorbird/state +POORBIRD_API_PORT=8090 +ENV +mkdir -p /tmp/poorbird/{images,thumbs,state} + +poorbird check # config, paths, database — before starting anything +poorbird migrate # alembic upgrade head +poorbird serve # http://127.0.0.1:8090/api/v1/health +``` + +In a second shell: + +```bash +cd server && . .venv/bin/activate +poorbird worker & +poorbird enqueue noop '{"hello": "world"}' # the worker logs it within ~2s +``` + +`poorbird check` is the fast answer to "is this machine set up correctly" — it +validates config, storage paths and database connectivity and prints what it +found, without starting a service. + +### Tests + +```bash +pytest # everything reachable +pytest -m 'not db' # no PostgreSQL needed +``` + +Queue and schema tests need a real PostgreSQL — `FOR UPDATE SKIP LOCKED` has +no equivalent elsewhere, and mocking it would test nothing. They skip +automatically when the database is unreachable, so a green run with no +Postgres proves less than it looks. Check for `skipped` in the summary. + +--- + +## Layout + +``` +src/poorbird/ + config.py every value from the environment, nothing baked in + logging_setup.py stdout only; journald or a log driver catches it + db.py engine + session factory (sync, deliberately) + models/ SPEC §3 schema + the SPEC §0 additions + api/ FastAPI app; Phase 2 mounts device routes here + worker/ queue (SKIP LOCKED), handlers, scheduler + cli.py serve | worker | migrate | check | enqueue +migrations/ Alembic +deploy/ systemd units, Caddyfile, env template, INSTALL.md +tests/ +``` + +--- + +## Decisions worth knowing before you read the code + +**Sync SQLAlchemy, not async.** At one camera and a few thousand frames a day +the async machinery buys nothing and costs clarity, and the worker's claim +loop is far easier to reason about synchronously. FastAPI runs `def` handlers +in a threadpool, so this does not block the event loop. The one thing that may +argue otherwise later is the MJPEG relay in Phase 6. + +**Device config is one JSONB column, not forty.** `GET /config` returns ~40 +optional keys and the firmware merges and clamps partial documents, so a +column per key would mean a migration every time the firmware gains a tunable. +Validation belongs in a Pydantic model, not in the DDL. The trade: you cannot +index or constrain an individual setting in SQL. If one ever needs querying +across devices, promote just that key to a column. + +**Migration 0001 builds from `Base.metadata`.** A bounded exception, and +`tests/test_schema_matches_models.py` migrates a scratch database and asserts +an empty autogenerate diff, so the models and the migration cannot silently +diverge. Every later revision is a normal autogenerated one. If you prefer +explicit DDL in the baseline, autogenerate it against an empty database and +replace the file — the drift test passes either way. + +**The scheduler only enqueues, never executes.** Every unit of work goes +through the queue, where it is visible, retried and auditable, rather than +running inside a timer callback where a failure disappears. + +--- + +## Two things the code already guards, and the UI must too + +- `battery_valid = false` means **not measured** — no divider is wired by + default. Render it as "—", never as a low-battery alarm. +- The daily counters live in the device's RTC memory and reset on power loss. + `captures` is authoritative. The counters' value is the *gap* between + captured and delivered, which is an upload-health signal. + +--- + +## Deploying for real + +See [`deploy/INSTALL.md`](deploy/INSTALL.md). diff --git a/server/alembic.ini b/server/alembic.ini new file mode 100644 index 0000000..21c715d --- /dev/null +++ b/server/alembic.ini @@ -0,0 +1,39 @@ +[alembic] +script_location = migrations +prepend_sys_path = src +# The URL is NOT set here. migrations/env.py takes it from POORBIRD_DATABASE_URL +# so that config comes from exactly one place (TODO.md Phase 1.2). + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARNING +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARNING +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stdout,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/server/deploy/Caddyfile b/server/deploy/Caddyfile new file mode 100644 index 0000000..682b69d --- /dev/null +++ b/server/deploy/Caddyfile @@ -0,0 +1,73 @@ +# poorBird reverse proxy. Install to /etc/caddy/Caddyfile. +# +# Ports, so nothing collides: +# 127.0.0.1:8090 uvicorn (POORBIRD_API_PORT) -- never exposed +# :8080 plain HTTP for the camera (SPEC C2, firmware/API.md) +# :443 TLS for humans +# +# TLS: Caddy gets a real Let's Encrypt certificate for a LAN-only hostname via +# DNS-01, so there is no port forwarding and no browser warning. That needs a +# Caddy build with your DNS provider's plugin: +# +# caddy add-package github.com/caddy-dns/cloudflare +# +# For a first test on any Linux box you can skip the whole human-facing block +# and just use the :8080 one. + +(protected_files) { + # Auth-checked image serving (SPEC 3.3). + # + # An unguessable URL is not access control. The app authorizes the + # request, then replies with an empty body and + # X-Accel-Redirect: /images/2026/09/08/.jpg + # and Caddy serves the bytes from disk. The browser never receives a + # directly fetchable URL. + # + # The root below is the PARENT of POORBIRD_IMAGE_ROOT and + # POORBIRD_THUMB_ROOT in /etc/poorbird/poorbird.env. One value, two + # readers -- keep them in step. + @accel header X-Accel-Redirect * + handle_response @accel { + rewrite * {rp.header.X-Accel-Redirect} + file_server { + root /srv/poorbird + } + } +} + +# --- humans ----------------------------------------------------------------- +poorbird.example.internal { + tls { + dns cloudflare {env.CLOUDFLARE_API_TOKEN} + } + + encode zstd gzip + + reverse_proxy 127.0.0.1:8090 { + header_up X-Real-IP {remote_host} + import protected_files + } +} + +# --- the camera -------------------------------------------------------------- +# Plain HTTP on the LAN, deliberately (SPEC C2): TLS on the ESP32 means a CA +# baked into firmware, and a mounted camera that silently stops uploading when +# the chain rotates. +:8080 { + handle /api/v1/* { + request_body { + # A burst frame at UXGA can be a few hundred KB; an OTA image is + # ~1-2 MB. The default limit is too small for both. + max_size 12MB + } + reverse_proxy 127.0.0.1:8090 + } + + handle /healthz { + reverse_proxy 127.0.0.1:8090 + } + + handle { + respond 404 + } +} diff --git a/server/deploy/INSTALL.md b/server/deploy/INSTALL.md new file mode 100644 index 0000000..148ed08 --- /dev/null +++ b/server/deploy/INSTALL.md @@ -0,0 +1,144 @@ +# Installing poorBird on the thin client + +Written for: whoever sets up the server host — assumes comfort with systemd +and `psql`, but not with this project. + +Target is an x86 Linux box on the same LAN as the camera (SPEC §0). Native +packages and systemd units, no containers. Commands below assume Debian or +Ubuntu; adjust the package manager otherwise. + +--- + +## 1. Packages and user + +```bash +sudo apt update +sudo apt install -y postgresql python3-venv python3-pip git caddy + +sudo useradd --system --home-dir /opt/poorbird --shell /usr/sbin/nologin poorbird +sudo mkdir -p /opt/poorbird /etc/poorbird /srv/poorbird/{images,thumbs} /var/lib/poorbird +sudo chown -R poorbird:poorbird /srv/poorbird /var/lib/poorbird /opt/poorbird +``` + +## 2. Database + +Loopback TCP with `scram-sha-256`, deliberately not a Unix socket — see +`TODO.md` Phase 1.2. + +```bash +sudo -u postgres psql <<'SQL' +CREATE ROLE poorbird LOGIN PASSWORD 'PUT_A_REAL_PASSWORD_HERE'; +CREATE DATABASE poorbird OWNER poorbird; +SQL +``` + +Confirm `pg_hba.conf` has a `host all all 127.0.0.1/32 scram-sha-256` +line before any `trust` line, then `sudo systemctl reload postgresql`. + +Verify the path the app will actually use, not the socket: + +```bash +psql "postgresql://poorbird:PUT_A_REAL_PASSWORD_HERE@127.0.0.1:5432/poorbird" -c 'SELECT 1' +``` + +## 3. Application + +```bash +sudo -u poorbird git clone /opt/poorbird/src +sudo ln -sfn /opt/poorbird/src/server /opt/poorbird/app +sudo -u poorbird python3 -m venv /opt/poorbird/venv +sudo -u poorbird /opt/poorbird/venv/bin/pip install -e /opt/poorbird/app +``` + +## 4. Configuration + +```bash +sudo cp /opt/poorbird/app/deploy/poorbird.env.example /etc/poorbird/poorbird.env +sudo chown root:poorbird /etc/poorbird/poorbird.env +sudo chmod 0640 /etc/poorbird/poorbird.env +sudo -e /etc/poorbird/poorbird.env # set the DB password and the enroll secret +``` + +Generate the enroll secret with `openssl rand -hex 32`. + +> **Before you ever rotate `POORBIRD_ENROLL_SECRET`:** it is compiled into the +> firmware image as the last-resort recovery path for a camera that cannot be +> reached over USB once mounted. Rotating it here without also shipping new +> firmware removes that escape hatch (`firmware/API.md`). + +Check the machine before starting anything: + +```bash +sudo -u poorbird env $(sudo cat /etc/poorbird/poorbird.env | grep -v '^#' | xargs) \ + /opt/poorbird/venv/bin/poorbird check +``` + +## 5. Services + +```bash +sudo cp /opt/poorbird/app/deploy/poorbird-*.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now poorbird-api poorbird-worker +systemctl status poorbird-api poorbird-worker +journalctl -u poorbird-api -f +``` + +The API unit runs `poorbird migrate` in `ExecStartPre`. The worker unit +deliberately does not, so two units never race to apply the same revision. + +Smoke test: + +```bash +curl -s localhost:8090/api/v1/health | python3 -m json.tool +``` + +## 6. Reverse proxy + +```bash +sudo cp /opt/poorbird/app/deploy/Caddyfile /etc/caddy/Caddyfile +sudo -e /etc/caddy/Caddyfile # set your hostname and DNS provider +sudo systemctl reload caddy +``` + +Ports, so nothing collides: + +| Port | Who | +|---|---| +| `127.0.0.1:8090` | uvicorn — never exposed | +| `:8080` | plain HTTP for the camera (SPEC C2) | +| `:443` | TLS for humans | + +DNS-01 needs a Caddy build with your provider's plugin: +`caddy add-package github.com/caddy-dns/cloudflare`. For a first test, replace +the human-facing site block with `http://:8081` and drop the `tls` block. + +## 7. Network + +Give the server a **DHCP reservation or a static IP, then hardcode that +address in the firmware** — simpler and more reliable than mDNS (SPEC §9). +The camera has no way to be told a new address once it is mounted and cannot +reach the endpoint. + +--- + +## Upgrading + +```bash +sudo -u poorbird git -C /opt/poorbird/src pull +sudo -u poorbird /opt/poorbird/venv/bin/pip install -e /opt/poorbird/app +sudo systemctl restart poorbird-api poorbird-worker +``` + +`ExecStartPre` applies migrations on restart. + +> Restarting mid-OTA-rollout matters: a device on a trial image marks that +> image valid **only after a heartbeat the endpoint accepted**. Returning 5xx +> to a trial device rolls it back — correct behaviour, but know it before you +> restart the API during a rollout (`firmware/API.md`). + +## Backups + +Not built yet — TODO Phase 5, and blocked on open question 9 (whether the NAS +offers SFTP, or only SMB/NFS), which decides between restic and a mounted +path. Until then **this machine is not backed up.** Do not let real captures +accumulate here before that is done. diff --git a/server/deploy/poorbird-api.service b/server/deploy/poorbird-api.service new file mode 100644 index 0000000..f3d90b5 --- /dev/null +++ b/server/deploy/poorbird-api.service @@ -0,0 +1,44 @@ +[Unit] +Description=poorBird API +After=network-online.target postgresql.service +Wants=network-online.target +Requires=postgresql.service + +[Service] +Type=exec +User=poorbird +Group=poorbird +WorkingDirectory=/opt/poorbird/app +EnvironmentFile=/etc/poorbird/poorbird.env + +# Migrations run as a separate idempotent command, never at app import time. +# Same command a container entrypoint or init job would call. +ExecStartPre=/opt/poorbird/venv/bin/poorbird migrate +ExecStart=/opt/poorbird/venv/bin/poorbird serve + +Restart=on-failure +RestartSec=5 +TimeoutStopSec=20 + +# Logs go to stdout and journald picks them up. No app-managed log files. +StandardOutput=journal +StandardError=journal +SyslogIdentifier=poorbird-api + +# --- hardening +NoNewPrivileges=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +RestrictSUIDSGID=yes +LockPersonality=yes +MemoryDenyWriteExecute=no +ReadWritePaths=/srv/poorbird /var/lib/poorbird + +[Install] +WantedBy=multi-user.target diff --git a/server/deploy/poorbird-worker.service b/server/deploy/poorbird-worker.service new file mode 100644 index 0000000..4043631 --- /dev/null +++ b/server/deploy/poorbird-worker.service @@ -0,0 +1,42 @@ +[Unit] +Description=poorBird worker (job queue + scheduler) +After=network-online.target postgresql.service poorbird-api.service +Wants=network-online.target +Requires=postgresql.service + +[Service] +Type=exec +User=poorbird +Group=poorbird +WorkingDirectory=/opt/poorbird/app +EnvironmentFile=/etc/poorbird/poorbird.env + +# No ExecStartPre=migrate here: the API unit owns migrations, so two units +# never race to apply the same revision. +ExecStart=/opt/poorbird/venv/bin/poorbird worker + +Restart=on-failure +RestartSec=5 +# The worker finishes its current job on SIGTERM. +KillSignal=SIGTERM +TimeoutStopSec=60 + +StandardOutput=journal +StandardError=journal +SyslogIdentifier=poorbird-worker + +# --- hardening +NoNewPrivileges=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +LockPersonality=yes +ReadWritePaths=/srv/poorbird /var/lib/poorbird + +[Install] +WantedBy=multi-user.target diff --git a/server/deploy/poorbird.env.example b/server/deploy/poorbird.env.example new file mode 100644 index 0000000..c011804 --- /dev/null +++ b/server/deploy/poorbird.env.example @@ -0,0 +1,44 @@ +# poorBird configuration. +# +# Install to /etc/poorbird/poorbird.env, owned by root:poorbird, mode 0640. +# systemd loads it via EnvironmentFile. This same file becomes a compose .env +# unchanged if containers ever happen (TODO.md Phase 1.2). +# +# Note: systemd's EnvironmentFile does NOT do shell quoting or expansion. +# Write VALUES literally, with no surrounding quotes. + +# --- database --------------------------------------------------------------- +# Loopback TCP with scram-sha-256, deliberately not a Unix socket. +POORBIRD_DATABASE_URL=postgresql+psycopg://poorbird:CHANGE_ME@127.0.0.1:5432/poorbird + +# --- http ------------------------------------------------------------------- +# Bind to loopback only; Caddy is the only thing that talks to it. +# Caddy itself takes :8080 for the camera and :443 for humans, so uvicorn sits +# behind on 8090. See deploy/Caddyfile. +POORBIRD_API_HOST=127.0.0.1 +POORBIRD_API_PORT=8090 + +# --- storage ---------------------------------------------------------------- +# Read by the app AND referenced by the Caddyfile: the auth-checked image +# handoff needs both to agree on this path (SPEC 3.3). +POORBIRD_IMAGE_ROOT=/srv/poorbird/images +POORBIRD_THUMB_ROOT=/srv/poorbird/thumbs +POORBIRD_STATE_DIR=/var/lib/poorbird + +# --- devices ---------------------------------------------------------------- +# Shared bootstrap secret the firmware presents in X-Enroll-Secret. +# Generate with: openssl rand -hex 32 +# +# WARNING (firmware/API.md): this value is compiled into the firmware image as +# the last-resort recovery path for a camera that cannot be reached over USB. +# Rotating it here WITHOUT shipping new firmware removes that escape hatch. +POORBIRD_ENROLL_SECRET= + +# --- worker ----------------------------------------------------------------- +POORBIRD_WORKER_POLL_INTERVAL_S=2 +POORBIRD_JOB_MAX_ATTEMPTS=3 + +# --- logging ---------------------------------------------------------------- +POORBIRD_LOG_LEVEL=INFO +# text for journalctl by eye, json once you are shipping logs somewhere. +POORBIRD_LOG_FORMAT=text diff --git a/server/migrations/env.py b/server/migrations/env.py new file mode 100644 index 0000000..44bfc8a --- /dev/null +++ b/server/migrations/env.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from logging.config import fileConfig + +from alembic import context +from sqlalchemy import engine_from_config, pool + +from poorbird.config import get_settings +from poorbird.models import Base + +config = context.config + +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# One source of truth for the URL: the environment, via Settings. An explicit +# override still wins, so tests can point a run at a scratch database. +if not config.get_main_option("sqlalchemy.url", None): + config.set_main_option("sqlalchemy.url", get_settings().database_url) + +target_metadata = Base.metadata + +OPTS = {"compare_type": True, "compare_server_default": True} + + +def run_migrations_offline() -> None: + context.configure( + url=config.get_main_option("sqlalchemy.url"), + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + **OPTS, + ) + with context.begin_transaction(): + context.run_migrations() + + +def _run(connection) -> None: + context.configure(connection=connection, target_metadata=target_metadata, **OPTS) + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + # A caller may hand us a live connection (the schema-drift test does). + injected = config.attributes.get("connection", None) + if injected is not None: + _run(injected) + return + + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + with connectable.connect() as connection: + _run(connection) + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/server/migrations/script.py.mako b/server/migrations/script.py.mako new file mode 100644 index 0000000..063ed2a --- /dev/null +++ b/server/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" +from __future__ import annotations + +from collections.abc import Sequence + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +revision: str = ${repr(up_revision)} +down_revision: str | None = ${repr(down_revision)} +branch_labels: str | Sequence[str] | None = ${repr(branch_labels)} +depends_on: str | Sequence[str] | None = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/server/migrations/versions/0001_initial.py b/server/migrations/versions/0001_initial.py new file mode 100644 index 0000000..9f3bad5 --- /dev/null +++ b/server/migrations/versions/0001_initial.py @@ -0,0 +1,42 @@ +"""Baseline schema: SPEC 3 plus the SPEC 0 additions. + +Revision ID: 0001 +Revises: +Create Date: 2026-09-20 + +This baseline builds the schema from ``Base.metadata`` rather than from +hand-written DDL. That is a deliberate, bounded exception, and it applies to +this revision only: + +* it cannot drift from the models, which hand-written DDL silently can; +* ``tests/test_schema_matches_models.py`` asserts that a freshly migrated + database produces an empty autogenerate diff, so the guarantee is checked + rather than assumed; +* every subsequent revision is a normal autogenerated one with real + ``op.*`` operations. + +If you would rather have explicit DDL here, run +``alembic revision --autogenerate`` against an empty database once Postgres is +up and replace this file with the result. The drift test passes either way. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +from alembic import op + +from poorbird.models import Base + +revision: str = "0001" +down_revision: str | None = None +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + Base.metadata.create_all(bind=op.get_bind()) + + +def downgrade() -> None: + Base.metadata.drop_all(bind=op.get_bind()) diff --git a/server/pyproject.toml b/server/pyproject.toml new file mode 100644 index 0000000..74fc449 --- /dev/null +++ b/server/pyproject.toml @@ -0,0 +1,45 @@ +[project] +name = "poorbird" +version = "0.1.0" +description = "poorBird server — ingest, gallery and device management for a radar-triggered bird camera" +requires-python = ">=3.11" +dependencies = [ + "fastapi>=0.115", + "uvicorn[standard]>=0.32", + "pydantic>=2.9", + "pydantic-settings>=2.6", + "sqlalchemy>=2.0.36", + "psycopg[binary]>=3.2", + "alembic>=1.14", + "apscheduler>=3.11,<4", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.3", + "httpx>=0.28", + "ruff>=0.8", +] + +[project.scripts] +poorbird = "poorbird.cli:main" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/poorbird"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +markers = [ + "db: integration test, needs a reachable PostgreSQL (deselect with -m 'not db')", +] + +[tool.ruff] +line-length = 100 +src = ["src"] + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] diff --git a/server/src/poorbird/__init__.py b/server/src/poorbird/__init__.py new file mode 100644 index 0000000..3dc1f76 --- /dev/null +++ b/server/src/poorbird/__init__.py @@ -0,0 +1 @@ +__version__ = "0.1.0" diff --git a/server/src/poorbird/api/__init__.py b/server/src/poorbird/api/__init__.py new file mode 100644 index 0000000..b94a1e8 --- /dev/null +++ b/server/src/poorbird/api/__init__.py @@ -0,0 +1,3 @@ +from .app import create_app + +__all__ = ["create_app"] diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py new file mode 100644 index 0000000..53c86a5 --- /dev/null +++ b/server/src/poorbird/api/app.py @@ -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() diff --git a/server/src/poorbird/api/deps.py b/server/src/poorbird/api/deps.py new file mode 100644 index 0000000..149f7ec --- /dev/null +++ b/server/src/poorbird/api/deps.py @@ -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 diff --git a/server/src/poorbird/api/routes/__init__.py b/server/src/poorbird/api/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/server/src/poorbird/api/routes/health.py b/server/src/poorbird/api/routes/health.py new file mode 100644 index 0000000..69fb70e --- /dev/null +++ b/server/src/poorbird/api/routes/health.py @@ -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"} diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py new file mode 100644 index 0000000..a60bf63 --- /dev/null +++ b/server/src/poorbird/cli.py @@ -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()) diff --git a/server/src/poorbird/config.py b/server/src/poorbird/config.py new file mode 100644 index 0000000..11b40c4 --- /dev/null +++ b/server/src/poorbird/config.py @@ -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() diff --git a/server/src/poorbird/db.py b/server/src/poorbird/db.py new file mode 100644 index 0000000..a479968 --- /dev/null +++ b/server/src/poorbird/db.py @@ -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 diff --git a/server/src/poorbird/logging_setup.py b/server/src/poorbird/logging_setup.py new file mode 100644 index 0000000..18bd27b --- /dev/null +++ b/server/src/poorbird/logging_setup.py @@ -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") diff --git a/server/src/poorbird/models/__init__.py b/server/src/poorbird/models/__init__.py new file mode 100644 index 0000000..ffc3ae9 --- /dev/null +++ b/server/src/poorbird/models/__init__.py @@ -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", +] diff --git a/server/src/poorbird/models/base.py b/server/src/poorbird/models/base.py new file mode 100644 index 0000000..c815f35 --- /dev/null +++ b/server/src/poorbird/models/base.py @@ -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) diff --git a/server/src/poorbird/models/captures.py b/server/src/poorbird/models/captures.py new file mode 100644 index 0000000..f09fb41 --- /dev/null +++ b/server/src/poorbird/models/captures.py @@ -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/.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), +) diff --git a/server/src/poorbird/models/devices.py b/server/src/poorbird/models/devices.py new file mode 100644 index 0000000..c1be8a9 --- /dev/null +++ b/server/src/poorbird/models/devices.py @@ -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) diff --git a/server/src/poorbird/models/ops.py b/server/src/poorbird/models/ops.py new file mode 100644 index 0000000..e65845c --- /dev/null +++ b/server/src/poorbird/models/ops.py @@ -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)) diff --git a/server/src/poorbird/models/users.py b/server/src/poorbird/models/users.py new file mode 100644 index 0000000..4393d75 --- /dev/null +++ b/server/src/poorbird/models/users.py @@ -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)) diff --git a/server/src/poorbird/worker/__init__.py b/server/src/poorbird/worker/__init__.py new file mode 100644 index 0000000..9c4f0db --- /dev/null +++ b/server/src/poorbird/worker/__init__.py @@ -0,0 +1,3 @@ +from .main import run + +__all__ = ["run"] diff --git a/server/src/poorbird/worker/handlers.py b/server/src/poorbird/worker/handlers.py new file mode 100644 index 0000000..0b3f315 --- /dev/null +++ b/server/src/poorbird/worker/handlers.py @@ -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}) diff --git a/server/src/poorbird/worker/main.py b/server/src/poorbird/worker/main.py new file mode 100644 index 0000000..0a68662 --- /dev/null +++ b/server/src/poorbird/worker/main.py @@ -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 diff --git a/server/src/poorbird/worker/queue.py b/server/src/poorbird/worker/queue.py new file mode 100644 index 0000000..ecdda58 --- /dev/null +++ b/server/src/poorbird/worker/queue.py @@ -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 diff --git a/server/tests/conftest.py b/server/tests/conftest.py new file mode 100644 index 0000000..df0f4a3 --- /dev/null +++ b/server/tests/conftest.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import os + +import pytest + +# Set before anything imports poorbird.config, whose Settings are cached. +os.environ.setdefault("POORBIRD_LOG_LEVEL", "WARNING") +os.environ.setdefault("POORBIRD_IMAGE_ROOT", "/tmp/poorbird-test/images") +os.environ.setdefault("POORBIRD_THUMB_ROOT", "/tmp/poorbird-test/thumbs") +os.environ.setdefault("POORBIRD_STATE_DIR", "/tmp/poorbird-test/state") + + +def database_is_reachable() -> bool: + try: + from sqlalchemy import text + + from poorbird.db import engine + + with engine.connect() as conn: + conn.execute(text("SELECT 1")) + return True + except Exception: + return False + + +needs_db = pytest.mark.skipif( + not database_is_reachable(), + reason="no reachable PostgreSQL (set POORBIRD_DATABASE_URL)", +) + + +@pytest.fixture(scope="session") +def client(): + from fastapi.testclient import TestClient + + from poorbird.api.app import create_app + + with TestClient(create_app()) as c: + yield c diff --git a/server/tests/test_config.py b/server/tests/test_config.py new file mode 100644 index 0000000..14192a2 --- /dev/null +++ b/server/tests/test_config.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from poorbird.config import Settings + + +def test_every_setting_reads_from_the_environment(monkeypatch): + """Phase 1.2: no path, host or secret may be baked into code.""" + monkeypatch.setenv("POORBIRD_DATABASE_URL", "postgresql+psycopg://u:p@10.0.0.5:5432/db") + monkeypatch.setenv("POORBIRD_IMAGE_ROOT", "/mnt/elsewhere/images") + monkeypatch.setenv("POORBIRD_API_PORT", "9999") + monkeypatch.setenv("POORBIRD_ENROLL_SECRET", "deadbeef") + + s = Settings(_env_file=None) + + assert s.database_url.endswith("@10.0.0.5:5432/db") + assert str(s.image_root).endswith("images") + assert s.api_port == 9999 + assert s.enroll_secret_is_set + + +def test_database_url_is_tcp_not_a_unix_socket(): + """A Unix socket is the one genuinely container-hostile choice.""" + s = Settings(_env_file=None) + assert "@" in s.database_url and ":" in s.database_url.rpartition("@")[2] + assert "/var/run/postgresql" not in s.database_url + + +def test_enroll_secret_is_not_leaked_by_repr(): + s = Settings(_env_file=None, enroll_secret="hunter2") + assert "hunter2" not in repr(s) diff --git a/server/tests/test_health.py b/server/tests/test_health.py new file mode 100644 index 0000000..3b2ed7f --- /dev/null +++ b/server/tests/test_health.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from conftest import needs_db + + +def test_health_answers_even_without_a_database(client): + """The WebUI banner must be able to render a degraded system.""" + r = client.get("/api/v1/health") + assert r.status_code == 200 + body = r.json() + assert body["status"] in {"ok", "degraded"} + assert "database" in body + assert "disk" in body + assert body["version"] + + +@needs_db +def test_health_is_ok_with_a_database(client): + body = client.get("/api/v1/health").json() + assert body["status"] == "ok" + assert body["database"]["ok"] is True + + +@needs_db +def test_healthz_is_200_when_the_database_is_up(client): + assert client.get("/healthz").status_code == 200 + + +def test_openapi_is_served(client): + assert client.get("/openapi.json").status_code == 200 diff --git a/server/tests/test_queue.py b/server/tests/test_queue.py new file mode 100644 index 0000000..0dd8a55 --- /dev/null +++ b/server/tests/test_queue.py @@ -0,0 +1,100 @@ +"""Queue behaviour. Needs a real PostgreSQL: SKIP LOCKED has no equivalent +anywhere else, and mocking it would test nothing. +""" + +from __future__ import annotations + +import pytest +from conftest import needs_db + +pytestmark = [pytest.mark.db, needs_db] + + +@pytest.fixture +def session(): + from poorbird.db import SessionLocal + from poorbird.models import Job + + with SessionLocal() as s: + yield s + s.query(Job).filter(Job.kind.like("test_%")).delete(synchronize_session=False) + s.commit() + + +def test_claim_returns_a_queued_job_then_nothing(session): + from poorbird.worker import queue + + queue.enqueue(session, "test_noop", {"n": 1}) + session.commit() + + claimed = queue.claim(session) + assert claimed is not None + assert claimed["kind"] == "test_noop" + assert claimed["payload"] == {"n": 1} + assert claimed["attempts"] == 1 + + queue.complete(session, claimed["id"]) + + # Same job must not come back. + again = queue.claim(session) + assert again is None or again["kind"] != "test_noop" + + +def test_a_second_worker_skips_a_locked_row_instead_of_blocking(session): + """The whole point of FOR UPDATE SKIP LOCKED.""" + from poorbird.db import SessionLocal + from poorbird.worker import queue + + queue.enqueue(session, "test_only_one") + session.commit() + + first = queue.claim(session) + assert first is not None + + with SessionLocal() as other: + assert queue.claim(other) is None + + queue.complete(session, first["id"]) + + +def test_failure_retries_until_max_attempts_then_parks(session): + from poorbird.models import Job + from poorbird.worker import queue + + job = queue.enqueue(session, "test_doomed", max_attempts=2) + session.commit() + job_id = job.id + + for _ in range(2): + claimed = queue.claim(session) + assert claimed is not None + queue.fail(session, claimed["id"], "boom", retry_in_s=0) + + session.expire_all() + parked = session.get(Job, job_id) + assert parked.status == "failed" + assert parked.attempts == 2 + assert "boom" in parked.last_error + + +def test_stale_running_jobs_are_reclaimed(session): + from sqlalchemy import text + + from poorbird.models import Job + from poorbird.worker import queue + + job = queue.enqueue(session, "test_orphan") + session.commit() + claimed = queue.claim(session) + assert claimed is not None + + # Pretend the worker died an hour ago. + session.execute( + text("UPDATE jobs SET locked_at = now() - interval '1 hour' WHERE id = :id"), + {"id": job.id}, + ) + session.commit() + + assert queue.requeue_stale(session, older_than_s=60) >= 1 + session.expire_all() + assert session.get(Job, job.id).status == "queued" diff --git a/server/tests/test_schema_matches_models.py b/server/tests/test_schema_matches_models.py new file mode 100644 index 0000000..fe97782 --- /dev/null +++ b/server/tests/test_schema_matches_models.py @@ -0,0 +1,68 @@ +"""Guard the baseline migration against the models. + +Migration 0001 builds the schema from ``Base.metadata`` (see its docstring). +That is only safe if something checks it, so: migrate a scratch database, then +ask Alembic to autogenerate against it and assert the diff is empty. + +This test keeps working after 0001 is replaced by explicit DDL, and it is what +catches "added a column to the model, forgot the migration" from Phase 2 on. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from conftest import needs_db + +pytestmark = [pytest.mark.db, needs_db] + + +def test_migrated_schema_matches_the_models(): + from alembic.autogenerate import compare_metadata + from alembic.migration import MigrationContext + from sqlalchemy import create_engine, text + + from poorbird.config import get_settings + from poorbird.db import engine + from poorbird.models import Base + + scratch = "poorbird_schema_check" + + # CREATE DATABASE cannot run inside a transaction block. + with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"')) + conn.execute(text(f'CREATE DATABASE "{scratch}"')) + + url = get_settings().database_url + scratch_url = url.rsplit("/", 1)[0] + "/" + scratch + scratch_engine = create_engine(scratch_url) + + try: + # Apply the real migration chain, exactly as `poorbird migrate` would. + with scratch_engine.begin() as conn: + from alembic import command + from alembic.config import Config + + cfg = Config() + cfg.set_main_option( + "script_location", str(Path(__file__).resolve().parents[1] / "migrations") + ) + cfg.set_main_option("sqlalchemy.url", scratch_url) + cfg.attributes["connection"] = conn + command.upgrade(cfg, "head") + + with scratch_engine.connect() as conn: + ctx = MigrationContext.configure( + conn, + opts={"compare_type": True, "compare_server_default": True}, + ) + diff = compare_metadata(ctx, Base.metadata) + + # alembic_version is Alembic's own bookkeeping, not part of the models. + diff = [d for d in diff if "alembic_version" not in str(d)] + assert diff == [], f"schema has drifted from the models:\n{diff}" + finally: + scratch_engine.dispose() + with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"'))