Files
Hello/server/src/poorbird/api/routes/ingest.py
T
Thomas KarnerandClaude Opus 5 ec9ef9b3a6 Add the thumbnail worker, and stop tests leaking jobs (Phase 2)
Captures now get a WebP thumbnail: 400px on the long edge, written to
thumbs/<uuid>_400.webp (SPEC 3.3). /ingest enqueues the job in the same
transaction as the capture row, so the worker never sees a job for a capture
that was rolled back, and decoding stays off the request path - it is the one
genuinely expensive part of a capture, and the device is waiting with a burst
still to upload.

api/images.py moves up to poorbird/images.py. Both sides use it now, and a
worker importing from api would be the wrong way round. The split by cost
stays: everything the ingest path touches still reads nine bytes of JPEG
header, and Pillow appears only in the thumbnail half.

Handler behaviour is about which failures are worth retrying:

  - An undecodable frame returns rather than raises. The handler contract
    makes a raise mean "retry", and a frame that will never decode should not
    spend three attempts proving it. Logged, thumb_path left NULL.
  - A missing source file raises, because it should be there and a mount that
    has not come back yet is worth retrying for.
  - A capture deleted between enqueue and run is not an error. Retention will
    do that routinely in Phase 5.
  - A malformed payload is validated with a Pydantic model and recorded, not
    retried (SEC-003 applied to a job payload).
  - Never upscales: blowing a 100px frame up to 400px produces a blurry lie.
  - Fills in width/height when the ingest header parse could not. This is the
    first full decode, so it is the chance to fix that.

Verified end to end against a real device row, a real HTTP ingest and the
real worker dispatch path - claim, _run_one, complete - not just the handler
called directly: 1600x1200 JPEG in, WEBP 400x300 on disk, job marked done.
That run is what caught the rest of this commit.

Tests were leaking jobs into the shared queue, which broke test_queue.py once
/ingest started enqueuing. Three separate causes, all the same shape as the
teardown bug fixed in 269a6ea:

  - test_ingest cleaned captures but not their thumbnail jobs, and one test
    hand-rolled teardown for a second device and forgot half of it. Devices
    now come from a fixture that cleans frames, captures and jobs for every
    device a test makes.
  - test_queue claimed jobs without checking they were its own, so a leftover
    thumbnail job could be failed on its behalf, and one test claimed a
    second job to prove the first did not recur and then stranded it in
    'running' forever. It now enqueues at a priority that wins, asserts every
    claim is its own, and releases anything else it touches.

The suite now runs twice in a row leaving zero jobs behind, which is the
assertion that actually matters here.

Tests: 175 -> 193.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-21 14:49:15 +02:00

221 lines
8.2 KiB
Python

"""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 ...images import (
MAX_IMAGE_BYTES,
jpeg_dimensions,
looks_like_jpeg,
relative_image_path,
write_atomically,
)
from ...models.captures import Capture
from ...worker.queue import enqueue
from .. import ratelimit
from ..deps import DbDep, DeviceDep, SettingsDep
from ..envelope import build_envelope
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"],
dependencies=[Depends(ratelimit.by_device("ingest", ratelimit.INGEST))],
)
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 job below. NULL means "not yet", which
# the gallery has to handle regardless: a capture is visible the
# moment it lands, not once it has been 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
# Off the request path on purpose: decoding a frame to resize it is the
# one genuinely expensive thing about a capture, and the device is
# waiting on this response with a burst still to upload. Enqueued in the
# same transaction as the row, so the worker never sees a job for a
# capture that was rolled back.
enqueue(db, "thumbnail", {"capture_id": str(capture_id)})
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