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>
172 lines
6.2 KiB
Python
172 lines
6.2 KiB
Python
"""Where capture bytes go, and what can be read back out of them.
|
|
|
|
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
|
|
|
|
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/<uuid>.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
|
|
|
|
|
|
# --- 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/<uuid>_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:
|
|
"""``<uuid>_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
|