The server half of the gallery. Listing and delivery land together because neither is useful alone: a listing with no way to fetch bytes renders empty tiles, and image serving with nothing to enumerate has no entry point. Delivery follows the design deploy/Caddyfile already committed to. The app authorises, then answers empty with X-Accel-Redirect and Caddy reads the file, so a 3 MB JPEG never occupies a Python worker thread. There is no Caddy in development, though, and that header reaching a browser is an empty 200 - every image in the gallery blank, with nothing to explain it. So POORBIRD_SERVE_IMAGES_DIRECTLY makes the app send the bytes instead. The important part is what that flag does NOT do: the authorisation is the same code either way, and the flag only changes how an already-authorised response is finished. A separate unauthenticated file route "only reachable in dev" is exactly the kind of thing that survives into production because it works, and this deliberately is not one. Both delivery paths refuse a path that escapes its root. captures.path is written by our own ingest code so it should never happen, but "should never" is not a security control and the cost of being wrong is serving an arbitrary file off the server. The handoff path needs it just as much as the direct one - a traversal in the header makes *Caddy* read the file, where the app never opens it at all. Keyset paging, not OFFSET. At 5000 captures a day OFFSET gets slower the further back you scroll, which is the direction a gallery scrolls. The cursor carries (received_at, id), and the id is in there for a specific reason: a burst arrives inside the same fraction of a second, so ties are normal rather than exotic, and a timestamp-only cursor would either repeat rows or skip them. A gallery that loses a frame while you scroll is one you cannot trust. Page size is fetched as limit + 1 rather than counted. It answers "is there another page" without a COUNT over the whole filtered set, and the test for a full final page covers the off-by-one that trick invites. Filters cover the columns that have data: device, received-date range, kept, reviewed, pre_trigger, trigger. Taxon and tag filters are in TODO Phase 3 and deliberately absent - both need a join, and neither has anything to join to until the observation editor and a seeded taxa table exist. A filter that can only ever return nothing is worse than an absent one, because the UI offers it. Dates filter on received_at and never captured_at_device, which is NULL whenever the camera's clock was unsynced (API.md, X-Captured-At: 0). Filtering on it would silently drop exactly those frames. A missing thumbnail is 404 rather than a fallback to the full JPEG. The grid needs to tell "queued" from "never decoded" and show a placeholder; a silent fallback would make 200 tiles fetch a hundred times the bytes and still look like it worked. `poorbird check` now verifies the layout the handoff depends on: Caddy serves the PARENT of both roots, so they have to be siblings named images/ and thumbs/. Getting it wrong produces 404s from Caddy with nothing in the app's log, which is the kind of thing worth failing a preflight check over rather than discovering in a browser. One test-quality fix worth naming: two delivery tests were inheriting their mode from whatever server/.env happened to say, and broke the moment SERVE_IMAGES_DIRECTLY=true was added there for the dev server's benefit. Both modes are now named explicitly by a fixture, and conftest pins the production default - a test that changes its answer because of an untracked file is not testing the code. Verified against the real server and the six real captures already in the dev database: 401 before signing in, two pages of three with no overlap and correct termination, device_name garden-feeder on the detail, a 1572-byte WebP with RIFF magic and a 3469-byte JPEG with FFD8FF magic, and 401 on the image again immediately after logout. Mutation-tested the two claims that matter: removing the traversal guard and reducing the cursor to a timestamp each failed exactly the tests written for them. The traversal test escapes to a canary file that really exists just outside the root rather than to /etc/passwd, which does not exist on this machine and would have let the test pass for the wrong reason. Tests: 257 -> 293. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
poorBird server
Phases 1 and 2: configuration, schema, health, job queue, scheduler, and every endpoint the camera calls.
POST /api/v1/enroll X-Enroll-Secret, returns a bearer token
POST /api/v1/ingest raw JPEG body, metadata in headers
POST /api/v1/heartbeat conditions in, envelope + commands out
POST /api/v1/status conditions in, 204 out
GET /api/v1/config ~40 optional keys the device merges
POST /api/v1/commands/{id}/ack 204
GET /api/v1/firmware/{version}.bin OTA image, exact Content-Length
GET /api/v1/health
../firmware/API.md is the contract, and it wins over
anything here: it is what the firmware already does, and the camera is the side
that cannot be patched from a laptop once it is mounted outdoors. The operator
half — firmware upload, device management, the gallery — needs user auth and
arrives with Phase 3.
Stack per SPEC §6, deployed natively per ../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.
Developing on Windows (uv + Podman)
This is the verified setup on the dev machine. Python is managed by uv, so
nothing touches the system PATH or the registry, and PostgreSQL runs in a
throwaway Podman container. Neither changes how the project deploys — the app
still talks loopback TCP exactly as it will on the server.
winget install astral-sh.uv
uv python install 3.14.7
podman machine start
podman run -d --name poorbird-db -p 127.0.0.1:5432:5432 `
-e POSTGRES_USER=poorbird -e POSTGRES_PASSWORD=poorbird -e POSTGRES_DB=poorbird `
docker.io/library/postgres:17
cd server
uv venv --python 3.14.7
uv pip install -e ".[dev]"
# write .env (see the Linux section below; use Windows paths for the roots)
.venv\Scripts\poorbird check
.venv\Scripts\poorbird migrate
.venv\Scripts\python -m pytest
Later sessions only need podman machine start and podman start poorbird-db.
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.
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:
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
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;
a complete run is 12 passed, 0 skipped.
test_schema_matches_models.py creates and drops a poorbird_schema_check
database on the same server. It needs a role that may CREATE DATABASE.
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
images.py JPEG sniffing, atomic writes, thumbnails
api/ FastAPI app, device routes, auth, rate limiting
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.
Server defaults are compared through a normaliser. Postgres reflects a
varchar default as 'viewer'::character varying while the model renders
'viewer'. Compared literally, every string default in the schema reads as
drift forever — which trains you to ignore the one time it isn't. See
schema_compare.py; autogenerate and the drift test share it, so the tool and
the test can never disagree about what counts as a difference.
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 = falsemeans 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.
capturesis authoritative. The counters' value is the gap between captured and delivered, which is an upload-health signal.
Deploying for real
See deploy/INSTALL.md.