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