From 6223d960c4e26b8b69df9dda211592a643406fa5 Mon Sep 17 00:00:00 2001 From: Thomas Karner Date: Mon, 21 Sep 2026 13:08:05 +0200 Subject: [PATCH] Add POST /api/v1/ingest (Phase 2) Raw JPEG body with metadata in headers, which is API.md's deliberate deviation from SPEC 4.1: multipart would make the device assemble a second buffer purely to add a wrapper the server strips immediately. REVIEW.AI.md's reference code implemented the multipart version and would not have matched the firmware at all. Returns the same envelope as /heartbeat, so a capture that was going to happen anyway also drains the command queue. api/images.py holds the storage helpers, with no imaging library. Reading nine bytes of JPEG header for the dimensions beats decoding a frame on a path that runs once per capture, and the same parse doubles as content validation: the magic bytes decide whether this is a JPEG, not the Content-Type header. Pillow belongs in the thumbnail worker, off the request path, where the image has to be decoded anyway. Ordering and failure: - The file is written first, through a temp file in the same directory and an atomic rename, so a half-written JPEG is never visible at its final path. The row is inserted second, and the file is removed if the commit fails. The reverse order would be worse: a row pointing at a missing image is a broken gallery entry, while a stray file is invisible and sweepable. - A body that is not a JPEG is 400, never 401, so the device does not read it as a credential problem and clear a good token. Unwritable storage is 503, because from the device's side it is transient. - 12MB cap mirrors the Caddyfile, since a limit that only exists in the proxy is not a limit in development. Identical bytes from the same device are treated as a retry and return the original capture, with the command queue still attached. The device cannot tell a lost response from a real failure, and two genuine frames never collide - sensor noise alone makes every capture unique. Checked in the application rather than with a unique constraint, so a freak collision loses a frame instead of raising. X-Captured-At: 0 means the clock is unsynced and is stored as NULL. An epoch date would bury the frame at the bottom of every chronological view forever. received_at stays authoritative either way (SPEC C7), and is what dates the YYYY/MM/DD path. NOT included, and deliberately: the thumbnail job. An unknown job kind is failed immediately by the worker (worker/main.py:35), so enqueuing one now would produce a failed job per capture. thumb_path stays NULL, which the gallery has to handle regardless - a capture is visible when it lands, not once it is processed. Thumbnails are the next unit of work and need Pillow. Tests: 122 -> 148. Verified by disabling dedup and by removing the captured-at-zero guard: the two corresponding tests fail, as intended. Co-Authored-By: Claude Opus 5 (1M context) --- server/src/poorbird/api/app.py | 5 +- server/src/poorbird/api/images.py | 104 ++++++ server/src/poorbird/api/routes/ingest.py | 210 ++++++++++++ server/src/poorbird/api/schemas.py | 4 + server/tests/test_ingest.py | 386 +++++++++++++++++++++++ 5 files changed, 707 insertions(+), 2 deletions(-) create mode 100644 server/src/poorbird/api/images.py create mode 100644 server/src/poorbird/api/routes/ingest.py create mode 100644 server/tests/test_ingest.py diff --git a/server/src/poorbird/api/app.py b/server/src/poorbird/api/app.py index 10418e4..4136fcb 100644 --- a/server/src/poorbird/api/app.py +++ b/server/src/poorbird/api/app.py @@ -8,7 +8,7 @@ from fastapi import FastAPI from .. import __version__ from ..config import get_settings from ..logging_setup import configure_logging -from .routes import commands, conditions, device_config, enroll, health +from .routes import commands, conditions, device_config, enroll, health, ingest log = logging.getLogger(__name__) @@ -49,8 +49,9 @@ def create_app() -> FastAPI: app.include_router(conditions.router, prefix=API_PREFIX) app.include_router(device_config.router, prefix=API_PREFIX) app.include_router(commands.router, prefix=API_PREFIX) + app.include_router(ingest.router, prefix=API_PREFIX) - # Still to come: /ingest, /firmware/{version}.bin. + # Still to come: /firmware/{version}.bin. # Phase 3 mounts the UI endpoints. return app diff --git a/server/src/poorbird/api/images.py b/server/src/poorbird/api/images.py new file mode 100644 index 0000000..d285d28 --- /dev/null +++ b/server/src/poorbird/api/images.py @@ -0,0 +1,104 @@ +"""Where capture bytes go, and the little we can learn from them. + +Deliberately no imaging library. Everything here needs to work on the ingest +path, which runs once per frame and must not be the reason a burst is slow. +Decoding a JPEG to learn its dimensions would be wasteful when the header +already says so in nine bytes. Pillow belongs in the thumbnail worker, off the +request path, where the image has to be decoded anyway. +""" + +from __future__ import annotations + +import os +import uuid +from datetime import datetime +from pathlib import Path + +# Matches `request_body max_size 12MB` in deploy/Caddyfile. Enforced here too, +# because Caddy is not in front of the app in development and a limit that +# only exists in the proxy is not a limit. +MAX_IMAGE_BYTES = 12 * 1024 * 1024 + +# SOI. A JPEG always starts FF D8 FF; anything else is not one, whatever the +# Content-Type header claims. +_JPEG_MAGIC = b"\xff\xd8\xff" + +# Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG) and +# CC (DAC) share the range but are not SOF. +_SOF_MARKERS = frozenset( + {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} +) + + +def looks_like_jpeg(data: bytes) -> bool: + return data.startswith(_JPEG_MAGIC) + + +def jpeg_dimensions(data: bytes) -> tuple[int, int] | None: + """(width, height) from the JPEG header, or None if it cannot be read. + + Walks the segment chain to the first SOF. None is not an error: a frame + whose dimensions we cannot parse is still a frame worth keeping, and the + columns are nullable for exactly that reason. + """ + i, n = 2, len(data) + + while i + 3 < n: + if data[i] != 0xFF: + i += 1 + continue + + marker = data[i + 1] + + # Standalone markers: no length field follows. + if marker == 0x01 or 0xD0 <= marker <= 0xD8: + i += 2 + continue + if marker == 0xD9: # EOI + break + + segment_length = int.from_bytes(data[i + 2 : i + 4], "big") + if segment_length < 2: + break # malformed; a shorter length would not advance + + if marker in _SOF_MARKERS: + if i + 9 > n: + break + height = int.from_bytes(data[i + 5 : i + 7], "big") + width = int.from_bytes(data[i + 7 : i + 9], "big") + return (width, height) if width and height else None + + i += 2 + segment_length + + return None + + +def relative_image_path(capture_id: uuid.UUID, received_at: datetime) -> str: + """``YYYY/MM/DD/.jpg`` (SPEC 3.3). + + Dated by ``received_at``, never by the device clock: the device may be + unsynced and report nothing at all, and SPEC C7 makes server time + authoritative. Stored relative to POORBIRD_IMAGE_ROOT so the root stays a + deployment concern -- Caddy resolves the same relative path against the + same configured root when it serves the bytes. + """ + return f"{received_at:%Y/%m/%d}/{capture_id}.jpg" + + +def write_atomically(destination: Path, data: bytes) -> None: + """Write via a temporary file in the same directory, then rename. + + A half-written JPEG is indistinguishable from a whole one until something + tries to decode it, so the file must never be visible at its final path + until it is complete. Same directory keeps the rename on one filesystem, + which is what makes it atomic. + """ + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_name(f".{destination.name}.part") + + try: + temporary.write_bytes(data) + os.replace(temporary, destination) + except BaseException: + temporary.unlink(missing_ok=True) + raise diff --git a/server/src/poorbird/api/routes/ingest.py b/server/src/poorbird/api/routes/ingest.py new file mode 100644 index 0000000..bbbc897 --- /dev/null +++ b/server/src/poorbird/api/routes/ingest.py @@ -0,0 +1,210 @@ +"""POST /api/v1/ingest -- a captured frame. + +**Deviation from SPEC 4.1, and a deliberate one.** The spec says +multipart/form-data with the image and a JSON metadata part. The firmware +sends the raw JPEG as the body with the metadata in headers, because +multipart would make the device assemble a second buffer purely to add a +wrapper the server strips immediately; the raw body hands the framebuffer +pointer straight to the HTTP client (firmware/API.md). REVIEW.AI.md's +reference code implemented the multipart version and would not have matched +the firmware at all. + +Returns the same envelope as /heartbeat, so a capture that was going to +happen anyway also delivers the command queue at no extra cost. +""" + +from __future__ import annotations + +import hashlib +import logging +import uuid +from datetime import UTC, datetime +from typing import Annotated + +from fastapi import APIRouter, Body, Depends, Header, HTTPException, status +from pydantic import ValidationError +from sqlalchemy import select + +from ...models.captures import Capture +from ..deps import DbDep, DeviceDep, SettingsDep +from ..envelope import build_envelope +from ..images import ( + MAX_IMAGE_BYTES, + jpeg_dimensions, + looks_like_jpeg, + relative_image_path, + write_atomically, +) +from ..schemas import Envelope, IngestMeta + +log = logging.getLogger(__name__) + +router = APIRouter() + + +def ingest_meta( + x_trigger: Annotated[str, Header()] = "radar", + x_burst_id: Annotated[str | None, Header()] = None, + x_burst_index: Annotated[int | None, Header()] = None, + x_burst_count: Annotated[int | None, Header()] = None, + x_pre_trigger: Annotated[int, Header()] = 0, + x_captured_at: Annotated[int, Header()] = 0, + x_frame_seq: Annotated[int | None, Header()] = None, + x_radar_state: Annotated[int | None, Header()] = None, + x_radar_distance_cm: Annotated[int | None, Header()] = None, + x_radar_energy: Annotated[int | None, Header()] = None, + x_rssi: Annotated[int | None, Header()] = None, +) -> IngestMeta: + """Validate the header metadata into one model (REVIEW SEC-003).""" + try: + return IngestMeta( + trigger=x_trigger, + burst_id=x_burst_id or None, + burst_index=x_burst_index, + burst_count=x_burst_count, + pre_trigger=bool(x_pre_trigger), + # X-Captured-At: 0 means the device clock is unsynced. That is + # NULL, not 1970 -- storing an epoch date here would put the frame + # at the bottom of every chronological view forever (API.md). + captured_at=( + datetime.fromtimestamp(x_captured_at / 1000, UTC) if x_captured_at > 0 else None + ), + frame_seq=x_frame_seq, + radar_state=x_radar_state, + radar_distance_cm=x_radar_distance_cm, + radar_energy=x_radar_energy, + rssi=x_rssi, + ) + except ValidationError as exc: + # A dependency raising ValidationError would otherwise surface as a + # 500. The metadata is client input; it deserves a 422. + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, + detail=exc.errors(include_url=False), + ) from None + + +@router.post( + "/ingest", + status_code=status.HTTP_201_CREATED, + response_model=Envelope, + response_model_exclude_none=True, + summary="Accept a captured frame; returns the command envelope", + tags=["captures"], +) +def ingest( + db: DbDep, + device: DeviceDep, + settings: SettingsDep, + meta: Annotated[IngestMeta, Depends(ingest_meta)], + body: Annotated[bytes, Body(media_type="image/jpeg")] = b"", +) -> Envelope: + if not body: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="empty body") + if len(body) > MAX_IMAGE_BYTES: + raise HTTPException( + status_code=status.HTTP_413_CONTENT_TOO_LARGE, + detail=f"image exceeds {MAX_IMAGE_BYTES} bytes", + ) + # Trust the bytes, not the Content-Type. 400 and not 401: the device must + # not read this as a credential problem and clear a perfectly good token. + if not looks_like_jpeg(body): + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="body is not a JPEG") + + digest = hashlib.sha256(body).hexdigest() + + # The device retries an upload whose response was lost, and it cannot tell + # that case from a genuine failure. Identical bytes from the same device + # are that retry -- two real frames never collide, since sensor noise + # alone makes every capture unique. Returning the original capture keeps + # ingest idempotent instead of filling the gallery with duplicates. + # + # Scoped to the device, and checked in the application rather than with a + # unique constraint: a genuine collision should lose a frame, not 500. + # Burst uploads are sequential (API.md), so there is no race to lose. + existing = db.scalar( + select(Capture).where(Capture.device_id == device.id, Capture.sha256 == digest) + ) + if existing is not None: + log.info( + "ingest de-duplicated", + extra={"device_id": device.id, "capture_id": str(existing.id)}, + ) + envelope = build_envelope(db, device, capture_id=str(existing.id)) + db.commit() + return envelope + + capture_id = uuid.uuid4() + received_at = datetime.now(UTC) + relative = relative_image_path(capture_id, received_at) + destination = settings.image_root / relative + + try: + write_atomically(destination, body) + except OSError as exc: + # Disk full, root not mounted, permissions. 503 rather than 500: it is + # transient from the device's point of view and it should retry. + log.error("cannot write capture", extra={"path": str(destination), "error": str(exc)}) + raise HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="image storage unavailable", + ) from None + + dimensions = jpeg_dimensions(body) + + capture = Capture( + id=capture_id, + device_id=device.id, + path=relative, + # Filled in by the thumbnail worker, which does not exist yet. A NULL + # here means "no thumbnail yet", which the gallery must handle anyway: + # a capture is visible the moment it lands, not once it is processed. + thumb_path=None, + sha256=digest, + width=dimensions[0] if dimensions else None, + height=dimensions[1] if dimensions else None, + bytes=len(body), + captured_at_device=meta.captured_at, + received_at=received_at, + trigger=meta.trigger, + burst_id=meta.burst_id, + burst_index=meta.burst_index, + burst_count=meta.burst_count, + pre_trigger=meta.pre_trigger, + frame_seq=meta.frame_seq, + radar_state=meta.radar_state, + radar_distance_cm=meta.radar_distance_cm, + radar_energy=meta.radar_energy, + rssi=meta.rssi, + ) + db.add(capture) + + device.last_seen_at = received_at + if meta.rssi is not None: + device.rssi = meta.rssi + + envelope = build_envelope(db, device, capture_id=str(capture_id)) + + try: + db.commit() + except Exception: + # The file is already on disk. Remove it rather than leave an orphan + # that nothing references. The reverse order -- row first, file second + # -- would be worse: a row pointing at a missing image is a broken + # gallery entry, whereas a stray file is invisible and sweepable. + db.rollback() + destination.unlink(missing_ok=True) + raise + + log.info( + "capture ingested", + extra={ + "device_id": device.id, + "capture_id": str(capture_id), + "bytes": len(body), + "trigger": meta.trigger, + "pre_trigger": meta.pre_trigger, + }, + ) + + return envelope diff --git a/server/src/poorbird/api/schemas.py b/server/src/poorbird/api/schemas.py index 5def750..bc189d5 100644 --- a/server/src/poorbird/api/schemas.py +++ b/server/src/poorbird/api/schemas.py @@ -137,6 +137,10 @@ class IngestMeta(BaseModel): radar_state: Annotated[int | None, Field(ge=0, le=3)] = None radar_distance_cm: int | None = None radar_energy: Annotated[int | None, Field(ge=0, le=100)] = None + # From X-Rssi, one of the common headers on every authenticated request + # rather than an ingest-specific one, but captures.rssi is the column it + # belongs in: signal strength at the moment this frame was uploaded. + rssi: int | None = None # --- device conditions: one body, two endpoints ----------------------------- diff --git a/server/tests/test_ingest.py b/server/tests/test_ingest.py new file mode 100644 index 0000000..f6b75af --- /dev/null +++ b/server/tests/test_ingest.py @@ -0,0 +1,386 @@ +"""POST /api/v1/ingest -- raw JPEG body, metadata in headers.""" + +from __future__ import annotations + +import hashlib +import io +import secrets +import struct +from pathlib import Path + +import pytest +from conftest import needs_db +from sqlalchemy import select + +from poorbird.api.deps import hash_credential, new_credential +from poorbird.api.images import jpeg_dimensions, looks_like_jpeg +from poorbird.config import get_settings +from poorbird.models.captures import Capture +from poorbird.models.devices import Device, DeviceCommand, DeviceStatus + + +def make_jpeg(width: int = 800, height: int = 600, noise: bytes = b"") -> bytes: + """A byte string with a valid SOI and SOF0, enough to be parsed as a JPEG. + + Not a decodable image: nothing on the ingest path decodes one, which is + the point of parsing the header rather than pulling in Pillow. + """ + out = io.BytesIO() + out.write(b"\xff\xd8\xff") # SOI + start of the next marker + out.write(b"\xe0") # APP0 + out.write(struct.pack(">H", 16)) + out.write(b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00") + out.write(b"\xff\xc0") # SOF0 + out.write(struct.pack(">H", 17)) + out.write(b"\x08") # precision + out.write(struct.pack(">HH", height, width)) + out.write(b"\x03\x01\x11\x00\x02\x11\x01\x03\x11\x01") + out.write(b"\xff\xd9") # EOI + out.write(noise) # makes the sha256 differ between frames + return out.getvalue() + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def device(db): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + + yield d, {"Authorization": f"Bearer {token}"} + + root = get_settings().image_root + for cap in db.scalars(select(Capture).where(Capture.device_id == d.id)): + (root / cap.path).unlink(missing_ok=True) + db.execute(Capture.__table__.delete().where(Capture.device_id == d.id)) + db.execute(DeviceStatus.__table__.delete().where(DeviceStatus.device_id == d.id)) + db.execute(DeviceCommand.__table__.delete().where(DeviceCommand.device_id == d.id)) + db.delete(db.get(Device, d.id)) + db.commit() + + +def post(client, auth, data=None, **headers): + h = {"Content-Type": "image/jpeg", **auth} + h.update({k.replace("_", "-"): str(v) for k, v in headers.items()}) + return client.post( + "/api/v1/ingest", content=data if data is not None else make_jpeg(), headers=h + ) + + +# --- the header parser, in isolation ---------------------------------------- + + +def test_jpeg_dimensions_reads_the_header(): + assert jpeg_dimensions(make_jpeg(1600, 1200)) == (1600, 1200) + assert jpeg_dimensions(make_jpeg(320, 240)) == (320, 240) + + +def test_jpeg_dimensions_gives_up_quietly_on_rubbish(): + """None is not an error: a frame we cannot measure is still worth keeping.""" + assert jpeg_dimensions(b"\xff\xd8\xff") is None + assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x10" + b"\x00" * 14) is None + assert jpeg_dimensions(b"") is None + + +def test_jpeg_dimensions_terminates_on_hostile_input(): + """A zero-length segment must not loop forever.""" + assert jpeg_dimensions(b"\xff\xd8\xff\xe0\x00\x00" + b"\x41" * 100) is None + assert jpeg_dimensions(b"\xff\xd8" + b"\xff" * 5000) is None + + +def test_magic_bytes_are_what_decide_it_is_a_jpeg(): + assert looks_like_jpeg(make_jpeg()) + assert not looks_like_jpeg(b"GIF89a") + assert not looks_like_jpeg(b"") + + +# --- the happy path --------------------------------------------------------- + + +@needs_db +def test_a_frame_is_stored_and_the_envelope_comes_back(client, device, db): + d, auth = device + r = post(client, auth, X_Trigger="radar", X_Burst_Id="a0b765-3-91204", X_Burst_Index=0) + + assert r.status_code == 201 + envelope = r.json() + assert envelope["capture_id"] + assert envelope["server_time"] > 1_700_000_000_000 + assert envelope["commands"] == [] + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert str(cap.id) == envelope["capture_id"] + assert cap.trigger == "radar" + assert cap.burst_id == "a0b765-3-91204" + assert cap.width == 800 and cap.height == 600 + + +@needs_db +def test_the_bytes_land_on_disk_under_a_dated_path(client, device, db): + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + assert post(client, auth, data=body).status_code == 201 + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + # Relative to the configured root, dated by received_at (SPEC 3.3). + assert cap.path == f"{cap.received_at:%Y/%m/%d}/{cap.id}.jpg" + assert not Path(cap.path).is_absolute() + + on_disk = get_settings().image_root / cap.path + assert on_disk.is_file() + assert on_disk.read_bytes() == body + assert cap.bytes == len(body) + assert cap.sha256 == hashlib.sha256(body).hexdigest() + + +@needs_db +def test_no_part_file_is_left_behind(client, device, db): + d, auth = device + post(client, auth) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + folder = (get_settings().image_root / cap.path).parent + assert not list(folder.glob(".*.part")) + + +@needs_db +def test_ingest_delivers_commands_like_heartbeat_does(client, device, db): + """Same envelope on purpose: a capture that was going to happen anyway + also drains the queue at no extra cost (SPEC 4.1).""" + d, auth = device + db.add(DeviceCommand(device_id=d.id, type="capture_now")) + db.commit() + + envelope = post(client, auth).json() + assert [c["type"] for c in envelope["commands"]] == ["capture_now"] + + +# --- the clock --------------------------------------------------------------- + + +@needs_db +def test_captured_at_zero_means_unsynced_not_1970(client, device, db): + """Storing an epoch date would bury the frame at the bottom of every + chronological view forever.""" + d, auth = device + post(client, auth, X_Captured_At=0) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.captured_at_device is None + assert cap.received_at is not None # server time stays authoritative + + +@needs_db +def test_a_synced_device_clock_is_recorded(client, device, db): + d, auth = device + post(client, auth, X_Captured_At=1758376267123) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.captured_at_device is not None + assert cap.captured_at_device.year == 2025 or cap.captured_at_device.year == 2026 + + +@needs_db +def test_received_at_is_server_time_regardless(client, device, db): + """SPEC C7. Even a device claiming to be in 1998.""" + d, auth = device + post(client, auth, X_Captured_At=915148800000) # 1999 + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.received_at.year >= 2026 + assert cap.path.startswith(f"{cap.received_at:%Y}") + + +# --- metadata --------------------------------------------------------------- + + +@needs_db +def test_pre_trigger_is_recorded(client, device, db): + """1 means the frame predates the trigger, out of the PSRAM ring -- often + the good one, because the bird is still arriving.""" + d, auth = device + post(client, auth, X_Pre_Trigger=1) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert cap.pre_trigger is True + + +@needs_db +def test_radar_and_signal_metadata_are_recorded(client, device, db): + d, auth = device + post( + client, + auth, + X_Radar_State=2, + X_Radar_Distance_Cm=180, + X_Radar_Energy=77, + X_Frame_Seq=42, + X_Rssi=-61, + ) + + cap = db.scalar(select(Capture).where(Capture.device_id == d.id)) + assert (cap.radar_state, cap.radar_distance_cm, cap.radar_energy) == (2, 180, 77) + assert cap.frame_seq == 42 + assert cap.rssi == -61 + + db.refresh(d) + assert d.rssi == -61 + assert d.last_seen_at is not None + + +@needs_db +def test_an_unknown_trigger_is_422(client, device): + _, auth = device + assert post(client, auth, X_Trigger="motion").status_code == 422 + + +@needs_db +def test_an_out_of_range_radar_state_is_422(client, device): + _, auth = device + assert post(client, auth, X_Radar_State=9).status_code == 422 + + +@needs_db +def test_the_trigger_defaults_when_the_header_is_absent(client, device, db): + d, auth = device + r = client.post( + "/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg", **auth} + ) + assert r.status_code == 201 + + +# --- retries ---------------------------------------------------------------- + + +@needs_db +def test_the_same_frame_twice_is_one_capture(client, device, db): + """The device retries an upload whose response was lost and cannot tell + that case from a real failure.""" + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + + first = post(client, auth, data=body).json() + second = post(client, auth, data=body).json() + + assert second["capture_id"] == first["capture_id"] + assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 1 + + +@needs_db +def test_a_retry_still_receives_pending_commands(client, device, db): + """The retry is still the device asking; it must not lose the queue.""" + d, auth = device + body = make_jpeg(noise=secrets.token_bytes(8)) + post(client, auth, data=body) + + db.add(DeviceCommand(device_id=d.id, type="reboot")) + db.commit() + + envelope = post(client, auth, data=body).json() + assert [c["type"] for c in envelope["commands"]] == ["reboot"] + + +@needs_db +def test_different_frames_are_separate_captures(client, device, db): + """Frames in a burst differ by sensor noise alone, so they must not + collapse into one.""" + d, auth = device + post(client, auth, data=make_jpeg(noise=b"frame-one")) + post(client, auth, data=make_jpeg(noise=b"frame-two")) + + assert len(db.scalars(select(Capture).where(Capture.device_id == d.id)).all()) == 2 + + +@needs_db +def test_one_devices_frame_does_not_deduplicate_against_anothers(client, device, db): + d, auth = device + other_token = new_credential() + other = Device( + device_uid=secrets.token_hex(6), + name="other", + token_hash=hash_credential(other_token), + enabled=True, + ) + db.add(other) + db.commit() + + body = make_jpeg(noise=b"identical") + a = post(client, auth, data=body).json() + b = post(client, {"Authorization": f"Bearer {other_token}"}, data=body).json() + assert a["capture_id"] != b["capture_id"] + + root = get_settings().image_root + for cap in db.scalars(select(Capture).where(Capture.device_id == other.id)): + (root / cap.path).unlink(missing_ok=True) + db.execute(Capture.__table__.delete().where(Capture.device_id == other.id)) + db.delete(db.get(Device, other.id)) + db.commit() + + +# --- refusals --------------------------------------------------------------- + + +@needs_db +def test_an_empty_body_is_400(client, device): + _, auth = device + assert post(client, auth, data=b"").status_code == 400 + + +@needs_db +def test_a_body_that_is_not_a_jpeg_is_400_not_401(client, device): + """400 specifically: a 401 would make the device clear a good token.""" + _, auth = device + r = post(client, auth, data=b"GIF89a" + b"\x00" * 100) + assert r.status_code == 400 + + +@needs_db +def test_an_oversized_body_is_413(client, device): + """Mirrors `request_body max_size 12MB` in the Caddyfile, because a limit + that only exists in the proxy is not a limit.""" + _, auth = device + assert post(client, auth, data=make_jpeg() + b"\x00" * (12 * 1024 * 1024)).status_code == 413 + + +@needs_db +def test_nothing_is_written_when_the_body_is_rejected(client, device, db): + """No row, and nothing left on disk either.""" + d, auth = device + before = set(get_settings().image_root.rglob("*.jpg")) + + assert post(client, auth, data=b"not a jpeg at all").status_code == 400 + + assert db.scalars(select(Capture).where(Capture.device_id == d.id)).all() == [] + assert set(get_settings().image_root.rglob("*.jpg")) == before + + +@needs_db +def test_ingest_requires_a_bearer_token(client): + assert ( + client.post( + "/api/v1/ingest", content=make_jpeg(), headers={"Content-Type": "image/jpeg"} + ).status_code + == 401 + ) + + +@needs_db +def test_a_disabled_device_cannot_ingest(client, device, db): + d, auth = device + d.enabled = False + db.commit() + assert post(client, auth).status_code == 403