diff --git a/server/pyproject.toml b/server/pyproject.toml index 74fc449..64685f2 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -12,6 +12,9 @@ dependencies = [ "psycopg[binary]>=3.2", "alembic>=1.14", "apscheduler>=3.11,<4", + # Thumbnails only, and only in the worker. The ingest path deliberately + # does not decode images -- see poorbird/images.py. + "pillow>=11.0", ] [project.optional-dependencies] diff --git a/server/src/poorbird/api/routes/ingest.py b/server/src/poorbird/api/routes/ingest.py index 88b818a..1098b59 100644 --- a/server/src/poorbird/api/routes/ingest.py +++ b/server/src/poorbird/api/routes/ingest.py @@ -25,17 +25,18 @@ from fastapi import APIRouter, Body, Depends, Header, HTTPException, status from pydantic import ValidationError from sqlalchemy import select -from ...models.captures import Capture -from .. import ratelimit -from ..deps import DbDep, DeviceDep, SettingsDep -from ..envelope import build_envelope -from ..images import ( +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__) @@ -158,9 +159,9 @@ def ingest( 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. + # 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, @@ -185,6 +186,13 @@ def ingest( 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: diff --git a/server/src/poorbird/api/images.py b/server/src/poorbird/images.py similarity index 51% rename from server/src/poorbird/api/images.py rename to server/src/poorbird/images.py index d285d28..7187f64 100644 --- a/server/src/poorbird/api/images.py +++ b/server/src/poorbird/images.py @@ -1,10 +1,14 @@ -"""Where capture bytes go, and the little we can learn from them. +"""Where capture bytes go, and what can be read back out of 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. +Lives at package level rather than under ``api`` because both sides use it: +the ingest route writes frames, and the worker reads them back to build +thumbnails. A worker importing from ``api`` would be the wrong way round. + +Split by cost, deliberately. Everything above the thumbnail section runs on +the ingest path, once per frame, and must never be the reason a burst is +slow -- so it reads nine bytes of JPEG header rather than decoding an image. +Pillow appears only below, in the worker, where the frame has to be decoded +anyway. """ from __future__ import annotations @@ -102,3 +106,66 @@ def write_atomically(destination: Path, data: bytes) -> None: except BaseException: temporary.unlink(missing_ok=True) raise + + +# --- thumbnails ------------------------------------------------------------- +# +# Worker only. Nothing above this line imports Pillow, so the ingest path +# never pays for it. + +# 400px on the long edge, WebP, matching the /thumbs/_400.webp pattern +# in SPEC 3.3. The number is in the filename, so changing it means writing to +# a new name rather than silently serving a differently-sized image from the +# old one. +THUMB_EDGE = 400 +THUMB_QUALITY = 80 + + +class UndecodableImage(Exception): + """The bytes are not an image this build of Pillow can read. + + Distinct from an I/O error on purpose: a frame that cannot be decoded + will never decode, so retrying is pointless and the worker should record + the fact rather than burn its attempts. + """ + + +def relative_thumb_path(capture_id: uuid.UUID) -> str: + """``_400.webp`` (SPEC 3.3), flat rather than dated. + + Thumbnails are addressed by capture id alone and there are far fewer of + them per byte, so the dated tree that keeps the image directories to a + sane size buys nothing here. + """ + return f"{capture_id}_{THUMB_EDGE}.webp" + + +def make_thumbnail(source: Path) -> tuple[bytes, tuple[int, int]]: + """Encode a WebP thumbnail. Returns the bytes and the SOURCE dimensions. + + The source size is returned because the worker is the first place that + truly decodes the frame: ingest reads the JPEG header, which can be + absent or unparseable, and this is the chance to fill in what it missed. + """ + import io + + from PIL import Image, UnidentifiedImageError + + try: + with Image.open(source) as img: + img.load() + original = (img.width, img.height) + + # Never upscale. A frame smaller than the thumbnail box should + # stay its own size rather than be blown up into a blurry one. + thumb = img.convert("RGB") + thumb.thumbnail((THUMB_EDGE, THUMB_EDGE), Image.Resampling.LANCZOS) + + buffer = io.BytesIO() + thumb.save(buffer, format="WEBP", quality=THUMB_QUALITY, method=4) + return buffer.getvalue(), original + except (UnidentifiedImageError, OSError, ValueError) as exc: + # Pillow raises OSError for a truncated file as well as for a real + # I/O fault, and the two are not worth separating here: either way + # this frame is not going to produce a thumbnail. + raise UndecodableImage(f"{type(exc).__name__}: {exc}") from exc diff --git a/server/src/poorbird/logging_setup.py b/server/src/poorbird/logging_setup.py index 18bd27b..0f63c6c 100644 --- a/server/src/poorbird/logging_setup.py +++ b/server/src/poorbird/logging_setup.py @@ -11,9 +11,11 @@ import logging import sys from datetime import UTC, datetime -_RESERVED = set( - logging.LogRecord("", 0, "", 0, "", None, None).__dict__ -) | {"message", "asctime", "taskName"} +_RESERVED = set(logging.LogRecord("", 0, "", 0, "", None, None).__dict__) | { + "message", + "asctime", + "taskName", +} class JsonFormatter(logging.Formatter): @@ -37,9 +39,7 @@ def configure_logging(level: str = "INFO", fmt: str = "text") -> None: if fmt == "json": handler.setFormatter(JsonFormatter()) else: - handler.setFormatter( - logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s") - ) + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(name)s %(message)s")) root = logging.getLogger() root.handlers.clear() diff --git a/server/src/poorbird/models/captures.py b/server/src/poorbird/models/captures.py index a0bf70e..cd07b77 100644 --- a/server/src/poorbird/models/captures.py +++ b/server/src/poorbird/models/captures.py @@ -90,9 +90,7 @@ class Capture(Base): # 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() - ) + 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" @@ -138,9 +136,7 @@ class Observation(Base): 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() - ) + 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() ) diff --git a/server/src/poorbird/models/ops.py b/server/src/poorbird/models/ops.py index e65845c..124fa44 100644 --- a/server/src/poorbird/models/ops.py +++ b/server/src/poorbird/models/ops.py @@ -66,9 +66,7 @@ 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() - ) + 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) @@ -106,7 +104,5 @@ class Job(Base): 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() - ) + 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 index 4393d75..9f5f89f 100644 --- a/server/src/poorbird/models/users.py +++ b/server/src/poorbird/models/users.py @@ -46,9 +46,7 @@ class User(Base): 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() - ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) @@ -57,9 +55,7 @@ class Session(Base): 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() - ) + 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/handlers.py b/server/src/poorbird/worker/handlers.py index 0b3f315..b72e0c7 100644 --- a/server/src/poorbird/worker/handlers.py +++ b/server/src/poorbird/worker/handlers.py @@ -10,12 +10,18 @@ Phase 2 adds ``thumbnail``. Phase 5 adds ``backup``, ``retention`` and from __future__ import annotations import logging +import uuid from collections.abc import Callable from typing import Any +from pydantic import BaseModel, ValidationError from sqlalchemy import text from sqlalchemy.orm import Session +from ..config import get_settings +from ..images import UndecodableImage, make_thumbnail, relative_thumb_path, write_atomically +from ..models import Capture + log = logging.getLogger(__name__) Handler = Callable[[Session, dict[str, Any]], None] @@ -38,6 +44,76 @@ def _noop(session: Session, payload: dict[str, Any]) -> None: log.info("noop job ran", extra={"payload": payload}) +class ThumbnailPayload(BaseModel): + """Validated job payload (REVIEW SEC-003). + + Job payloads are JSONB and nothing stops a malformed one being enqueued, + so a handler that indexes straight into the dict fails with a KeyError + three retries later instead of saying what was wrong. + """ + + capture_id: uuid.UUID + + +@handler("thumbnail") +def _thumbnail(session: Session, payload: dict[str, Any]) -> None: + """Build the WebP thumbnail for one capture. + + Enqueued by /ingest after the frame is on disk and in the same + transaction as the capture row, so by the time this runs both exist. + """ + try: + job = ThumbnailPayload.model_validate(payload) + except ValidationError as exc: + # Permanently wrong, not transient. Raising would spend three + # attempts rediscovering that the payload is still malformed. + log.error("thumbnail job payload is invalid", extra={"payload": payload, "error": str(exc)}) + return + + capture = session.get(Capture, job.capture_id) + if capture is None: + # Deleted between enqueue and now. Retention will do this routinely + # once Phase 5 exists, and it is not a failure. + log.info("thumbnail skipped, capture is gone", extra={"capture_id": str(job.capture_id)}) + return + + settings = get_settings() + source = settings.image_root / capture.path + + if not source.is_file(): + # The file should be there: ingest writes it before committing the + # row. Its absence is a real fault, and transient causes (a mount + # that has not come back yet) are worth retrying for. + raise FileNotFoundError(f"capture file missing: {source}") + + try: + data, (width, height) = make_thumbnail(source) + except UndecodableImage as exc: + # A frame that cannot be decoded will never decode. Record it and + # finish, rather than retrying twice more to learn the same thing. + log.warning( + "capture could not be decoded, leaving it without a thumbnail", + extra={"capture_id": str(capture.id), "path": capture.path, "error": str(exc)}, + ) + return + + relative = relative_thumb_path(capture.id) + write_atomically(settings.thumb_root / relative, data) + + capture.thumb_path = relative + # Ingest reads dimensions from the JPEG header, which can be missing or + # unparseable. This is the first full decode, so fill in what it missed. + if capture.width is None or capture.height is None: + capture.width, capture.height = width, height + + session.commit() + + log.info( + "thumbnail written", + extra={"capture_id": str(capture.id), "path": relative, "bytes": len(data)}, + ) + + @handler("prune_expired_commands") def _prune_expired_commands(session: Session, payload: dict[str, Any]) -> None: """Expire commands the device never came back for. diff --git a/server/src/poorbird/worker/queue.py b/server/src/poorbird/worker/queue.py index ecdda58..5f1dbb5 100644 --- a/server/src/poorbird/worker/queue.py +++ b/server/src/poorbird/worker/queue.py @@ -76,8 +76,7 @@ def claim(session: Session) -> dict[str, Any] | 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" + "UPDATE jobs SET status = 'done', finished_at = now(), last_error = NULL WHERE id = :id" ), {"id": job_id}, ) diff --git a/server/tests/test_ingest.py b/server/tests/test_ingest.py index f6b75af..48183df 100644 --- a/server/tests/test_ingest.py +++ b/server/tests/test_ingest.py @@ -13,10 +13,11 @@ 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.images import jpeg_dimensions, looks_like_jpeg from poorbird.models.captures import Capture from poorbird.models.devices import Device, DeviceCommand, DeviceStatus +from poorbird.models.ops import Job def make_jpeg(width: int = 800, height: int = 600, noise: bytes = b"") -> bytes: @@ -49,30 +50,60 @@ def db(): @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) +def make_device(db): + """Devices, their captures, their frames and their jobs -- all cleaned up. - yield d, {"Authorization": f"Bearer {token}"} + Every device a test makes goes through here, so a test that needs a + second one does not have to hand-roll teardown and forget half of it. + """ + created: list[Device] = [] + + def make(name: str = "cam"): + token = new_credential() + d = Device( + device_uid=secrets.token_hex(6), + name=name, + token_hash=hash_credential(token), + enabled=True, + ) + db.add(d) + db.commit() + db.refresh(d) + created.append(d) + return d, {"Authorization": f"Bearer {token}"} + + yield make 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)) + for d in created: + capture_ids = [] + for cap in db.scalars(select(Capture).where(Capture.device_id == d.id)): + (root / cap.path).unlink(missing_ok=True) + capture_ids.append(str(cap.id)) + + # Ingest enqueues a thumbnail job per capture. Leaving those behind + # breaks test_queue.py, which claims from the same shared queue. + # Matched on payload so this never touches a job it did not create. + if capture_ids: + db.query(Job).filter( + Job.kind == "thumbnail", + Job.payload["capture_id"].astext.in_(capture_ids), + ).delete(synchronize_session=False) + + 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)) + existing = db.get(Device, d.id) + if existing is not None: + db.delete(existing) db.commit() +@pytest.fixture +def device(make_device): + return make_device() + + 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()}) @@ -306,29 +337,15 @@ def test_different_frames_are_separate_captures(client, device, db): @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() +def test_one_devices_frame_does_not_deduplicate_against_anothers(client, device, make_device): + _, auth = device + _, other_auth = make_device("other") 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"] + b = post(client, other_auth, data=body).json() - 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() + assert a["capture_id"] != b["capture_id"] # --- refusals --------------------------------------------------------------- diff --git a/server/tests/test_queue.py b/server/tests/test_queue.py index 0dd8a55..8ddf644 100644 --- a/server/tests/test_queue.py +++ b/server/tests/test_queue.py @@ -1,5 +1,11 @@ """Queue behaviour. Needs a real PostgreSQL: SKIP LOCKED has no equivalent anywhere else, and mocking it would test nothing. + +These share the ``jobs`` table with everything else, including /ingest, which +enqueues a thumbnail job per capture. So nothing here may assume it owns the +queue: test jobs are enqueued at a priority that puts them first, and every +claim is checked to be one of ours before anything is done to it. Acting on a +claim without that check could fail somebody else's job. """ from __future__ import annotations @@ -9,6 +15,9 @@ from conftest import needs_db pytestmark = [pytest.mark.db, needs_db] +# claim() orders by priority DESC, so this wins against anything real. +TEST_PRIORITY = 1000 + @pytest.fixture def session(): @@ -21,38 +30,56 @@ def session(): s.commit() +def claim_ours(queue, session, kind: str) -> dict: + """Claim, and insist it is the job this test enqueued.""" + claimed = queue.claim(session) + assert claimed is not None, "our own job should have been claimable" + assert claimed["kind"] == kind, f"claimed {claimed['kind']!r}, not our {kind!r}" + return claimed + + def test_claim_returns_a_queued_job_then_nothing(session): from poorbird.worker import queue - queue.enqueue(session, "test_noop", {"n": 1}) + queue.enqueue(session, "test_noop", {"n": 1}, priority=TEST_PRIORITY) session.commit() - claimed = queue.claim(session) - assert claimed is not None - assert claimed["kind"] == "test_noop" + claimed = claim_ours(queue, session, "test_noop") assert claimed["payload"] == {"n": 1} assert claimed["attempts"] == 1 queue.complete(session, claimed["id"]) - # Same job must not come back. + # Same job must not come back. Anything else that turns up belongs to + # another test, so put it back rather than stranding it in 'running' -- + # a claim that is never released is invisible until something else + # mysteriously stops being processed. again = queue.claim(session) assert again is None or again["kind"] != "test_noop" + if again is not None: + queue.fail(session, again["id"], "released by test", retry_in_s=0) def test_a_second_worker_skips_a_locked_row_instead_of_blocking(session): - """The whole point of FOR UPDATE SKIP LOCKED.""" + """The whole point of FOR UPDATE SKIP LOCKED. + + The invariant is that the second worker is not blocked by the first and + never gets the same row -- not that the queue is otherwise empty, which + is not something a shared table can promise. + """ from poorbird.db import SessionLocal from poorbird.worker import queue - queue.enqueue(session, "test_only_one") + queue.enqueue(session, "test_only_one", priority=TEST_PRIORITY) session.commit() - first = queue.claim(session) - assert first is not None + first = claim_ours(queue, session, "test_only_one") with SessionLocal() as other: - assert queue.claim(other) is None + second = queue.claim(other) + assert second is None or second["id"] != first["id"] + if second is not None: + queue.fail(other, second["id"], "released by test", retry_in_s=0) queue.complete(session, first["id"]) @@ -61,13 +88,12 @@ 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) + job = queue.enqueue(session, "test_doomed", max_attempts=2, priority=TEST_PRIORITY) session.commit() job_id = job.id for _ in range(2): - claimed = queue.claim(session) - assert claimed is not None + claimed = claim_ours(queue, session, "test_doomed") queue.fail(session, claimed["id"], "boom", retry_in_s=0) session.expire_all() @@ -83,10 +109,9 @@ def test_stale_running_jobs_are_reclaimed(session): from poorbird.models import Job from poorbird.worker import queue - job = queue.enqueue(session, "test_orphan") + job = queue.enqueue(session, "test_orphan", priority=TEST_PRIORITY) session.commit() - claimed = queue.claim(session) - assert claimed is not None + claim_ours(queue, session, "test_orphan") # Pretend the worker died an hour ago. session.execute( diff --git a/server/tests/test_thumbnails.py b/server/tests/test_thumbnails.py new file mode 100644 index 0000000..40bcd68 --- /dev/null +++ b/server/tests/test_thumbnails.py @@ -0,0 +1,326 @@ +"""The thumbnail worker job. + +Unlike the ingest path, this really decodes the frame, so these tests use +real JPEGs rather than the hand-built headers in test_ingest.py. +""" + +from __future__ import annotations + +import io +import secrets +import uuid + +import pytest +from conftest import needs_db +from PIL import Image + +from poorbird.config import get_settings +from poorbird.images import ( + THUMB_EDGE, + UndecodableImage, + make_thumbnail, + relative_thumb_path, +) +from poorbird.models.captures import Capture +from poorbird.models.devices import Device +from poorbird.worker.handlers import HANDLERS + + +def real_jpeg(width: int = 1600, height: int = 1200) -> bytes: + """An actual decodable JPEG, not just a plausible header.""" + img = Image.new("RGB", (width, height)) + for x in range(0, width, 64): # some structure, so it is not a solid block + for y in range(0, height, 64): + img.putpixel((x, y), (x % 256, y % 256, 128)) + out = io.BytesIO() + img.save(out, format="JPEG", quality=85) + return out.getvalue() + + +# --- the encoder ------------------------------------------------------------ + + +def test_the_long_edge_is_capped_and_the_aspect_ratio_is_kept(tmp_path): + source = tmp_path / "wide.jpg" + source.write_bytes(real_jpeg(1600, 1200)) + + data, original = make_thumbnail(source) + + assert original == (1600, 1200) + with Image.open(io.BytesIO(data)) as thumb: + assert max(thumb.size) == THUMB_EDGE + assert thumb.size == (400, 300) # 4:3 preserved + + +def test_a_portrait_frame_is_capped_on_its_own_long_edge(tmp_path): + source = tmp_path / "tall.jpg" + source.write_bytes(real_jpeg(600, 1200)) + + data, _ = make_thumbnail(source) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.size == (200, 400) + + +def test_a_small_frame_is_never_upscaled(tmp_path): + """Blowing a 100px frame up to 400px produces a blurry lie.""" + source = tmp_path / "small.jpg" + source.write_bytes(real_jpeg(100, 80)) + + data, original = make_thumbnail(source) + + assert original == (100, 80) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.size == (100, 80) + + +def test_the_output_is_webp(tmp_path): + source = tmp_path / "x.jpg" + source.write_bytes(real_jpeg(800, 600)) + + data, _ = make_thumbnail(source) + with Image.open(io.BytesIO(data)) as thumb: + assert thumb.format == "WEBP" + + +def test_a_thumbnail_is_much_smaller_than_its_source(tmp_path): + source = tmp_path / "x.jpg" + source.write_bytes(real_jpeg(1600, 1200)) + + data, _ = make_thumbnail(source) + assert len(data) < source.stat().st_size + + +def test_rubbish_raises_undecodable_rather_than_something_generic(tmp_path): + """The distinction matters: undecodable is permanent, so the worker must + not spend three attempts rediscovering it.""" + source = tmp_path / "not-an-image.jpg" + source.write_bytes(b"\xff\xd8\xff" + b"garbage" * 100) + + with pytest.raises(UndecodableImage): + make_thumbnail(source) + + +def test_a_truncated_jpeg_is_also_undecodable(tmp_path): + source = tmp_path / "half.jpg" + source.write_bytes(real_jpeg(1600, 1200)[:200]) + + with pytest.raises(UndecodableImage): + make_thumbnail(source) + + +def test_the_thumb_name_carries_its_size(tmp_path): + """The size is in the filename, so changing it writes a new name rather + than silently serving a different image from the old one.""" + cid = uuid.uuid4() + assert relative_thumb_path(cid) == f"{cid}_400.webp" + + +# --- the handler ------------------------------------------------------------ + + +@pytest.fixture +def db(): + from poorbird.db import SessionLocal + + with SessionLocal() as session: + yield session + + +@pytest.fixture +def capture(db): + """A capture with its frame genuinely on disk, cleaned up either way.""" + settings = get_settings() + device = Device(device_uid=secrets.token_hex(6), name="cam") + db.add(device) + db.commit() + db.refresh(device) + + created: list[Capture] = [] + + def make(data: bytes | None = None, *, width=None, height=None): + cid = uuid.uuid4() + relative = f"2026/09/21/{cid}.jpg" + path = settings.image_root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(real_jpeg(1600, 1200) if data is None else data) + + cap = Capture( + id=cid, + device_id=device.id, + path=relative, + sha256="0" * 64, + bytes=path.stat().st_size, + trigger="radar", + width=width, + height=height, + ) + db.add(cap) + db.commit() + db.refresh(cap) + created.append(cap) + return cap + + yield make + + for cap in created: + (settings.image_root / cap.path).unlink(missing_ok=True) + if cap.thumb_path: + (settings.thumb_root / cap.thumb_path).unlink(missing_ok=True) + db.execute(Capture.__table__.delete().where(Capture.device_id == device.id)) + db.delete(db.get(Device, device.id)) + db.commit() + + +def run_job(db, capture_id) -> None: + HANDLERS["thumbnail"](db, {"capture_id": str(capture_id)}) + + +@needs_db +def test_the_handler_writes_a_thumbnail_and_records_it(db, capture): + cap = capture() + assert cap.thumb_path is None + + run_job(db, cap.id) + + db.refresh(cap) + assert cap.thumb_path == f"{cap.id}_400.webp" + + on_disk = get_settings().thumb_root / cap.thumb_path + assert on_disk.is_file() + with Image.open(on_disk) as thumb: + assert thumb.format == "WEBP" + assert max(thumb.size) == THUMB_EDGE + + +@needs_db +def test_it_fills_in_dimensions_ingest_could_not_read(db, capture): + """Ingest reads the JPEG header, which can be absent or unparseable. + This is the first full decode, so it is the chance to fix that.""" + cap = capture(width=None, height=None) + + run_job(db, cap.id) + + db.refresh(cap) + assert (cap.width, cap.height) == (1600, 1200) + + +@needs_db +def test_it_does_not_overwrite_dimensions_ingest_already_had(db, capture): + cap = capture(width=1600, height=1200) + + run_job(db, cap.id) + + db.refresh(cap) + assert (cap.width, cap.height) == (1600, 1200) + + +@needs_db +def test_running_it_twice_is_harmless(db, capture): + """Jobs get retried, and a partially written thumbnail must not survive.""" + cap = capture() + + run_job(db, cap.id) + first = (get_settings().thumb_root / cap.thumb_path).read_bytes() + run_job(db, cap.id) + second = (get_settings().thumb_root / cap.thumb_path).read_bytes() + + assert first == second + + +@needs_db +def test_no_part_file_is_left_behind(db, capture): + cap = capture() + run_job(db, cap.id) + + assert not list(get_settings().thumb_root.glob(".*.part")) + + +@needs_db +def test_an_undecodable_frame_is_recorded_not_retried(db, capture): + """Returning rather than raising is the point: the handler contract makes + a raise mean 'retry', and this will never decode.""" + cap = capture(data=b"\xff\xd8\xff" + b"garbage" * 100) + + run_job(db, cap.id) # must not raise + + db.refresh(cap) + assert cap.thumb_path is None + + +@needs_db +def test_a_missing_source_raises_so_the_job_retries(db, capture): + """The opposite case: the file should be there, and a mount that has not + come back yet is worth retrying for.""" + cap = capture() + (get_settings().image_root / cap.path).unlink() + + with pytest.raises(FileNotFoundError): + run_job(db, cap.id) + + +@needs_db +def test_a_capture_that_has_since_been_deleted_is_not_an_error(db): + """Retention will do this routinely once Phase 5 exists.""" + run_job(db, uuid.uuid4()) # must not raise + + +@needs_db +def test_a_malformed_payload_is_recorded_not_retried(db): + """SEC-003. Raising would spend three attempts rediscovering that the + payload is still malformed.""" + HANDLERS["thumbnail"](db, {}) + HANDLERS["thumbnail"](db, {"capture_id": "not-a-uuid"}) + HANDLERS["thumbnail"](db, {"wrong_key": 1}) + + +# --- wired to ingest -------------------------------------------------------- + + +@needs_db +def test_ingest_enqueues_the_job(client, db): + """Off the request path: decoding to resize is the one genuinely + expensive part of a capture, and the device is waiting with a burst + still to upload.""" + from sqlalchemy import text + + from poorbird.api.deps import hash_credential, new_credential + + token = new_credential() + device = Device( + device_uid=secrets.token_hex(6), + name="cam", + token_hash=hash_credential(token), + enabled=True, + ) + db.add(device) + db.commit() + db.refresh(device) + + r = client.post( + "/api/v1/ingest", + content=real_jpeg(800, 600), + headers={"Content-Type": "image/jpeg", "Authorization": f"Bearer {token}"}, + ) + assert r.status_code == 201 + capture_id = r.json()["capture_id"] + + queued = db.execute( + text( + "SELECT kind, status FROM jobs " + "WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid" + ), + {"cid": capture_id}, + ).first() + assert queued is not None, "ingest must queue the thumbnail" + assert queued.status == "queued" + + settings = get_settings() + cap = db.get(Capture, uuid.UUID(capture_id)) + (settings.image_root / cap.path).unlink(missing_ok=True) + db.execute( + text("DELETE FROM jobs WHERE kind = 'thumbnail' AND payload->>'capture_id' = :cid"), + {"cid": capture_id}, + ) + db.execute(Capture.__table__.delete().where(Capture.device_id == device.id)) + db.delete(db.get(Device, device.id)) + db.commit()