From d0b8e1ed223e76d2c01cc0fea1cdea97bb8ad458 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 22:22:26 +0100 Subject: [PATCH 1/6] Add per-user album art override model and migration Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- .env.example | 3 ++ src/scrobbler/config.py | 2 + .../versions/a41c9e2d7b53_user_album_art.py | 51 +++++++++++++++++++ src/scrobbler/models.py | 36 +++++++++++++ 4 files changed, 92 insertions(+) create mode 100644 src/scrobbler/migrations/versions/a41c9e2d7b53_user_album_art.py diff --git a/.env.example b/.env.example index e23385d..47558dd 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,9 @@ MUSICBRAINZ_CONTACT= # Where downloaded art is stored. docker compose points this at a shared volume; the # default below is for running the api/worker directly (not in Docker). ART_STORAGE_DIR=var/album-art +# Largest image a user may upload as their own album art (bytes). Uploaded art is +# stored in ART_STORAGE_DIR too, so back that directory up. +ART_UPLOAD_MAX_BYTES=5242880 # docker compose host ports (defaults shown) API_PORT=5050 diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index b0671a2..e86ae1b 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -67,6 +67,8 @@ class Config: # Downloaded art is kept here, named by the album_art row's id. Needs write access # from the worker (which downloads it) and read access from the api (which serves it). ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art") + # Largest image a user may upload as their own album art. + ART_UPLOAD_MAX_BYTES = int(os.environ.get("ART_UPLOAD_MAX_BYTES", str(5 * 1024 * 1024))) IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024))) MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests diff --git a/src/scrobbler/migrations/versions/a41c9e2d7b53_user_album_art.py b/src/scrobbler/migrations/versions/a41c9e2d7b53_user_album_art.py new file mode 100644 index 0000000..1c5f554 --- /dev/null +++ b/src/scrobbler/migrations/versions/a41c9e2d7b53_user_album_art.py @@ -0,0 +1,51 @@ +"""user album art + +Revision ID: a41c9e2d7b53 +Revises: 3ba21eb1ea0c +Create Date: 2026-10-06 21:40:00.000000 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "a41c9e2d7b53" +down_revision = "3ba21eb1ea0c" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "user_album_art", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("artist", sa.Text(), nullable=False), + sa.Column("album", sa.Text(), nullable=False), + sa.Column("kind", sa.String(length=16), nullable=False), + sa.Column("status", sa.String(length=16), nullable=False), + sa.Column("search_artist", sa.Text(), nullable=True), + sa.Column("search_album", sa.Text(), nullable=True), + sa.Column("release_group_mbid", sa.String(length=36), nullable=True), + sa.Column("content_type", sa.String(length=32), nullable=True), + sa.Column("error_code", sa.String(length=64), nullable=True), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + with op.batch_alter_table("user_album_art", schema=None) as batch_op: + batch_op.create_index( + "uq_user_album_art_user_artist_album_lower", + ["user_id", sa.literal_column("lower(artist)"), sa.literal_column("lower(album)")], + unique=True, + ) + + +def downgrade(): + with op.batch_alter_table("user_album_art", schema=None) as batch_op: + batch_op.drop_index("uq_user_album_art_user_artist_album_lower") + + op.drop_table("user_album_art") diff --git a/src/scrobbler/models.py b/src/scrobbler/models.py index 7f90ed0..d01a102 100644 --- a/src/scrobbler/models.py +++ b/src/scrobbler/models.py @@ -183,3 +183,39 @@ class AlbumArt(db.Model): "uq_album_art_artist_album_lower", func.lower(artist), func.lower(album), unique=True ), ) + + +class UserAlbumArt(db.Model): + """One user's own art for (artist, album): an uploaded image, or a manual correction. + + Takes precedence over the global `AlbumArt` cache for that user only. A correction + (a different search text and/or a MusicBrainz release-group ID) is resolved by the + worker, never by the request that asked for it; an upload is `found` immediately. + The image bytes live on disk, named by this row's id. + """ + + __tablename__ = "user_album_art" + + id: Mapped[int] = mapped_column(primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE")) + artist: Mapped[str] = mapped_column(Text) + album: Mapped[str] = mapped_column(Text) + kind: Mapped[str] = mapped_column(String(16)) # upload or correction + status: Mapped[str] = mapped_column(String(16)) # pending, found or error + search_artist: Mapped[str | None] = mapped_column(Text) # correction inputs + search_album: Mapped[str | None] = mapped_column(Text) + release_group_mbid: Mapped[str | None] = mapped_column(String(36)) + content_type: Mapped[str | None] = mapped_column(String(32)) # set iff status == "found" + error_code: Mapped[str | None] = mapped_column(String(64)) # set iff status == "error" + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + __table_args__ = ( + Index( + "uq_user_album_art_user_artist_album_lower", + user_id, + func.lower(artist), + func.lower(album), + unique=True, + ), + ) From a887865f05f09d9c918dea7964a1108cefc74beb Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 22:25:05 +0100 Subject: [PATCH 2/6] Add per-user art overrides: service, worker corrections and metrics Uploads and queued corrections are stored per user and take precedence over the global cache; the worker resolves corrections (by MusicBrainz release-group or corrected search text) ahead of the global queue. Adds upload/correction metrics and DB gauges for overrides and the unresolved-album backlog. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- src/scrobbler/metrics/__init__.py | 35 ++++ src/scrobbler/metrics/collectors.py | 46 +++++ src/scrobbler/services/art.py | 286 +++++++++++++++++++++++++++- tests/test_art.py | 161 +++++++++++++++- tests/test_metrics.py | 30 +++ 5 files changed, 553 insertions(+), 5 deletions(-) diff --git a/src/scrobbler/metrics/__init__.py b/src/scrobbler/metrics/__init__.py index 0c27fa1..056573a 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -156,6 +156,38 @@ art_image_bytes = Histogram( buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000), ) +# Album art: per-user uploads and corrections +art_uploads_total = Counter( + "scrobbler_art_uploads_total", + "Album art upload attempts: ok, empty, too_large or bad_type", + ["result"], +) +art_upload_bytes = Histogram( + "scrobbler_art_upload_bytes", + "Size of accepted album art uploads", + buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 5_000_000), +) +art_override_actions_total = Counter( + "scrobbler_art_override_actions_total", + "Manual album art actions: correction_requested, retry_requested, override_deleted", + ["action"], +) +art_correction_resolutions_total = Counter( + "scrobbler_art_correction_resolutions_total", + "Worker outcome of a manual correction, by input (mbid or search) and result", + ["input", "result"], +) +art_correction_wait_seconds = Histogram( + "scrobbler_art_correction_wait_seconds", + "Time from a correction being requested to the worker finishing it", + buckets=(1, 5, 15, 30, 60, 300, 900, 3600, 6 * 3600), +) +art_override_worker_seconds = Histogram( + "scrobbler_art_override_worker_seconds", + "Time for the worker to resolve and download one corrected album's art", + buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80), +) + # Database db_query_duration_seconds = Histogram( "scrobbler_db_query_duration_seconds", @@ -186,4 +218,7 @@ COLLECTED = { "import_jobs": "scrobbler_import_jobs", "art_cache": "scrobbler_art_cache", "art_oldest_pending": "scrobbler_art_oldest_pending_seconds", + "art_overrides": "scrobbler_art_overrides", + "art_override_oldest_pending": "scrobbler_art_override_oldest_pending_seconds", + "art_unresolved": "scrobbler_art_unresolved_albums", } diff --git a/src/scrobbler/metrics/collectors.py b/src/scrobbler/metrics/collectors.py index 40c4c74..6defaa8 100644 --- a/src/scrobbler/metrics/collectors.py +++ b/src/scrobbler/metrics/collectors.py @@ -13,6 +13,8 @@ from sqlalchemy.pool import NullPool from scrobbler.metrics import COLLECTED ART_STATUSES = ("pending", "found", "not_found", "error") +ART_OVERRIDE_KINDS = ("upload", "correction") +ART_OVERRIDE_STATUSES = ("pending", "found", "error") ACTIVE_WINDOWS = {"1h": "1 hour", "24h": "24 hours", "7d": "7 days"} @@ -56,6 +58,25 @@ class DatabaseStatsCollector(Collector): "FROM album_art WHERE status = 'pending'" ) ).scalar_one() + overrides = { + (kind, status): count + for kind, status, count in conn.execute( + text("SELECT kind, status, count(*) FROM user_album_art GROUP BY kind, status") + ).all() + } + override_oldest = conn.execute( + text( + "SELECT coalesce(extract(epoch FROM now() - min(updated_at)), 0) " + "FROM user_album_art WHERE status = 'pending'" + ) + ).scalar_one() + unresolved = conn.execute( + text( + "SELECT count(*) FROM album_art a WHERE a.status IN ('not_found', 'error') " + "AND NOT EXISTS (SELECT 1 FROM user_album_art u WHERE u.status = 'found' " + "AND lower(u.artist) = lower(a.artist) AND lower(u.album) = lower(a.album))" + ) + ).scalar_one() return { "users": users, "active": active, @@ -63,6 +84,13 @@ class DatabaseStatsCollector(Collector): "import_jobs": {s: import_jobs.get(s, 0) for s in ("pending", "running")}, "art_cache": {s: art_cache.get(s, 0) for s in ART_STATUSES}, "art_oldest_pending": float(oldest_pending), + "art_overrides": { + (kind, status): overrides.get((kind, status), 0) + for kind in ART_OVERRIDE_KINDS + for status in ART_OVERRIDE_STATUSES + }, + "art_override_oldest_pending": float(override_oldest), + "art_unresolved": unresolved, } def values(self) -> dict | None: @@ -108,3 +136,21 @@ class DatabaseStatsCollector(Collector): "Age of the longest-waiting album art request (0 if none pending)", value=values["art_oldest_pending"], ) + overrides = GaugeMetricFamily( + COLLECTED["art_overrides"], + "User album art overrides by kind and status", + labels=["kind", "status"], + ) + for (kind, status), count in values["art_overrides"].items(): + overrides.add_metric([kind, status], count) + yield overrides + yield GaugeMetricFamily( + COLLECTED["art_override_oldest_pending"], + "Age of the longest-waiting manual art correction (0 if none pending)", + value=values["art_override_oldest_pending"], + ) + yield GaugeMetricFamily( + COLLECTED["art_unresolved"], + "Albums with no art that no user has fixed", + value=values["art_unresolved"], + ) diff --git a/src/scrobbler/services/art.py b/src/scrobbler/services/art.py index 4588205..b31077d 100644 --- a/src/scrobbler/services/art.py +++ b/src/scrobbler/services/art.py @@ -29,12 +29,12 @@ from datetime import UTC, datetime, timedelta from pathlib import Path from flask import current_app -from sqlalchemy import func, or_, select +from sqlalchemy import and_, delete, func, or_, select from sqlalchemy.dialects.postgresql import insert from scrobbler import metrics from scrobbler.extensions import db -from scrobbler.models import AlbumArt +from scrobbler.models import AlbumArt, Scrobble, UserAlbumArt log = logging.getLogger(__name__) @@ -266,6 +266,215 @@ def fetch_image(image_url: str) -> ImageBytes: raise ArtFetchFailed(str(err)) from err +# --- Per-user overrides -------------------------------------------------------------- +# +# A user's own art for an album (an upload, or a manual correction the worker resolves) +# beats the global cache for that user only. Like the rest of the web path, nothing here +# touches the network: a correction is just a queued row. + +IMAGE_TYPES = {"image/jpeg", "image/png", "image/webp"} + + +class UnsupportedImage(Exception): + """The bytes aren't a JPEG, PNG or WebP image.""" + + +def sniff_image_type(data: bytes) -> str: + """The image's content type from its magic bytes. Raises UnsupportedImage.""" + if data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + raise UnsupportedImage + + +def _override_path(row_id: int) -> Path: + return Path(current_app.config["ART_STORAGE_DIR"]) / "user" / str(row_id) + + +def _override_key(user_id: int, artist: str, album: str): + return and_( + UserAlbumArt.user_id == user_id, + func.lower(UserAlbumArt.artist) == artist.lower(), + func.lower(UserAlbumArt.album) == album.lower(), + ) + + +def get_override(user_id: int, artist: str, album: str) -> UserAlbumArt | None: + return db.session.scalar(select(UserAlbumArt).where(_override_key(user_id, artist, album))) + + +def read_override_file(row: UserAlbumArt) -> bytes | None: + try: + return _override_path(row.id).read_bytes() + except FileNotFoundError: + return None + + +def _upsert_override(user_id: int, artist: str, album: str, **values) -> int: + now = datetime.now(UTC) + stmt = insert(UserAlbumArt).values( + user_id=user_id, artist=artist, album=album, created_at=now, updated_at=now, **values + ) + stmt = stmt.on_conflict_do_update( + index_elements=[ + UserAlbumArt.user_id, + func.lower(UserAlbumArt.artist), + func.lower(UserAlbumArt.album), + ], + set_={**values, "updated_at": now}, + ).returning(UserAlbumArt.id) + row_id = db.session.execute(stmt).scalar_one() + db.session.commit() + return row_id + + +def save_upload(user_id: int, artist: str, album: str, data: bytes, content_type: str) -> None: + """Store an uploaded image as the user's art. The caller has already validated it.""" + path_id = _upsert_override( + user_id, + artist, + album, + kind="upload", + status="found", + content_type=content_type, + search_artist=None, + search_album=None, + release_group_mbid=None, + error_code=None, + ) + path = _override_path(path_id) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + + +def request_correction( + user_id: int, + artist: str, + album: str, + search_artist: str | None, + search_album: str | None, + release_group_mbid: str | None, +) -> None: + """Queue a corrected lookup (different search text, or a known MusicBrainz + release-group) for the worker. A fast, network-free write.""" + _upsert_override( + user_id, + artist, + album, + kind="correction", + status="pending", + content_type=None, + search_artist=search_artist, + search_album=search_album, + release_group_mbid=release_group_mbid, + error_code=None, + ) + metrics.art_override_actions_total.labels("correction_requested").inc() + + +def delete_override(user_id: int, artist: str, album: str) -> bool: + """Drops the user's override (and its image). False if there wasn't one.""" + row = get_override(user_id, artist, album) + if row is None: + return False + row_id = row.id + db.session.execute(delete(UserAlbumArt).where(UserAlbumArt.id == row_id)) + db.session.commit() + _override_path(row_id).unlink(missing_ok=True) + metrics.art_override_actions_total.labels("override_deleted").inc() + return True + + +def retry(artist: str, album: str) -> bool: + """Ask the worker to look an album up again from scratch. False if there's nothing + to retry (it's already found, or already waiting).""" + row = get_cached(artist, album) + if row is None: + want(artist, album) + elif row.status in ("not_found", "error"): + requeue(row) + else: + return False + metrics.art_override_actions_total.labels("retry_requested").inc() + return True + + +def list_failures(user_id: int, page: int, limit: int) -> tuple[list[dict], int]: + """One page of the user's scrobbled albums that have no art (the lookup failed) or + whose manual correction hasn't worked, most-scrobbled first. Returns (items, total).""" + albums = ( + select( + func.min(Scrobble.artist).label("artist"), + func.min(Scrobble.album).label("album"), + func.count().label("scrobbles"), + ) + .where(Scrobble.user_id == user_id, Scrobble.album.is_not(None), Scrobble.album != "") + .group_by(func.lower(Scrobble.artist), func.lower(Scrobble.album)) + .subquery() + ) + query = ( + select(albums.c.artist, albums.c.album, albums.c.scrobbles, AlbumArt, UserAlbumArt) + .select_from(albums) + .outerjoin( + AlbumArt, + and_( + func.lower(AlbumArt.artist) == func.lower(albums.c.artist), + func.lower(AlbumArt.album) == func.lower(albums.c.album), + ), + ) + .outerjoin( + UserAlbumArt, + and_( + UserAlbumArt.user_id == user_id, + func.lower(UserAlbumArt.artist) == func.lower(albums.c.artist), + func.lower(UserAlbumArt.album) == func.lower(albums.c.album), + ), + ) + .where( + or_( + UserAlbumArt.status.in_(("pending", "error")), + and_( + UserAlbumArt.id.is_(None), + AlbumArt.status.in_(("not_found", "error")), + ), + ) + ) + ) + total = db.session.scalar(select(func.count()).select_from(query.subquery())) + rows = db.session.execute( + query.order_by(albums.c.scrobbles.desc(), albums.c.artist, albums.c.album) + .limit(limit) + .offset((page - 1) * limit) + ).all() + items = [ + { + "artist": artist, + "album": album, + "scrobbles": scrobbles, + "status": cached.status if cached else "pending", + "error_code": cached.error_code if cached else None, + "checked_at": cached.checked_at if cached else None, + "override": ( + { + "kind": override.kind, + "status": override.status, + "error_code": override.error_code, + "search_artist": override.search_artist, + "search_album": override.search_album, + "release_group_mbid": override.release_group_mbid, + } + if override + else None + ), + } + for artist, album, scrobbles, cached, override in rows + ] + return items, total + + # --- Worker -------------------------------------------------------------------------- @@ -295,10 +504,79 @@ def _claim_pending() -> AlbumArt | None: return row +def _claim_correction() -> UserAlbumArt | None: + row = db.session.scalar( + select(UserAlbumArt) + .where(UserAlbumArt.status == "pending") + .order_by(UserAlbumArt.updated_at) + .limit(1) + .with_for_update(skip_locked=True) + ) + if row is None: + db.session.rollback() + return row + + +def _resolve_correction(row: UserAlbumArt) -> tuple[ArtResult, str | None]: + """Live resolution of a user's correction: a known release-group goes straight to + Cover Art Archive, otherwise the (corrected) text is searched. Never raises.""" + if not row.release_group_mbid: + result, _, error_code = _resolve( + row.search_artist or row.artist, row.search_album or row.album + ) + return result, error_code + try: + image_url = _cover_art_url(row.release_group_mbid) + except Exception as err: # noqa: BLE001 - any upstream failure is recorded on the row + log.warning("Corrected art lookup failed for %r/%r: %s", row.artist, row.album, err) + return ArtResult("error"), type(err).__name__ + return ArtResult("found" if image_url else "not_found", image_url), None + + +def resolve_one_correction() -> bool: + """Resolve one user's pending manual correction, saving the image on success. + Returns True if it processed one.""" + row = _claim_correction() + if row is None: + return False + start = time.perf_counter() + source = "mbid" if row.release_group_mbid else "search" + result, error_code = _resolve_correction(row) + content_type = None + if result.status == "found": + try: + image = fetch_image(result.image_url) + content_type = image.content_type.split(";")[0].strip() + if content_type not in IMAGE_TYPES: + content_type = "image/jpeg" + path = _override_path(row.id) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(image.body) + except ArtFetchFailed as err: + log.warning("Corrected art download failed for %r/%r: %s", row.artist, row.album, err) + result, error_code = ArtResult("error"), "ArtFetchFailed" + elif result.status == "not_found": + error_code = "NotFound" + metrics.art_correction_resolutions_total.labels(source, result.status).inc() + metrics.art_resolutions_total.labels("override", result.status).inc() + now = datetime.now(UTC) + metrics.art_correction_wait_seconds.observe((now - row.updated_at).total_seconds()) + row.status = "found" if result.status == "found" else "error" + row.content_type = content_type + row.error_code = error_code + row.updated_at = now + db.session.commit() + metrics.art_override_worker_seconds.observe(time.perf_counter() - start) + return True + + def resolve_one_pending() -> bool: """Worker task: resolve one row that's pending or due for a recheck, downloading - and saving its image bytes when found. Returns True if it processed a row (call - again immediately), False if there was nothing to do.""" + and saving its image bytes when found. A user's manual correction goes first. + Returns True if it processed a row (call again immediately), False if there was + nothing to do.""" + if resolve_one_correction(): + return True row = _claim_pending() if row is None: return False diff --git a/tests/test_art.py b/tests/test_art.py index 058e0f8..e9d5538 100644 --- a/tests/test_art.py +++ b/tests/test_art.py @@ -1,6 +1,7 @@ import json import pathlib import threading +import time import urllib.parse from datetime import UTC, datetime, timedelta @@ -9,7 +10,8 @@ from werkzeug.serving import make_server from scrobbler.extensions import db from scrobbler.models import AlbumArt -from scrobbler.services import art +from scrobbler.services import art, scrobbles +from scrobbler.services.scrobbles import TrackInput # Canned release-group matches, keyed by a substring of the Lucene search query we send. _RELEASE_GROUPS = { @@ -422,3 +424,160 @@ def test_endpoint_counts_served(client, auth, art_config, metric_delta): art.resolve_one_pending() assert client.get(url, headers=auth).status_code == 200 assert served.delta == 1 + + +# --- per-user overrides (service + worker) ---------------------------------------------- + +BASE = int(time.time()) - 3600 +JPEG = b"\xff\xd8\xff\xe0my-own-art" + + +def override(user, artist, album): + return art.get_override(user.id, artist, album) + + +def scrobble_album(user, artist, album, count=1, base=None): + scrobbles.submit_scrobbles( + user, + None, + [ + TrackInput(artist=artist, track=f"t{i}", album=album, timestamp=(base or BASE) + i) + for i in range(count) + ], + ) + + +def test_sniff_image_type(): + assert art.sniff_image_type(JPEG) == "image/jpeg" + assert art.sniff_image_type(b"\x89PNG\r\n\x1a\n....") == "image/png" + assert art.sniff_image_type(b"RIFF\x00\x00\x00\x00WEBPVP8 ") == "image/webp" + with pytest.raises(art.UnsupportedImage): + art.sniff_image_type(b"GIF89a") + + +def test_save_upload_stores_the_file_and_replaces_it(art_config, user): + art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg") + first = override(user, "nobody", "NOTHING") # case-insensitive + assert (first.kind, first.status, first.content_type) == ("upload", "found", "image/jpeg") + assert art.read_override_file(first) == JPEG + art.save_upload(user.id, "Nobody", "Nothing", b"\x89PNG\r\n\x1a\nnew", "image/png") + second = override(user, "Nobody", "Nothing") + assert second.id == first.id + assert art.read_override_file(second).endswith(b"new") + assert second.content_type == "image/png" + + +def test_overrides_are_per_user(art_config, user, make_user): + other = make_user(username="mallory") + art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg") + assert override(other, "Nobody", "Nothing") is None + + +def test_delete_override_removes_row_and_file(art_config, user): + art.save_upload(user.id, "Nobody", "Nothing", JPEG, "image/jpeg") + row_id = override(user, "Nobody", "Nothing").id + assert art.delete_override(user.id, "Nobody", "Nothing") is True + assert override(user, "Nobody", "Nothing") is None + assert not art._override_path(row_id).exists() + assert art.delete_override(user.id, "Nobody", "Nothing") is False + + +def test_retry_requeues_failures_only(art_config): + insert("A", "Failed", "not_found") + insert("A", "Fine", "found") + assert art.retry("A", "Failed") is True + assert row("A", "Failed").status == "pending" + assert art.retry("A", "Fine") is False + assert art.retry("Brand", "New") is True + assert row("Brand", "New").status == "pending" + + +def test_correction_by_mbid_is_resolved_by_the_worker(art_config, user, metric_delta): + resolved = metric_delta( + "scrobbler_art_correction_resolutions_total", input="mbid", result="found" + ) + wait = metric_delta("scrobbler_art_correction_wait_seconds_count") + art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, "rg-found") + assert override(user, "Radiohead", "Inrainbows").status == "pending" + assert art.resolve_one_pending() is True + fixed = override(user, "Radiohead", "Inrainbows") + assert (fixed.status, fixed.content_type) == ("found", "image/jpeg") + assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes" + assert (resolved.delta, wait.delta) == (1, 1) + + +def test_correction_by_search_text_is_resolved_by_the_worker(art_config, user, metric_delta): + resolved = metric_delta( + "scrobbler_art_correction_resolutions_total", input="search", result="found" + ) + art.request_correction(user.id, "Radiohead", "Inrainbows", "Radiohead", "In Rainbows", None) + art.resolve_one_pending() + assert override(user, "Radiohead", "Inrainbows").status == "found" + assert resolved.delta == 1 + + +def test_correction_that_finds_nothing_is_an_error_on_the_override(art_config, user, metric_delta): + nothing = metric_delta( + "scrobbler_art_correction_resolutions_total", input="search", result="not_found" + ) + art.request_correction(user.id, "Nobody", "Nothing", "Nobody", "Still Nothing", None) + art.resolve_one_pending() + failed = override(user, "Nobody", "Nothing") + assert (failed.status, failed.error_code) == ("error", "NotFound") + assert nothing.delta == 1 + + +def test_correction_with_a_failing_upstream_records_the_error(art_config, user): + art.request_correction(user.id, "Someone", "Boom", None, None, "rg-boom") + art.resolve_one_pending() + failed = override(user, "Someone", "Boom") + assert (failed.status, failed.error_code) == ("error", "HTTPError") + + +def test_worker_resolves_corrections_before_the_global_queue(art_config, user): + art.want("Radiohead", "In Rainbows") + art.request_correction(user.id, "X", "Y", None, None, "rg-found") + art.resolve_one_pending() + assert override(user, "X", "Y").status == "found" + assert row("Radiohead", "In Rainbows").status == "pending" + + +def test_failures_lists_only_the_users_failed_albums(art_config, user, make_user): + other = make_user(username="mallory") + scrobble_album(user, "A", "Missing", count=3) + scrobble_album(user, "A", "Fine", count=1) + scrobble_album(user, "A", "Unlooked", count=1) + scrobble_album(other, "B", "Theirs", count=1) + insert("A", "Missing", "not_found") + insert("A", "Fine", "found") + insert("B", "Theirs", "error") + items, total = art.list_failures(user.id, 1, 50) + assert total == 1 + assert [(i["artist"], i["album"], i["scrobbles"], i["status"]) for i in items] == [ + ("A", "Missing", 3, "not_found") + ] + assert items[0]["override"] is None + + +def test_failures_drops_fixed_albums_and_keeps_failed_corrections(art_config, user): + scrobble_album(user, "A", "Uploaded") + scrobble_album(user, "A", "Wrong", base=BASE + 500) + insert("A", "Uploaded", "not_found") + insert("A", "Wrong", "not_found") + art.save_upload(user.id, "A", "Uploaded", JPEG, "image/jpeg") + art.request_correction(user.id, "A", "Wrong", None, None, "rg-boom") + art.resolve_one_pending() + items, total = art.list_failures(user.id, 1, 50) + assert total == 1 + assert items[0]["album"] == "Wrong" + assert (items[0]["override"]["status"], items[0]["override"]["kind"]) == ("error", "correction") + + +def test_failures_paginates_most_scrobbled_first(art_config, user): + for i, count in enumerate((1, 3, 2)): + scrobble_album(user, "A", f"Album {i}", count=count, base=BASE + i * 100) + insert("A", f"Album {i}", "not_found") + items, total = art.list_failures(user.id, 1, 2) + assert (total, [i["album"] for i in items]) == (3, ["Album 1", "Album 2"]) + items, _ = art.list_failures(user.id, 2, 2) + assert [i["album"] for i in items] == ["Album 0"] diff --git a/tests/test_metrics.py b/tests/test_metrics.py index e4f91f3..19f2a52 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -90,6 +90,13 @@ def test_database_stats_collector(app, user, make_user): cache = {s.labels["status"]: s.value for s in families["scrobbler_art_cache"].samples} assert cache == {"pending": 0, "found": 0, "not_found": 0, "error": 0} assert families["scrobbler_art_oldest_pending_seconds"].samples[0].value == 0 + overrides = { + (s.labels["kind"], s.labels["status"]): s.value + for s in families["scrobbler_art_overrides"].samples + } + assert len(overrides) == 6 and not any(overrides.values()) + assert families["scrobbler_art_override_oldest_pending_seconds"].samples[0].value == 0 + assert families["scrobbler_art_unresolved_albums"].samples[0].value == 0 def test_database_stats_collector_caches(app, user): @@ -159,3 +166,26 @@ def test_gunicorn_aggregates_worker_metrics(app, tmp_path): ] assert openapi.value == 10 assert "scrobbler_users" in families + + +def test_database_stats_collector_counts_art_backlog(app, user): + from scrobbler.extensions import db + from scrobbler.models import AlbumArt, UserAlbumArt + + db.session.add_all( + [ + AlbumArt(artist="A", album="Lost", status="not_found"), + AlbumArt(artist="A", album="Fixed", status="error"), + AlbumArt(artist="A", album="Fine", status="found"), + UserAlbumArt(user_id=user.id, artist="a", album="fixed", kind="upload", status="found"), + UserAlbumArt( + user_id=user.id, artist="A", album="Waiting", kind="correction", status="pending" + ), + ] + ) + db.session.commit() + values = DatabaseStatsCollector(app.config["SQLALCHEMY_DATABASE_URI"]).values() + assert values["art_unresolved"] == 1 # "Lost"; "Fixed" has a user's upload + assert values["art_overrides"][("upload", "found")] == 1 + assert values["art_overrides"][("correction", "pending")] == 1 + assert values["art_override_oldest_pending"] >= 0 From 87edaafe1958f758bacdc40e82f9b25b8525fc3c Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 22:26:46 +0100 Subject: [PATCH 3/6] Add album art upload, correction, retry, delete and failures endpoints Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- docs/openapi.json | 514 +++++++++++++++++++++++++++++- src/scrobbler/api/art.py | 146 ++++++++- src/scrobbler/schemas/__init__.py | 52 ++- tests/test_art.py | 169 +++++++++- 4 files changed, 867 insertions(+), 14 deletions(-) diff --git a/docs/openapi.json b/docs/openapi.json index 10cd78c..b0fd646 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1542,7 +1542,7 @@ } }, "200": { - "description": "The album's cover art" + "description": "The album's cover art (JPEG, PNG or WebP)" }, "401": { "description": "Not authenticated", @@ -1559,7 +1559,358 @@ } }, "summary": "An album's cover art", - "description": "Served from a local cache that a background worker task keeps filled; this endpoint\nnever makes a live MusicBrainz/Cover Art Archive call, so it can't be slowed down by\none. An album seen for the first time returns 404 until the worker resolves it,\ntypically within a few seconds - cache this response client-side and retry later.", + "description": "Your own uploaded or corrected art comes first. Otherwise it's served from a local\ncache that a background worker task keeps filled; this endpoint never makes a live\nMusicBrainz/Cover Art Archive call, so it can't be slowed down by one. An album seen\nfor the first time returns 404 until the worker resolves it, typically within a few\nseconds - cache this response client-side and retry later.", + "tags": [ + "Art" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "post": { + "parameters": [ + { + "in": "query", + "name": "artist", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + }, + { + "in": "query", + "name": "album", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "415": { + "description": "Not a JPEG, PNG or WebP image", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Image too large", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "400": { + "description": "Empty file", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AlbumArtOverride" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/AlbumArtUpload" + } + } + } + }, + "summary": "Upload your own art for an album", + "description": "Replaces any earlier upload or correction of yours for this album. Only you see it.", + "tags": [ + "Art" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "delete": { + "parameters": [ + { + "in": "query", + "name": "artist", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + }, + { + "in": "query", + "name": "album", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "404": { + "description": "You have no art of your own for this album", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Remove your own art for an album", + "description": "The album goes back to the shared lookup result, if there is one.", + "tags": [ + "Art" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/art/album/correction": { + "put": { + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "202": { + "description": "Accepted", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AlbumArtOverride" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AlbumArtCorrection" + } + } + } + }, + "summary": "Correct a failed lookup", + "description": "Queues a new lookup with different search text, or straight from a MusicBrainz\nrelease-group ID. The background worker resolves it; poll the failures list, or just\nfetch the art later. Replaces any earlier upload or correction of yours.", + "tags": [ + "Art" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/art/album/retry": { + "post": { + "parameters": [ + { + "in": "query", + "name": "artist", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + }, + { + "in": "query", + "name": "album", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "required": true + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "409": { + "description": "Nothing to retry", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "202": { + "description": "Accepted" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Look an album up again", + "description": "Re-queues the shared lookup for an album whose search found nothing or failed.", + "tags": [ + "Art" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/art/failures": { + "get": { + "parameters": [ + { + "in": "query", + "name": "page", + "schema": { + "type": "integer", + "default": 1, + "minimum": 1 + }, + "required": false + }, + { + "in": "query", + "name": "limit", + "schema": { + "type": "integer", + "default": 50, + "minimum": 1, + "maximum": 200 + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AlbumArtFailuresPage" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Albums of yours without art", + "description": "Albums you've scrobbled whose lookup found nothing or failed, plus ones where your\nown correction didn't work, most-scrobbled first. Albums you've fixed drop off.", "tags": [ "Art" ], @@ -3443,7 +3794,7 @@ }, { "name": "Art", - "description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker" + "description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. You can also upload your own art, or correct a failed lookup; those only change what you see." }, { "name": "Health", @@ -4135,6 +4486,163 @@ ], "additionalProperties": false }, + "AlbumArtUpload": { + "type": "object", + "properties": { + "file": { + "description": "A JPEG, PNG or WebP image", + "type": "string", + "format": "binary" + } + }, + "required": [ + "file" + ], + "additionalProperties": false + }, + "AlbumArtOverride": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "description": "upload or correction" + }, + "status": { + "type": "string", + "description": "pending, found or error" + }, + "error_code": { + "type": [ + "string", + "null" + ] + }, + "search_artist": { + "type": [ + "string", + "null" + ] + }, + "search_album": { + "type": [ + "string", + "null" + ] + }, + "release_group_mbid": { + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "AlbumArtCorrection": { + "type": "object", + "properties": { + "artist": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "album": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "search_artist": { + "type": "string", + "minLength": 1, + "maxLength": 500, + "description": "Artist text to search MusicBrainz for, if it differs" + }, + "search_album": { + "type": "string", + "minLength": 1, + "maxLength": 500, + "description": "Album text to search MusicBrainz for, if it differs" + }, + "release_group_mbid": { + "type": "string", + "format": "uuid", + "description": "A MusicBrainz release-group ID; skips the search" + } + }, + "required": [ + "album", + "artist" + ], + "additionalProperties": false + }, + "AlbumArtFailure": { + "type": "object", + "properties": { + "artist": { + "type": "string" + }, + "album": { + "type": "string" + }, + "scrobbles": { + "type": "integer", + "description": "Your scrobbles of this album" + }, + "status": { + "type": "string", + "description": "The shared lookup: pending, not_found or error" + }, + "error_code": { + "type": [ + "string", + "null" + ] + }, + "checked_at": { + "type": [ + "string", + "null" + ], + "format": "date-time" + }, + "override": { + "description": "Your own fix, if any", + "anyOf": [ + { + "$ref": "#/components/schemas/AlbumArtOverride" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + "AlbumArtFailuresPage": { + "type": "object", + "properties": { + "page": { + "type": "integer" + }, + "per_page": { + "type": "integer" + }, + "total": { + "type": "integer" + }, + "total_pages": { + "type": "integer" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AlbumArtFailure" + } + } + }, + "additionalProperties": false + }, "Health": { "type": "object", "properties": { diff --git a/src/scrobbler/api/art.py b/src/scrobbler/api/art.py index 3131154..f21c350 100644 --- a/src/scrobbler/api/art.py +++ b/src/scrobbler/api/art.py @@ -1,31 +1,58 @@ -from flask import Response +import math + +from flask import Response, current_app, g, request from flask_smorest import Blueprint, abort from scrobbler import metrics from scrobbler.api.decorators import authenticated -from scrobbler.schemas import AlbumArtArgsSchema, ErrorSchema +from scrobbler.schemas import ( + AlbumArtArgsSchema, + AlbumArtCorrectionSchema, + AlbumArtFailuresPageSchema, + AlbumArtOverrideSchema, + AlbumArtUploadSchema, + ErrorSchema, + PageArgsSchema, +) from scrobbler.services import art blp = Blueprint( "Art", __name__, - description="Album art, resolved from MusicBrainz / Cover Art Archive by a background worker", + description=( + "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. " + "You can also upload your own art, or correct a failed lookup; those only change " + "what you see." + ), ) @blp.route("/album", methods=["GET"]) @authenticated(blp) @blp.arguments(AlbumArtArgsSchema, location="query") -@blp.response(200, content_type="image/jpeg", description="The album's cover art") +@blp.response( + 200, content_type="image/jpeg", description="The album's cover art (JPEG, PNG or WebP)" +) @blp.alt_response(404, schema=ErrorSchema, description="No cover art available yet") def album_art(args): """An album's cover art - Served from a local cache that a background worker task keeps filled; this endpoint - never makes a live MusicBrainz/Cover Art Archive call, so it can't be slowed down by - one. An album seen for the first time returns 404 until the worker resolves it, - typically within a few seconds - cache this response client-side and retry later. + Your own uploaded or corrected art comes first. Otherwise it's served from a local + cache that a background worker task keeps filled; this endpoint never makes a live + MusicBrainz/Cover Art Archive call, so it can't be slowed down by one. An album seen + for the first time returns 404 until the worker resolves it, typically within a few + seconds - cache this response client-side and retry later. """ + own = art.get_override(g.user.id, args["artist"], args["album"]) + if own is not None and own.status == "found": + data = art.read_override_file(own) + if data is not None: + metrics.art_requests_total.labels("override").inc() + response = Response(data, mimetype=own.content_type or "image/jpeg") + response.headers["Cache-Control"] = "private, no-cache" # revalidate: it can change + response.add_etag() + return response.make_conditional(request) + row = art.get_cached(args["artist"], args["album"]) if row is None: art.want(args["artist"], args["album"]) @@ -44,3 +71,106 @@ def album_art(args): response = Response(image, mimetype="image/jpeg") response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes return response + + +@blp.route("/album", methods=["POST"]) +@authenticated(blp) +@blp.arguments(AlbumArtUploadSchema, location="files") +@blp.arguments(AlbumArtArgsSchema, location="query") +@blp.response(201, AlbumArtOverrideSchema) +@blp.alt_response(400, schema=ErrorSchema, description="Empty file") +@blp.alt_response(413, schema=ErrorSchema, description="Image too large") +@blp.alt_response(415, schema=ErrorSchema, description="Not a JPEG, PNG or WebP image") +def upload_art(files, args): + """Upload your own art for an album + + Replaces any earlier upload or correction of yours for this album. Only you see it. + """ + limit = current_app.config["ART_UPLOAD_MAX_BYTES"] + data = files["file"].read(limit + 1) + if not data: + metrics.art_uploads_total.labels("empty").inc() + abort(400, code="empty_file", message="That file is empty.") + if len(data) > limit: + metrics.art_uploads_total.labels("too_large").inc() + abort(413, code="file_too_large", message="That image is larger than this server accepts.") + try: + content_type = art.sniff_image_type(data) + except art.UnsupportedImage: + metrics.art_uploads_total.labels("bad_type").inc() + abort(415, code="unsupported_image", message="Upload a JPEG, PNG or WebP image.") + art.save_upload(g.user.id, args["artist"], args["album"], data, content_type) + metrics.art_uploads_total.labels("ok").inc() + metrics.art_upload_bytes.observe(len(data)) + return art.get_override(g.user.id, args["artist"], args["album"]) + + +@blp.route("/album", methods=["DELETE"]) +@authenticated(blp) +@blp.arguments(AlbumArtArgsSchema, location="query") +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="You have no art of your own for this album") +def delete_override(args): + """Remove your own art for an album + + The album goes back to the shared lookup result, if there is one. + """ + if not art.delete_override(g.user.id, args["artist"], args["album"]): + abort(404, code="not_found", message="You have no art of your own for this album") + + +@blp.route("/album/correction", methods=["PUT"]) +@authenticated(blp) +@blp.arguments(AlbumArtCorrectionSchema) +@blp.response(202, AlbumArtOverrideSchema) +def correct_art(body): + """Correct a failed lookup + + Queues a new lookup with different search text, or straight from a MusicBrainz + release-group ID. The background worker resolves it; poll the failures list, or just + fetch the art later. Replaces any earlier upload or correction of yours. + """ + mbid = body.get("release_group_mbid") + art.request_correction( + g.user.id, + body["artist"], + body["album"], + body.get("search_artist"), + body.get("search_album"), + str(mbid) if mbid else None, + ) + return art.get_override(g.user.id, body["artist"], body["album"]) + + +@blp.route("/album/retry", methods=["POST"]) +@authenticated(blp) +@blp.arguments(AlbumArtArgsSchema, location="query") +@blp.response(202) +@blp.alt_response(409, schema=ErrorSchema, description="Nothing to retry") +def retry_art(args): + """Look an album up again + + Re-queues the shared lookup for an album whose search found nothing or failed. + """ + if not art.retry(args["artist"], args["album"]): + abort(409, code="nothing_to_retry", message="This album's art is found or already queued") + + +@blp.route("/failures", methods=["GET"]) +@authenticated(blp) +@blp.arguments(PageArgsSchema, location="query") +@blp.response(200, AlbumArtFailuresPageSchema) +def failures(args): + """Albums of yours without art + + Albums you've scrobbled whose lookup found nothing or failed, plus ones where your + own correction didn't work, most-scrobbled first. Albums you've fixed drop off. + """ + items, total = art.list_failures(g.user.id, args["page"], args["limit"]) + return { + "items": items, + "page": args["page"], + "per_page": args["limit"], + "total": total, + "total_pages": math.ceil(total / args["limit"]), + } diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index 67a098c..390c35e 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -2,7 +2,7 @@ validation and the generated OpenAPI document.""" from flask_smorest.fields import Upload -from marshmallow import Schema, fields, validate +from marshmallow import Schema, ValidationError, fields, validate, validates_schema class ErrorDetailSchema(Schema): @@ -160,6 +160,56 @@ class AlbumArtArgsSchema(Schema): album = fields.String(required=True, validate=validate.Length(min=1, max=500)) +class AlbumArtUploadSchema(Schema): + file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"}) + + +class AlbumArtCorrectionSchema(AlbumArtArgsSchema): + search_artist = fields.String( + validate=validate.Length(min=1, max=500), + metadata={"description": "Artist text to search MusicBrainz for, if it differs"}, + ) + search_album = fields.String( + validate=validate.Length(min=1, max=500), + metadata={"description": "Album text to search MusicBrainz for, if it differs"}, + ) + release_group_mbid = fields.UUID( + metadata={"description": "A MusicBrainz release-group ID; skips the search"} + ) + + @validates_schema + def _needs_a_correction(self, data, **kwargs): + if not any(k in data for k in ("search_artist", "search_album", "release_group_mbid")): + raise ValidationError("Give a search_artist, search_album or release_group_mbid") + + +class AlbumArtOverrideSchema(Schema): + kind = fields.String(metadata={"description": "upload or correction"}) + status = fields.String(metadata={"description": "pending, found or error"}) + error_code = fields.String(allow_none=True) + search_artist = fields.String(allow_none=True) + search_album = fields.String(allow_none=True) + release_group_mbid = fields.String(allow_none=True) + + +class AlbumArtFailureSchema(Schema): + artist = fields.String() + album = fields.String() + scrobbles = fields.Integer(metadata={"description": "Your scrobbles of this album"}) + status = fields.String( + metadata={"description": "The shared lookup: pending, not_found or error"} + ) + error_code = fields.String(allow_none=True) + checked_at = fields.DateTime(allow_none=True) + override = fields.Nested( + AlbumArtOverrideSchema, allow_none=True, metadata={"description": "Your own fix, if any"} + ) + + +class AlbumArtFailuresPageSchema(PageMetaSchema): + items = fields.List(fields.Nested(AlbumArtFailureSchema)) + + class TrackMetadataSchema(Schema): album = fields.String(allow_none=True) album_artist = fields.String(allow_none=True) diff --git a/tests/test_art.py b/tests/test_art.py index e9d5538..b4b3d3d 100644 --- a/tests/test_art.py +++ b/tests/test_art.py @@ -1,3 +1,4 @@ +import io import json import pathlib import threading @@ -9,10 +10,12 @@ import pytest from werkzeug.serving import make_server from scrobbler.extensions import db -from scrobbler.models import AlbumArt +from scrobbler.models import AlbumArt, UserAlbumArt from scrobbler.services import art, scrobbles from scrobbler.services.scrobbles import TrackInput +FOUND_MBID = "11111111-1111-1111-1111-111111111111" # a real-looking id the fake has art for + # Canned release-group matches, keyed by a substring of the Lucene search query we send. _RELEASE_GROUPS = { "In Rainbows": "rg-found", # has art @@ -38,7 +41,7 @@ def _fake_musicbrainz_caa(environ, start_response): ) return [body] - if path == "/release-group/rg-found/front-500": + if path in ("/release-group/rg-found/front-500", f"/release-group/{FOUND_MBID}/front-500"): body = b"\xff\xd8\xff\xe0fake-jpeg-bytes" headers = [("Content-Type", "image/jpeg"), ("Content-Length", str(len(body)))] start_response("200 OK", headers) @@ -581,3 +584,165 @@ def test_failures_paginates_most_scrobbled_first(art_config, user): assert (total, [i["album"] for i in items]) == (3, ["Album 1", "Album 2"]) items, _ = art.list_failures(user.id, 2, 2) assert [i["album"] for i in items] == ["Album 0"] + + +# --- per-user override endpoints ----------------------------------------------------------- + +ALBUM = "artist=Nobody&album=Nothing" + + +def upload(client, auth, data=JPEG, name="cover.jpg", query=ALBUM): + return client.post( + f"/api/v1/art/album?{query}", + headers=auth, + data={"file": (io.BytesIO(data), name)}, + content_type="multipart/form-data", + ) + + +def test_upload_requires_auth(client): + assert client.post(f"/api/v1/art/album?{ALBUM}").status_code == 401 + + +def test_upload_then_get_serves_the_users_image(client, auth, art_config, metric_delta): + ok = metric_delta("scrobbler_art_uploads_total", result="ok") + size = metric_delta("scrobbler_art_upload_bytes_count") + served = metric_delta("scrobbler_art_requests_total", result="override") + response = upload(client, auth) + assert response.status_code == 201 + assert response.get_json()["status"] == "found" + image = client.get(f"/api/v1/art/album?{ALBUM}", headers=auth) + assert image.status_code == 200 + assert image.data == JPEG + assert image.mimetype == "image/jpeg" + assert image.headers["Cache-Control"] == "private, no-cache" + assert (ok.delta, size.delta, served.delta) == (1, 1, 1) + + +def test_override_response_supports_conditional_requests(client, auth, art_config): + upload(client, auth) + first = client.get(f"/api/v1/art/album?{ALBUM}", headers=auth) + again = client.get( + f"/api/v1/art/album?{ALBUM}", headers={**auth, "If-None-Match": first.headers["ETag"]} + ) + assert again.status_code == 304 + + +def test_upload_keeps_the_png_content_type(client, auth, art_config): + upload(client, auth, data=b"\x89PNG\r\n\x1a\nxxxx", name="c.png") + assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).mimetype == "image/png" + + +def test_upload_beats_the_shared_cache(client, auth, art_config): + insert("Nobody", "Nothing", "not_found") + upload(client, auth) + assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).data == JPEG + + +def test_upload_is_only_visible_to_its_owner(client, auth, art_config, make_user): + from scrobbler.services.accounts import issue_ui_token + + upload(client, auth) + token = issue_ui_token(make_user(username="mallory")) + other = client.get(f"/api/v1/art/album?{ALBUM}", headers={"Authorization": f"Bearer {token}"}) + assert other.status_code == 404 + + +@pytest.mark.parametrize( + ("data", "status", "result"), + [(b"", 400, "empty"), (b"GIF89a....", 415, "bad_type"), (JPEG + b"x" * 100, 413, "too_large")], +) +def test_upload_rejects_bad_files( + client, auth, app, art_config, metric_delta, data, status, result +): + app.config["ART_UPLOAD_MAX_BYTES"] = 50 + try: + counted = metric_delta("scrobbler_art_uploads_total", result=result) + assert upload(client, auth, data=data).status_code == status + assert counted.delta == 1 + assert override_row() is None + finally: + app.config["ART_UPLOAD_MAX_BYTES"] = 5 * 1024 * 1024 + + +def override_row(): + return db.session.scalar(db.select(UserAlbumArt)) + + +def test_upload_requires_artist_and_album(client, auth, art_config): + assert upload(client, auth, query="artist=A").status_code == 422 + + +def test_delete_override_reverts_to_the_shared_cache(client, auth, art_config, metric_delta): + deleted = metric_delta("scrobbler_art_override_actions_total", action="override_deleted") + upload(client, auth) + assert client.delete(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 204 + assert client.get(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 404 + assert client.delete(f"/api/v1/art/album?{ALBUM}", headers=auth).status_code == 404 + assert deleted.delta == 1 + + +def test_correction_is_queued_without_touching_the_network( + client, auth, app, art_config, metric_delta +): + app.config.update( + MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/" + ) + queued = metric_delta("scrobbler_art_override_actions_total", action="correction_requested") + response = client.put( + "/api/v1/art/album/correction", + headers=auth, + json={"artist": "Radiohead", "album": "Inrainbows", "search_album": "In Rainbows"}, + ) + assert response.status_code == 202 + body = response.get_json() + assert (body["kind"], body["status"], body["search_album"]) == ( + "correction", + "pending", + "In Rainbows", + ) + assert queued.delta == 1 + + +def test_correction_then_worker_then_get(client, auth, art_config): + url = "/api/v1/art/album?artist=Radiohead&album=Inrainbows" + client.put( + "/api/v1/art/album/correction", + headers=auth, + json={"artist": "Radiohead", "album": "Inrainbows", "release_group_mbid": FOUND_MBID}, + ) + assert client.get(url, headers=auth).status_code == 404 # not resolved yet + art.resolve_one_pending() + assert client.get(url, headers=auth).data == b"\xff\xd8\xff\xe0fake-jpeg-bytes" + + +def test_correction_needs_something_to_correct_and_a_valid_mbid(client, auth): + url = "/api/v1/art/album/correction" + assert client.put(url, headers=auth, json={"artist": "A", "album": "B"}).status_code == 422 + bad = {"artist": "A", "album": "B", "release_group_mbid": "nope"} + assert client.put(url, headers=auth, json=bad).status_code == 422 + + +def test_retry_requeues_a_failed_lookup(client, auth, art_config, metric_delta): + retried = metric_delta("scrobbler_art_override_actions_total", action="retry_requested") + insert("Nobody", "Nothing", "not_found") + assert client.post(f"/api/v1/art/album/retry?{ALBUM}", headers=auth).status_code == 202 + assert row("Nobody", "Nothing").status == "pending" + assert client.post(f"/api/v1/art/album/retry?{ALBUM}", headers=auth).status_code == 409 + assert retried.delta == 1 + + +def test_failures_endpoint(client, auth, art_config, user): + scrobble_album(user, "Nobody", "Nothing", count=2) + insert("Nobody", "Nothing", "not_found") + body = client.get("/api/v1/art/failures", headers=auth).get_json() + assert (body["total"], body["total_pages"], body["page"]) == (1, 1, 1) + assert body["items"][0]["album"] == "Nothing" + assert body["items"][0]["scrobbles"] == 2 + assert body["items"][0]["override"] is None + upload(client, auth) + assert client.get("/api/v1/art/failures", headers=auth).get_json()["items"] == [] + + +def test_failures_requires_auth(client): + assert client.get("/api/v1/art/failures").status_code == 401 From bee83cb9f395b866be5a6a603ddab0c58d198122 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 22:27:18 +0100 Subject: [PATCH 4/6] Add manual album art panels, usage stats and alerts Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- deploy/grafana/dashboards/album-art.json | 588 ++++++++++++++++++++++- deploy/grafana/dashboards/usage.json | 125 +++++ deploy/prometheus/alerts.yml | 19 + 3 files changed, 728 insertions(+), 4 deletions(-) diff --git a/deploy/grafana/dashboards/album-art.json b/deploy/grafana/dashboards/album-art.json index 496f2e1..9365305 100644 --- a/deploy/grafana/dashboards/album-art.json +++ b/deploy/grafana/dashboards/album-art.json @@ -286,7 +286,7 @@ { "type": "timeseries", "title": "Responses / min by result", - "description": "queued = first sighting of an album; pending = still being resolved; unavailable = settled with no art.", + "description": "queued = first sighting of an album; pending = still being resolved; unavailable = settled with no art; override = served from the user's own upload/correction.", "datasource": { "type": "prometheus", "uid": "prometheus" @@ -340,7 +340,7 @@ }, { "type": "timeseries", - "title": "Endpoint latency (p95)", + "title": "Endpoint latency (p95) by endpoint", "description": "", "datasource": { "type": "prometheus", @@ -352,8 +352,8 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=\"Art.album_art\"}[$__rate_interval])))", - "legendFormat": "p95", + "expr": "histogram_quantile(0.95, sum by (le, endpoint) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=~\"Art[.].*\"}[$__rate_interval])))", + "legendFormat": "{{endpoint}}", "refId": "A" } ], @@ -750,6 +750,586 @@ "w": 12, "h": 8 } + }, + { + "type": "row", + "title": "Manual art", + "id": 17, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 41, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Uploads / min by result", + "description": "Anything other than ok was rejected: empty, too_large or bad_type.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_art_uploads_total[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 18, + "gridPos": { + "x": 0, + "y": 42, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Accepted upload size (p50 / p95)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(scrobbler_art_upload_bytes_bucket[$__rate_interval])))", + "legendFormat": "p50", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_art_upload_bytes_bucket[$__rate_interval])))", + "legendFormat": "p95", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 19, + "gridPos": { + "x": 12, + "y": 42, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Manual actions / min", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (action) (rate(scrobbler_art_override_actions_total[$__rate_interval])) * 60", + "legendFormat": "{{action}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 20, + "gridPos": { + "x": 0, + "y": 50, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Correction outcomes / min", + "description": "input is mbid (a release-group ID was given) or search (corrected text).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (input, result) (rate(scrobbler_art_correction_resolutions_total[$__rate_interval])) * 60", + "legendFormat": "{{input}} {{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 21, + "gridPos": { + "x": 12, + "y": 50, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Correction wait (p50 / p95)", + "description": "From the user asking for a correction to the worker finishing it.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.5, sum by (le) (rate(scrobbler_art_correction_wait_seconds_bucket[$__rate_interval])))", + "legendFormat": "p50", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_art_correction_wait_seconds_bucket[$__rate_interval])))", + "legendFormat": "p95", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 22, + "gridPos": { + "x": 0, + "y": 58, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Worker time per correction (p95)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_art_override_worker_seconds_bucket[$__rate_interval])))", + "legendFormat": "corrections", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_art_worker_resolve_seconds_bucket[$__rate_interval])))", + "legendFormat": "shared lookups", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 23, + "gridPos": { + "x": 12, + "y": 58, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "User art by kind and status", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (kind, status) (scrobbler_art_overrides)", + "legendFormat": "{{kind}} {{status}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 24, + "gridPos": { + "x": 0, + "y": 66, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Own art vs shared art served / min", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_art_requests_total{result=~\"override|served\"}[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 25, + "gridPos": { + "x": 12, + "y": 66, + "w": 12, + "h": 8 + } + }, + { + "type": "stat", + "title": "Oldest pending correction", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_art_override_oldest_pending_seconds)", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 26, + "gridPos": { + "x": 0, + "y": 74, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Albums needing manual art", + "description": "Not found or errored in the shared cache, and not fixed by any user.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_art_unresolved_albums)", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 27, + "gridPos": { + "x": 6, + "y": 74, + "w": 6, + "h": 5 + } } ] } diff --git a/deploy/grafana/dashboards/usage.json b/deploy/grafana/dashboards/usage.json index d230503..13da42d 100644 --- a/deploy/grafana/dashboards/usage.json +++ b/deploy/grafana/dashboards/usage.json @@ -989,6 +989,131 @@ "w": 12, "h": 8 } + }, + { + "type": "row", + "title": "Album art", + "id": 21, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 54, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "stat", + "title": "Albums needing manual art", + "description": "Not found or errored in the shared cache, and not fixed by any user. See the Album Art dashboard.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_art_unresolved_albums)", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 22, + "gridPos": { + "x": 0, + "y": 55, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Pending art corrections", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_art_overrides{kind=\"correction\",status=\"pending\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 23, + "gridPos": { + "x": 6, + "y": 55, + "w": 6, + "h": 5 + } } ] } diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml index 9bb7d7e..1c70c3e 100644 --- a/deploy/prometheus/alerts.yml +++ b/deploy/prometheus/alerts.yml @@ -125,6 +125,25 @@ groups: summary: Over half of {{ $labels.service }} album art calls are failing description: Failed lookups are cached as errors and retried later; check the upstream's status. + - alert: AlbumArtCorrectionBacklog + expr: max(scrobbler_art_override_oldest_pending_seconds) > 900 + for: 10m + labels: {severity: warning} + annotations: + summary: A manual album art correction has been waiting over 15 minutes + description: The worker is probably stopped, or MusicBrainz / Cover Art Archive is failing. + + - alert: AlbumArtUploadRejections + expr: | + sum(rate(scrobbler_art_uploads_total{result!="ok"}[30m])) + / sum(rate(scrobbler_art_uploads_total[30m])) > 0.5 + and sum(rate(scrobbler_art_uploads_total[30m])) > 0.002 + for: 30m + labels: {severity: warning} + annotations: + summary: Most album art uploads are being rejected + description: Check the Album Art dashboard for the reason (too_large suggests ART_UPLOAD_MAX_BYTES or a proxy limit; bad_type a client sending the wrong format). + - alert: PostgresDown expr: pg_up == 0 for: 2m From 9c84a64d4e268c474e3e0db17842813ceba147a4 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 22:27:58 +0100 Subject: [PATCH 5/6] Add album art page for uploading, retrying and correcting missing art Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- frontend/art.html | 22 +++++ frontend/css/style.css | 21 +++++ frontend/js/api.js | 6 +- frontend/js/art-failures.js | 170 ++++++++++++++++++++++++++++++++++++ frontend/js/art.js | 10 ++- frontend/js/layout.js | 1 + 6 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 frontend/art.html create mode 100644 frontend/js/art-failures.js diff --git a/frontend/art.html b/frontend/art.html new file mode 100644 index 0000000..294e55f --- /dev/null +++ b/frontend/art.html @@ -0,0 +1,22 @@ + + + + + + Album art · Scrobbler + + + + + + + +
+

Album art

+

Albums you've scrobbled that have no cover art.

+
+
    + +
    + + diff --git a/frontend/css/style.css b/frontend/css/style.css index 7b6f67d..9cd52d6 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -1149,3 +1149,24 @@ input { height: 2.25rem; align-self: center; /* .log li items default to stretch/start, which suits text, not art */ } + +/* ---- Album art: fixing missing art ---------------------------------------------- */ +.art-row { + display: grid; + grid-template-columns: 4rem minmax(0, 1fr); + gap: 1rem; + align-items: start; +} + +.art-thumb-lg { + width: 4rem; + height: 4rem; +} + +.art-row-body .muted { + margin: 0.35rem 0 0.75rem; +} + +.art-correction { + margin-top: 1rem; +} diff --git a/frontend/js/api.js b/frontend/js/api.js index 308f737..2104516 100644 --- a/frontend/js/api.js +++ b/frontend/js/api.js @@ -102,7 +102,7 @@ export async function api(path, { method = "GET", body, auth = true } = {}) { // Turn webargs validation details into a single readable sentence. export function describeError(error) { - const fields = error.details?.json ?? error.details?.query; + const fields = error.details?.json ?? error.details?.query ?? error.details?.files; if (fields) { return Object.entries(fields) .map(([field, messages]) => `${field}: ${[].concat(messages).join(" ")}`) @@ -112,10 +112,10 @@ export function describeError(error) { } // Multipart upload with progress (fetch can't report upload progress). -export function upload(path, formData, onProgress) { +export function upload(path, formData, onProgress, method = "POST") { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); - xhr.open("POST", `${apiBase}/api/v1${path}`); + xhr.open(method, `${apiBase}/api/v1${path}`); const token = getToken(); if (token) xhr.setRequestHeader("Authorization", `Bearer ${token}`); xhr.upload.addEventListener("progress", (event) => { diff --git a/frontend/js/art-failures.js b/frontend/js/art-failures.js new file mode 100644 index 0000000..ce2f5bb --- /dev/null +++ b/frontend/js/art-failures.js @@ -0,0 +1,170 @@ +import { api, describeError, upload } from "./api.js"; +import { artThumb, forgetArt } from "./art.js"; +import { errorBox, h, num, replace } from "./dom.js"; +import { signedInPage } from "./layout.js"; + +const PER_PAGE = 25; +const list = document.getElementById("albums"); +const messages = document.getElementById("messages"); +const pager = document.getElementById("pager"); +const page = Math.max(1, Number.parseInt(new URLSearchParams(location.search).get("page"), 10) || 1); + +await signedInPage("art.html"); +await refresh(); + +async function refresh() { + try { + render(await api(`/art/failures?page=${page}&limit=${PER_PAGE}`)); + } catch (error) { + replace(list, h("li", {}, errorBox(error.message))); + } +} + +function render(result) { + document.getElementById("art-summary").textContent = result.total + ? `${num(result.total)} of your albums have no cover art, most-played first. Upload a picture, retry the lookup, or correct what it searches for.` + : "Every album you've scrobbled has cover art, or is still being looked up."; + if (!result.items.length) { + replace(list); + } else { + replace(list, result.items.map(albumRow)); + } + replace( + pager, + result.page > 1 ? h("a", { class: "button button-quiet", href: `?page=${result.page - 1}` }, "Previous") : h("span"), + result.page < result.total_pages + ? h("a", { class: "button button-quiet", href: `?page=${result.page + 1}` }, "Next") + : h("span"), + ); +} + +function statusText(item) { + const own = item.override; + if (own?.status === "pending") return "Your correction is waiting to be looked up."; + if (own?.status === "error") { + return own.error_code === "NotFound" + ? "Your correction didn't find any art." + : `Your correction failed (${own.error_code ?? "unknown error"}).`; + } + if (item.status === "error") return `The lookup failed (${item.error_code ?? "unknown error"}). It will be tried again.`; + if (item.status === "not_found") return "No cover art was found for this album."; + return "Waiting to be looked up."; +} + +function say(notice) { + replace(messages, notice); +} + +function albumRow(item) { + const { artist, album } = item; + const query = `artist=${encodeURIComponent(artist)}&album=${encodeURIComponent(album)}`; + const fileInput = h("input", { type: "file", accept: "image/jpeg,image/png,image/webp", hidden: true }); + const correction = correctionForm(item, query); + const buttons = h("div", { class: "button-row" }); + const busy = (on) => buttons.querySelectorAll("button").forEach((b) => (b.disabled = on)); + + async function act(work, done) { + busy(true); + replace(messages); + try { + await work(); + say(h("p", { class: "notice notice-ok", role: "status" }, done)); + forgetArt(artist, album); + await refresh(); + } catch (error) { + say(errorBox(describeError(error))); + } finally { + busy(false); + } + } + + fileInput.addEventListener("change", () => { + const file = fileInput.files[0]; + if (!file) return; + const data = new FormData(); + data.append("file", file); + act(() => upload(`/art/album?${query}`, data), `Uploaded art for ${album}.`); + fileInput.value = ""; + }); + + replace( + buttons, + h("button", { type: "button", class: "button", onclick: () => fileInput.click() }, "Upload art"), + h( + "button", + { + type: "button", + class: "button button-quiet", + onclick: () => act(() => api(`/art/album/retry?${query}`, { method: "POST" }), `Looking up ${album} again.`), + }, + "Retry lookup", + ), + h( + "button", + { type: "button", class: "button button-quiet", onclick: () => (correction.hidden = !correction.hidden) }, + "Correct search", + ), + item.override + ? h( + "button", + { + type: "button", + class: "button button-quiet", + onclick: () => act(() => api(`/art/album?${query}`, { method: "DELETE" }), `Removed your correction for ${album}.`), + }, + "Remove mine", + ) + : null, + ); + correction.addEventListener("submit", (event) => { + event.preventDefault(); + const body = { artist, album }; + const { search_artist, search_album, release_group_mbid } = correction.elements; + if (search_artist.value.trim()) body.search_artist = search_artist.value.trim(); + if (search_album.value.trim()) body.search_album = search_album.value.trim(); + if (release_group_mbid.value.trim()) body.release_group_mbid = release_group_mbid.value.trim(); + act(() => api("/art/album/correction", { method: "PUT", body }), `Queued a corrected lookup for ${album}.`); + }); + + return h( + "li", + { class: "art-row" }, + artThumb(artist, album, "art-thumb-lg"), + h( + "div", + { class: "art-row-body" }, + h("span", { class: "row-title" }, album), + h("span", { class: "by" }, ` by ${artist}`), + h("p", { class: "muted" }, `${num(item.scrobbles)} ${item.scrobbles === 1 ? "scrobble" : "scrobbles"} · ${statusText(item)}`), + buttons, + fileInput, + correction, + ), + ); +} + +function correctionForm(item, query) { + const own = item.override ?? {}; + const field = (name, label, value, hint, extra = {}) => + h( + "div", + { class: "field" }, + h("label", { for: `${name}-${query}` }, label), + h("input", { id: `${name}-${query}`, name, type: "text", value: value ?? "", autocomplete: "off", ...extra }), + hint ? h("p", { class: "hint" }, hint) : null, + ); + return h( + "form", + { class: "stacked-form art-correction", hidden: true }, + field("search_artist", "Search for artist", own.search_artist ?? item.artist), + field("search_album", "Search for album", own.search_album ?? item.album), + field( + "release_group_mbid", + "MusicBrainz release-group ID (optional)", + own.release_group_mbid, + "If you know it, paste the ID from the album's MusicBrainz page. It skips the search.", + { placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" }, + ), + h("button", { type: "submit", class: "button" }, "Look it up"), + ); +} diff --git a/frontend/js/art.js b/frontend/js/art.js index 35154fb..a59f010 100644 --- a/frontend/js/art.js +++ b/frontend/js/art.js @@ -6,12 +6,20 @@ import { h } from "./dom.js"; const cache = new Map(); // dedupes repeat/concurrent lookups for the same album within a page +const keyFor = (artist, album) => `${artist.toLowerCase()}␟${album.toLowerCase()}`; + +// Forget a looked-up album (after the user uploads or corrects its art) so the next +// artThumb() for it asks the server again instead of reusing the stale answer. +export function forgetArt(artist, album) { + cache.delete(keyFor(artist, album)); +} + export function artThumb(artist, album, extraClass) { const classes = extraClass ? `art-thumb ${extraClass}` : "art-thumb"; const el = h("div", { class: `${classes} art-thumb-empty` }); if (!album) return el; // nothing to look up - const key = `${artist.toLowerCase()}␟${album.toLowerCase()}`; + const key = keyFor(artist, album); if (!cache.has(key)) { cache.set( key, diff --git a/frontend/js/layout.js b/frontend/js/layout.js index feb134d..2e5deb1 100644 --- a/frontend/js/layout.js +++ b/frontend/js/layout.js @@ -6,6 +6,7 @@ import { h, replace } from "./dom.js"; const NAV = [ ["index.html", "Overview"], ["history.html", "History"], + ["art.html", "Album art"], ["apps.html", "Apps"], ["sessions.html", "Sessions"], ["import.html", "Import"], From 524b78a0757675004a4510caa6815ee25047fb05 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 22:31:28 +0100 Subject: [PATCH 6/6] Document user-uploaded album art in the admin guide Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- docs/admin-guide.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/admin-guide.md b/docs/admin-guide.md index c0a9ac5..e521443 100644 --- a/docs/admin-guide.md +++ b/docs/admin-guide.md @@ -60,6 +60,7 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP | `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | | `MUSICBRAINZ_CONTACT` | api, worker | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) | | `ART_STORAGE_DIR` | api, worker | `var/album-art` | Where downloaded album art is stored; the worker writes it, the api serves it — both need access to the same directory (`docker compose` mounts a shared volume there) | +| `ART_UPLOAD_MAX_BYTES` | api | 5 MB | Largest image a user may upload as their own album art. A reverse proxy in front of the api needs a body limit at least this large | | `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | | `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | | `API_BASE_URL` | ui image | `http://localhost:5050` | Where the browser reaches the API — written into `config.js` and the CSP | @@ -192,9 +193,11 @@ Restoring an older dump with federation on will leave followers pointed at posts longer exist and profile data that's gone stale — expected after any point-in-time restore, not a sign anything's broken. -The `album-art-data` volume is just a disposable cache of downloaded cover art — losing it -isn't a data-loss event, the worker simply re-downloads anything missing the next time it's -requested. No need to include it in backups. +The `album-art-data` volume holds two kinds of file. Cover art the worker downloaded is a +disposable cache — it's simply re-downloaded the next time it's requested. Images users +**upload** (and the art from their manual corrections) live under `user/` in the same +volume and can't be re-created, so include the volume in your backups. The database rows +that point at them are in `user_album_art`; restore the two together. ## Upgrades