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>
109 lines
4.4 KiB
Python
109 lines
4.4 KiB
Python
"""Operational tables: settings, audit log, backup runs, and the job queue."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import (
|
|
BigInteger,
|
|
CheckConstraint,
|
|
DateTime,
|
|
ForeignKey,
|
|
Index,
|
|
Integer,
|
|
String,
|
|
Text,
|
|
func,
|
|
)
|
|
from sqlalchemy.dialects.postgresql import JSONB
|
|
from sqlalchemy.orm import Mapped, mapped_column
|
|
|
|
from .base import Base
|
|
|
|
JOB_STATUSES = ("queued", "running", "done", "failed")
|
|
|
|
|
|
class Setting(Base):
|
|
"""SPEC 3.4. "Fully configurable" needs a boundary or it never finishes.
|
|
|
|
Server scope: retention policy, thumbnail size, backup schedule + target,
|
|
alarm thresholds and channels, default theme, default locale, session
|
|
lifetime. Anything not on that list is a code change, deliberately.
|
|
|
|
Backup schedule lives here rather than in a systemd timer, which is why
|
|
scheduling runs in the worker (TODO Phase 1.2).
|
|
"""
|
|
|
|
__tablename__ = "settings"
|
|
__table_args__ = (CheckConstraint("scope IN ('server', 'device')", name="scope_valid"),)
|
|
|
|
key: Mapped[str] = mapped_column(String(64), primary_key=True)
|
|
value: Mapped[str | None] = mapped_column(Text)
|
|
value_type: Mapped[str] = mapped_column(String(16), default="str", server_default="'str'")
|
|
scope: Mapped[str] = mapped_column(String(16), default="server", server_default="'server'")
|
|
updated_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
updated_at: Mapped[datetime] = mapped_column(
|
|
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
|
)
|
|
|
|
|
|
class AuditLog(Base):
|
|
__tablename__ = "audit_log"
|
|
__table_args__ = (Index("ix_audit_log_entity", "entity", "entity_id", "at"),)
|
|
|
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
|
|
action: Mapped[str] = mapped_column(String(64))
|
|
entity: Mapped[str] = mapped_column(String(64))
|
|
entity_id: Mapped[str | None] = mapped_column(String(64))
|
|
before: Mapped[dict | None] = mapped_column(JSONB)
|
|
after: Mapped[dict | None] = mapped_column(JSONB)
|
|
ip: Mapped[str | None] = mapped_column(String(45))
|
|
|
|
|
|
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())
|
|
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)
|
|
snapshot_id: Mapped[str | None] = mapped_column(String(64))
|
|
# A backup you have never restored is a hypothesis: set by the monthly
|
|
# restore test (TODO Phase 5).
|
|
restore_tested_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
error: Mapped[str | None] = mapped_column(Text)
|
|
|
|
|
|
class Job(Base):
|
|
"""Postgres-backed queue, claimed with FOR UPDATE SKIP LOCKED. No Redis.
|
|
|
|
This second writer is the concrete reason SPEC C8 pushed past SQLite.
|
|
"""
|
|
|
|
__tablename__ = "jobs"
|
|
__table_args__ = (
|
|
CheckConstraint("status IN " + str(JOB_STATUSES), name="status_valid"),
|
|
# The claim query's covering index.
|
|
Index("ix_jobs_claimable", "status", "run_at", "priority"),
|
|
)
|
|
|
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
|
kind: Mapped[str] = mapped_column(String(64))
|
|
payload: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
|
|
status: Mapped[str] = mapped_column(String(16), default="queued", server_default="'queued'")
|
|
priority: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
|
|
|
run_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
|
attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
|
|
max_attempts: Mapped[int] = mapped_column(Integer, default=3, server_default="3")
|
|
|
|
locked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
|
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())
|
|
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|