Stop album art from blocking page loads
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m39s
CI / test (push) Successful in 3m38s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / trigger-deploy (push) Skipped
CI / notify (push) Successful in 5s

Root cause: gunicorn runs only 2 sync workers, and GET /api/v1/art/album
did its MusicBrainz + Cover Art Archive work synchronously inside the
request (2-12+ seconds per call, measured). A page with several
uncached albums could tie up the entire application - every endpoint,
every user - for as long as that took. Separately, even an
already-resolved album re-streamed its image bytes live from Cover
Art Archive on every single page view, by the original v1 design.

The endpoint is now cache-only: it reads the album_art table and, if
resolved, a local file, and never touches the network. A cache miss
records a "pending" row and returns 404 immediately - the frontend
already treats 404 as "show the placeholder," so no frontend changes
are needed. A new background worker task (the same claim-with-
FOR-UPDATE-SKIP-LOCKED pattern already used by imports and federation
deliveries) does the actual resolving and downloads the image bytes
to a shared volume, completely decoupled from any request. No
migration needed: AlbumArt.status just gains a new "pending" value.

Verified against the real docker compose stack (not just the test
suite): cold lookups for 5 real albums all returned 404 in well under
0.2s (previously 2-12+s each), the worker resolved all 5 within ~10s
in the background, and resolved art then served in single-digit
milliseconds from the volume, including after a full container
restart (no re-download).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Hn2QwS1HRT8tFAzo8ew63
This commit is contained in:
mattandClaude Sonnet 5 committed 2026-10-06 21:27:50 +01:00
1 parent 79193fbc8e
commit 83b27d7ba1
11 files changed
+345 -68

No files matched your search

+3
View File
@@ -19,6 +19,9 @@ LASTFM_API_KEY=
# Album art (MusicBrainz + Cover Art Archive, both free and keyless — no setup required). # Album art (MusicBrainz + Cover Art Archive, both free and keyless — no setup required).
# MusicBrainz asks for a contact URL/email in requests; falls back to UI_BASE_URL if unset. # MusicBrainz asks for a contact URL/email in requests; falls back to UI_BASE_URL if unset.
MUSICBRAINZ_CONTACT= 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
# docker compose host ports (defaults shown) # docker compose host ports (defaults shown)
API_PORT=5050 API_PORT=5050
+1
View File
@@ -15,6 +15,7 @@ htmlcov/
# Runtime # Runtime
prometheus_multiproc/ prometheus_multiproc/
var/album-art/
# IDEs # IDEs
.idea/ .idea/
+8
View File
@@ -35,6 +35,7 @@ services:
FORWARDED_ALLOW_IPS: "*" FORWARDED_ALLOW_IPS: "*"
LASTFM_API_KEY: ${LASTFM_API_KEY:-} LASTFM_API_KEY: ${LASTFM_API_KEY:-}
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-} MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0} FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-} FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-} FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
@@ -43,6 +44,8 @@ services:
- "${API_PORT:-5050}:8000" - "${API_PORT:-5050}:8000"
expose: expose:
- "9100" # metrics: internal network only - "9100" # metrics: internal network only
volumes:
- album-art-data:/data/album-art
depends_on: depends_on:
db: db:
condition: service_healthy condition: service_healthy
@@ -58,6 +61,8 @@ services:
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
SECRET_KEY: ${SECRET_KEY:-change-me} SECRET_KEY: ${SECRET_KEY:-change-me}
LASTFM_API_KEY: ${LASTFM_API_KEY:-} LASTFM_API_KEY: ${LASTFM_API_KEY:-}
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0} FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0}
FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-} FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-}
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-} FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
@@ -65,6 +70,8 @@ services:
RUN_MIGRATIONS: "0" # the api service applies them RUN_MIGRATIONS: "0" # the api service applies them
expose: expose:
- "9101" # metrics: internal network only - "9101" # metrics: internal network only
volumes:
- album-art-data:/data/album-art
healthcheck: healthcheck:
disable: true disable: true
depends_on: depends_on:
@@ -124,5 +131,6 @@ services:
volumes: volumes:
db-data: db-data:
album-art-data:
prometheus-data: prometheus-data:
grafana-data: grafana-data:
+2
View File
@@ -13,6 +13,8 @@ RUN uv sync --locked --no-dev --no-editable
FROM python:3.13-slim FROM python:3.13-slim
LABEL org.opencontainers.image.licenses="BSD-3-Clause" LABEL org.opencontainers.image.licenses="BSD-3-Clause"
RUN useradd --system --uid 10001 --no-create-home scrobbler RUN useradd --system --uid 10001 --no-create-home scrobbler
# Downloaded album art lives here, on a volume shared with the worker (which writes it).
RUN mkdir -p /data/album-art && chown scrobbler:scrobbler /data/album-art
WORKDIR /app WORKDIR /app
COPY --from=build /app/.venv /app/.venv COPY --from=build /app/.venv /app/.venv
COPY gunicorn.conf.py docker/api-entrypoint.sh ./ COPY gunicorn.conf.py docker/api-entrypoint.sh ./
+12 -3
View File
@@ -16,8 +16,12 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana
- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages. - **`api`**: Flask under gunicorn. API-only; it serves no HTML pages.
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step). - **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
- **`worker`**: `flask worker` — history imports and background tasks for optional - **`worker`**: `flask worker` — history imports, resolving and downloading album art
modules (federation's deliveries, scheduled posts, and so on). (MusicBrainz + Cover Art Archive), and background tasks for optional modules
(federation's deliveries, scheduled posts, and so on). This is the only service that
makes outbound calls to third-party APIs (Last.fm, MusicBrainz, Cover Art Archive, and
remote fediverse servers with federation on) — worth knowing if you're restricting
egress.
- **`db`**: PostgreSQL. - **`db`**: PostgreSQL.
- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`. - With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`.
@@ -54,7 +58,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers | | `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | | `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 | `UI_BASE_URL` | Contact URL/email sent to MusicBrainz for album art lookups (no key needed, but they ask for one) | | `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) |
| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | | `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted |
| `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | | `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 | | `API_BASE_URL` | ui image | `http://localhost:5050` | Where the browser reaches the API — written into `config.js` and the CSP |
@@ -187,6 +192,10 @@ 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 longer exist and profile data that's gone stale — expected after any point-in-time
restore, not a sign anything's broken. 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.
## Upgrades ## Upgrades
```sh ```sh
+3 -13
View File
@@ -1531,18 +1531,8 @@
"422": { "422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT" "$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
}, },
"502": {
"description": "MusicBrainz or Cover Art Archive is unreachable",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": { "404": {
"description": "No cover art found for this album", "description": "No cover art available yet",
"content": { "content": {
"application/json": { "application/json": {
"schema": { "schema": {
@@ -1569,7 +1559,7 @@
} }
}, },
"summary": "An album's cover art", "summary": "An album's cover art",
"description": "Resolved via MusicBrainz + Cover Art Archive and cached; bytes are proxied on every\ncall, so cache this response client-side.", "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.",
"tags": [ "tags": [
"Art" "Art"
], ],
@@ -3453,7 +3443,7 @@
}, },
{ {
"name": "Art", "name": "Art",
"description": "Album art, proxied from MusicBrainz / Cover Art Archive" "description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker"
}, },
{ {
"name": "Health", "name": "Health",
+2
View File
@@ -42,11 +42,13 @@ def create_app(config_object=None):
) )
from scrobbler.cli import imports_cli, worker_command from scrobbler.cli import imports_cli, worker_command
from scrobbler.services import art as art_service
from scrobbler.services import imports as import_service from scrobbler.services import imports as import_service
app.cli.add_command(worker_command) app.cli.add_command(worker_command)
app.cli.add_command(imports_cli) app.cli.add_command(imports_cli)
import_service.register_worker_tasks(app) import_service.register_worker_tasks(app)
art_service.register_worker_tasks(app)
from scrobbler.metrics import db as db_metrics from scrobbler.metrics import db as db_metrics
+17 -20
View File
@@ -6,7 +6,9 @@ from scrobbler.schemas import AlbumArtArgsSchema, ErrorSchema
from scrobbler.services import art from scrobbler.services import art
blp = Blueprint( blp = Blueprint(
"Art", __name__, description="Album art, proxied from MusicBrainz / Cover Art Archive" "Art",
__name__,
description="Album art, resolved from MusicBrainz / Cover Art Archive by a background worker",
) )
@@ -14,29 +16,24 @@ blp = Blueprint(
@authenticated(blp) @authenticated(blp)
@blp.arguments(AlbumArtArgsSchema, location="query") @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")
@blp.alt_response(404, schema=ErrorSchema, description="No cover art found for this album") @blp.alt_response(404, schema=ErrorSchema, description="No cover art available yet")
@blp.alt_response(
502, schema=ErrorSchema, description="MusicBrainz or Cover Art Archive is unreachable"
)
def album_art(args): def album_art(args):
"""An album's cover art """An album's cover art
Resolved via MusicBrainz + Cover Art Archive and cached; bytes are proxied on every Served from a local cache that a background worker task keeps filled; this endpoint
call, so cache this response client-side. 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.
""" """
result = art.lookup(args["artist"], args["album"]) row = art.get_cached(args["artist"], args["album"])
if result.status == "not_found": if row is None:
art.want(args["artist"], args["album"])
abort(404, code="no_album_art", message="Not resolved yet")
image = art.read_file(row.id) if row.status == "found" else None
if image is None:
if row.status == "found":
art.requeue(row) # resolved before, but the file is missing - ask again
abort(404, code="no_album_art", message="No cover art found for this album") abort(404, code="no_album_art", message="No cover art found for this album")
if result.status == "error": response = Response(image, mimetype="image/jpeg")
abort(
502,
code="art_upstream_unavailable",
message="Couldn't reach MusicBrainz or Cover Art Archive",
)
try:
image = art.fetch_image(result.image_url)
except art.ArtFetchFailed:
abort(502, code="art_upstream_unavailable", message="Couldn't reach Cover Art Archive")
response = Response(image.body, mimetype=image.content_type)
response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes
return response return response
+3
View File
@@ -64,6 +64,9 @@ class Config:
MUSICBRAINZ_RETRIES = int(os.environ.get("MUSICBRAINZ_RETRIES", "2")) MUSICBRAINZ_RETRIES = int(os.environ.get("MUSICBRAINZ_RETRIES", "2"))
ART_NOT_FOUND_RETRY_DAYS = int(os.environ.get("ART_NOT_FOUND_RETRY_DAYS", "30")) ART_NOT_FOUND_RETRY_DAYS = int(os.environ.get("ART_NOT_FOUND_RETRY_DAYS", "30"))
ART_ERROR_RETRY_SECONDS = int(os.environ.get("ART_ERROR_RETRY_SECONDS", "3600")) ART_ERROR_RETRY_SECONDS = int(os.environ.get("ART_ERROR_RETRY_SECONDS", "3600"))
# 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")
IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 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 MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
+137 -12
View File
@@ -3,8 +3,17 @@
Every (artist, album) lookup is cached in `AlbumArt` — a miss or an error is cached too, so Every (artist, album) lookup is cached in `AlbumArt` — a miss or an error is cached too, so
repeat requests for an album we can't find art for don't keep hammering the upstream APIs. repeat requests for an album we can't find art for don't keep hammering the upstream APIs.
`lookup()` resolves *where* the art is (and never raises); `fetch_image()` streams the bytes `lookup()` resolves *where* the art is (and never raises); `fetch_image()` streams the bytes
from there. They're kept separate so that storing the bytes ourselves later only needs to from there.
change `fetch_image()`, not the caching/lookup logic.
`lookup()` itself is still a live, synchronous resolution — fine for its one caller
(`federation/publishing/now_playing.py`, already running from a background worker task, not
a request). The web-facing `/api/v1/art/album` endpoint does NOT call `lookup()`: it only
ever reads via `get_cached()`/`read_file()`, both pure local reads with no network call, so
a page can never be slowed down by a MusicBrainz/Cover Art Archive round trip. A cache miss
there calls `want()` (a fast DB write, "please resolve this") instead, and a background
worker task (`resolve_one_pending()`, registered by `register_worker_tasks()`) does the
actual resolving plus downloading the image bytes to `ART_STORAGE_DIR`, completely
decoupled from any request.
""" """
import json import json
@@ -16,9 +25,10 @@ import urllib.parse
import urllib.request import urllib.request
from dataclasses import dataclass from dataclasses import dataclass
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from pathlib import Path
from flask import current_app from flask import current_app
from sqlalchemy import func, select from sqlalchemy import func, or_, select
from sqlalchemy.dialects.postgresql import insert from sqlalchemy.dialects.postgresql import insert
from scrobbler.extensions import db from scrobbler.extensions import db
@@ -132,29 +142,37 @@ def _cover_art_url(release_group_mbid: str) -> str | None:
raise TimeoutError("Cover Art Archive request exhausted its retries") raise TimeoutError("Cover Art Archive request exhausted its retries")
def lookup(artist: str, album: str) -> ArtResult: def get_cached(artist: str, album: str) -> AlbumArt | None:
"""Cached (artist, album) art resolution. Never raises.""" """Plain cache read by (artist, album). No network, no write."""
existing = db.session.scalar( return db.session.scalar(
select(AlbumArt).where( select(AlbumArt).where(
func.lower(AlbumArt.artist) == artist.lower(), func.lower(AlbumArt.artist) == artist.lower(),
func.lower(AlbumArt.album) == album.lower(), func.lower(AlbumArt.album) == album.lower(),
) )
) )
if existing is not None and not _stale(existing):
return ArtResult(existing.status, existing.image_url)
def _resolve(artist: str, album: str) -> tuple[ArtResult, str | None, str | None]:
"""Live MusicBrainz + Cover Art Archive resolution, no caching involved. Returns
(result, release_group_mbid, error_code). Never raises."""
release_group_mbid = None release_group_mbid = None
try: try:
release_group_mbid = _find_release_group(artist, album) release_group_mbid = _find_release_group(artist, album)
image_url = _cover_art_url(release_group_mbid) if release_group_mbid else None image_url = _cover_art_url(release_group_mbid) if release_group_mbid else None
status = "found" if image_url else "not_found" status = "found" if image_url else "not_found"
result = ArtResult(status, image_url) return ArtResult(status, image_url), release_group_mbid, None
error_code = None
except Exception as err: # noqa: BLE001 - any upstream failure degrades to a cached "error" except Exception as err: # noqa: BLE001 - any upstream failure degrades to a cached "error"
log.warning("Album art lookup failed for %r/%r: %s", artist, album, err) log.warning("Album art lookup failed for %r/%r: %s", artist, album, err)
result = ArtResult("error") return ArtResult("error"), release_group_mbid, type(err).__name__
error_code = type(err).__name__
def _store(
artist: str,
album: str,
result: ArtResult,
release_group_mbid: str | None,
error_code: str | None,
) -> None:
values = { values = {
"artist": artist, "artist": artist,
"album": album, "album": album,
@@ -170,9 +188,53 @@ def lookup(artist: str, album: str) -> ArtResult:
) )
db.session.execute(stmt) db.session.execute(stmt)
db.session.commit() db.session.commit()
def lookup(artist: str, album: str) -> ArtResult:
"""Cached (artist, album) art resolution, resolving live on a cache miss. Never
raises. Used by ActivityPub posting, which already runs from a worker task - not
used by the web-facing endpoint, which must never block on a live lookup (see
get_cached()/want() below)."""
existing = get_cached(artist, album)
if existing is not None and not _stale(existing):
return ArtResult(existing.status, existing.image_url)
result, release_group_mbid, error_code = _resolve(artist, album)
_store(artist, album, result, release_group_mbid, error_code)
return result return result
def want(artist: str, album: str) -> None:
"""Record that we'd like art for (artist, album), for the background worker to
resolve. A fast, network-free write; a no-op if a row already exists (any status)."""
stmt = insert(AlbumArt).values(
artist=artist, album=album, status="pending", checked_at=datetime.now(UTC)
)
stmt = stmt.on_conflict_do_nothing(
index_elements=[func.lower(AlbumArt.artist), func.lower(AlbumArt.album)]
)
db.session.execute(stmt)
db.session.commit()
def requeue(row: AlbumArt) -> None:
"""Asks the worker to (re)resolve a row - used when a 'found' row's file has gone
missing (e.g. one resolved before local file storage existed)."""
row.status = "pending"
db.session.commit()
def _file_path(row_id: int) -> Path:
return Path(current_app.config["ART_STORAGE_DIR"]) / f"{row_id}.jpg"
def read_file(row_id: int) -> bytes | None:
"""The downloaded image bytes for a resolved row, or None if not downloaded."""
try:
return _file_path(row_id).read_bytes()
except FileNotFoundError:
return None
def fetch_image(image_url: str) -> ImageBytes: def fetch_image(image_url: str) -> ImageBytes:
"""Streams the bytes from image_url. Raises ArtFetchFailed on any problem.""" """Streams the bytes from image_url. Raises ArtFetchFailed on any problem."""
try: try:
@@ -180,3 +242,66 @@ def fetch_image(image_url: str) -> ImageBytes:
return ImageBytes(response.read(), response.headers.get("Content-Type", "image/jpeg")) return ImageBytes(response.read(), response.headers.get("Content-Type", "image/jpeg"))
except (urllib.error.URLError, TimeoutError) as err: except (urllib.error.URLError, TimeoutError) as err:
raise ArtFetchFailed(str(err)) from err raise ArtFetchFailed(str(err)) from err
# --- Worker --------------------------------------------------------------------------
def _claim_pending() -> AlbumArt | None:
"""Atomically takes one row due for resolution (new, or a stale not_found/error)."""
not_found_cutoff = datetime.now(UTC) - timedelta(
days=current_app.config["ART_NOT_FOUND_RETRY_DAYS"]
)
error_cutoff = datetime.now(UTC) - timedelta(
seconds=current_app.config["ART_ERROR_RETRY_SECONDS"]
)
row = db.session.scalar(
select(AlbumArt)
.where(
or_(
AlbumArt.status == "pending",
(AlbumArt.status == "not_found") & (AlbumArt.checked_at < not_found_cutoff),
(AlbumArt.status == "error") & (AlbumArt.checked_at < error_cutoff),
)
)
.order_by(AlbumArt.checked_at)
.limit(1)
.with_for_update(skip_locked=True)
)
if row is None:
db.session.rollback()
return row
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."""
row = _claim_pending()
if row is None:
return False
result, release_group_mbid, error_code = _resolve(row.artist, row.album)
if result.status == "found":
try:
image = fetch_image(result.image_url)
path = _file_path(row.id)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(image.body)
except ArtFetchFailed as err:
log.warning("Album art download failed for %r/%r: %s", row.artist, row.album, err)
result, error_code = ArtResult("error"), "ArtFetchFailed"
row.status = result.status
row.image_url = result.image_url
row.release_group_mbid = release_group_mbid
row.error_code = error_code
row.checked_at = datetime.now(UTC)
db.session.commit()
return True
def register_worker_tasks(app) -> None:
from scrobbler import worker
worker.register_task(app, "art", resolve_one_pending)
+157 -20
View File
@@ -1,4 +1,5 @@
import json import json
import pathlib
import threading import threading
import urllib.parse import urllib.parse
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
@@ -14,7 +15,8 @@ from scrobbler.services import art
_RELEASE_GROUPS = { _RELEASE_GROUPS = {
"In Rainbows": "rg-found", # has art "In Rainbows": "rg-found", # has art
"No Art Album": "rg-no-art", # MB match, but Cover Art Archive has nothing "No Art Album": "rg-no-art", # MB match, but Cover Art Archive has nothing
"Boom Album": "rg-boom", # MB match, but Cover Art Archive 500s "Boom Album": "rg-boom", # MB match, but Cover Art Archive 500s on HEAD
"Download Fail Album": "rg-dl-fail", # HEAD succeeds, but the GET download 500s
} }
@@ -44,6 +46,13 @@ def _fake_musicbrainz_caa(environ, start_response):
start_response("500 Internal Server Error", [("Content-Type", "text/plain")]) start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
return [b"boom"] return [b"boom"]
if path == "/release-group/rg-dl-fail/front-500":
if method == "HEAD":
start_response("200 OK", [("Content-Type", "image/jpeg")])
return []
start_response("500 Internal Server Error", [("Content-Type", "text/plain")])
return [b"boom"]
start_response("404 Not Found", [("Content-Type", "text/plain")]) start_response("404 Not Found", [("Content-Type", "text/plain")])
return [b"not found"] return [b"not found"]
@@ -58,12 +67,13 @@ def fake_art_api():
@pytest.fixture @pytest.fixture
def art_config(app, fake_art_api): def art_config(app, fake_art_api, tmp_path):
keys = ( keys = (
"MUSICBRAINZ_API_URL", "MUSICBRAINZ_API_URL",
"COVERART_API_URL", "COVERART_API_URL",
"MUSICBRAINZ_REQUEST_INTERVAL", "MUSICBRAINZ_REQUEST_INTERVAL",
"MUSICBRAINZ_RETRIES", "MUSICBRAINZ_RETRIES",
"ART_STORAGE_DIR",
) )
saved = {k: app.config[k] for k in keys} saved = {k: app.config[k] for k in keys}
app.config.update( app.config.update(
@@ -71,6 +81,7 @@ def art_config(app, fake_art_api):
COVERART_API_URL=fake_art_api, COVERART_API_URL=fake_art_api,
MUSICBRAINZ_REQUEST_INTERVAL=0, MUSICBRAINZ_REQUEST_INTERVAL=0,
MUSICBRAINZ_RETRIES=0, MUSICBRAINZ_RETRIES=0,
ART_STORAGE_DIR=str(tmp_path),
) )
yield yield
app.config.update(saved) app.config.update(saved)
@@ -98,7 +109,7 @@ def insert(artist, album, status, days_ago=0.0, image_url=None):
db.session.commit() db.session.commit()
# --- lookup() ------------------------------------------------------------------------------ # --- lookup() (still live-resolving: used by ActivityPub posting, out of scope here) -----------
def test_lookup_finds_art(art_config): def test_lookup_finds_art(art_config):
@@ -142,9 +153,6 @@ def test_lookup_is_case_insensitive_and_cached(app, art_config):
def test_lookup_fresh_cache_hit_skips_the_network(app, art_config, fake_art_api): def test_lookup_fresh_cache_hit_skips_the_network(app, art_config, fake_art_api):
insert("Fresh Artist", "Fresh Album", "not_found", days_ago=0) insert("Fresh Artist", "Fresh Album", "not_found", days_ago=0)
# If this weren't a cache hit, the (nonexistent) search term would still return "not_found"
# from the live fake server too — so instead prove no network call happened by pointing at
# a port nothing listens on and confirming the result is still served from the cache.
app.config.update( app.config.update(
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/" MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
) )
@@ -187,7 +195,7 @@ def test_found_row_is_never_rechecked(app, art_config):
assert result.image_url == "https://example.com/old.jpg" assert result.image_url == "https://example.com/old.jpg"
# --- fetch_image() --------------------------------------------------------------------------- # --- fetch_image() -------------------------------------------------------------------------
def test_fetch_image_streams_the_bytes(art_config): def test_fetch_image_streams_the_bytes(art_config):
@@ -202,14 +210,146 @@ def test_fetch_image_raises_on_failure(art_config):
art.fetch_image("http://127.0.0.1:1/nope.jpg") art.fetch_image("http://127.0.0.1:1/nope.jpg")
# --- GET /api/v1/art/album --------------------------------------------------------------------- # --- get_cached() / want() / requeue() / read_file() ----------------------------------------
def test_get_cached_returns_none_for_unseen_album(art_config):
assert art.get_cached("Nobody", "Nothing") is None
def test_get_cached_is_case_insensitive(art_config):
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
assert art.get_cached("radiohead", "in rainbows").image_url == "https://example.com/a.jpg"
def test_want_creates_a_pending_row(art_config):
art.want("New Artist", "New Album")
assert row("New Artist", "New Album").status == "pending"
def test_want_is_a_noop_if_a_row_already_exists(art_config):
insert("Radiohead", "In Rainbows", "found", image_url="https://example.com/a.jpg")
art.want("Radiohead", "In Rainbows")
assert row("Radiohead", "In Rainbows").status == "found" # untouched, not reset to pending
def test_read_file_returns_none_when_not_downloaded(art_config):
assert art.read_file(999_999) is None
def test_read_file_returns_the_bytes(app, art_config):
path = pathlib.Path(app.config["ART_STORAGE_DIR"]) / "123.jpg"
path.write_bytes(b"hello")
assert art.read_file(123) == b"hello"
def test_requeue_marks_a_row_pending(art_config):
insert("Someone", "Old Album", "found", image_url="https://example.com/a.jpg")
art.requeue(row("Someone", "Old Album"))
assert row("Someone", "Old Album").status == "pending"
# --- resolve_one_pending() (the worker task) ------------------------------------------------
def test_resolve_one_pending_resolves_and_downloads(art_config):
art.want("Radiohead", "In Rainbows")
assert art.resolve_one_pending() is True
cached = row("Radiohead", "In Rainbows")
assert cached.status == "found"
assert art.read_file(cached.id) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
def test_resolve_one_pending_handles_not_found(art_config):
art.want("Nobody", "Nothing")
assert art.resolve_one_pending() is True
assert row("Nobody", "Nothing").status == "not_found"
def test_resolve_one_pending_handles_upstream_error(art_config):
art.want("Someone", "Boom Album")
assert art.resolve_one_pending() is True
cached = row("Someone", "Boom Album")
assert cached.status == "error"
assert cached.error_code
def test_resolve_one_pending_download_failure_is_cached_as_error(art_config):
art.want("Someone", "Download Fail Album")
assert art.resolve_one_pending() is True
cached = row("Someone", "Download Fail Album")
assert cached.status == "error" # not left "found" with no file on disk
assert art.read_file(cached.id) is None
def test_resolve_one_pending_returns_false_when_nothing_to_do(art_config):
assert art.resolve_one_pending() is False
def test_resolve_one_pending_picks_up_stale_not_found(art_config):
insert("Radiohead", "In Rainbows", "not_found", days_ago=31)
assert art.resolve_one_pending() is True
assert row("Radiohead", "In Rainbows").status == "found"
def test_resolve_one_pending_picks_up_stale_error(art_config):
db.session.add(
AlbumArt(
artist="Radiohead",
album="In Rainbows",
status="error",
error_code="TimeoutError",
checked_at=datetime.now(UTC) - timedelta(hours=2),
)
)
db.session.commit()
assert art.resolve_one_pending() is True
assert row("Radiohead", "In Rainbows").status == "found"
def test_resolve_one_pending_ignores_fresh_not_found(art_config):
insert("Radiohead", "In Rainbows", "not_found", days_ago=1)
assert art.resolve_one_pending() is False
# --- GET /api/v1/art/album -------------------------------------------------------------------
def test_album_art_requires_auth(client): def test_album_art_requires_auth(client):
assert client.get("/api/v1/art/album?artist=A&album=B").status_code == 401 assert client.get("/api/v1/art/album?artist=A&album=B").status_code == 401
def test_album_art_returns_the_image(client, auth, art_config): def test_album_art_requires_artist_and_album(client, auth):
assert client.get("/api/v1/art/album?artist=A", headers=auth).status_code == 422
assert client.get("/api/v1/art/album?album=B", headers=auth).status_code == 422
def test_album_art_404s_and_queues_an_unseen_album(client, auth, art_config):
response = client.get("/api/v1/art/album?artist=New+Artist&album=New+Album", headers=auth)
assert response.status_code == 404
assert response.get_json()["error"]["code"] == "no_album_art"
assert row("New Artist", "New Album").status == "pending"
def test_album_art_never_calls_the_network(client, auth, app, art_config):
# Point at a port nothing listens on: the endpoint must still respond (fast, 404)
# without ever trying to reach it — proof it's a cache-only read.
app.config.update(
MUSICBRAINZ_API_URL="http://127.0.0.1:1/", COVERART_API_URL="http://127.0.0.1:1/"
)
response = client.get("/api/v1/art/album?artist=Another&album=Album", headers=auth)
assert response.status_code == 404
def test_album_art_404s_while_pending(client, auth, art_config):
art.want("Radiohead", "In Rainbows")
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
assert response.status_code == 404
def test_album_art_returns_the_image_once_resolved(client, auth, art_config):
art.want("Radiohead", "In Rainbows")
art.resolve_one_pending()
response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth) response = client.get("/api/v1/art/album?artist=Radiohead&album=In+Rainbows", headers=auth)
assert response.status_code == 200 assert response.status_code == 200
assert response.data == b"\xff\xd8\xff\xe0fake-jpeg-bytes" assert response.data == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
@@ -217,18 +357,15 @@ def test_album_art_returns_the_image(client, auth, art_config):
assert response.headers["Cache-Control"] == "private, max-age=604800" assert response.headers["Cache-Control"] == "private, max-age=604800"
def test_album_art_404s_when_not_found(client, auth, art_config): def test_album_art_404s_when_resolved_not_found(client, auth, art_config):
art.want("Nobody", "Nothing")
art.resolve_one_pending()
response = client.get("/api/v1/art/album?artist=Nobody&album=Nothing", headers=auth) response = client.get("/api/v1/art/album?artist=Nobody&album=Nothing", headers=auth)
assert response.status_code == 404 assert response.status_code == 404
assert response.get_json()["error"]["code"] == "no_album_art"
def test_album_art_502s_on_upstream_error(client, auth, art_config): def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_config):
response = client.get("/api/v1/art/album?artist=Someone&album=Boom+Album", headers=auth) insert("Legacy", "Album", "found", image_url="https://example.com/old.jpg")
assert response.status_code == 502 response = client.get("/api/v1/art/album?artist=Legacy&album=Album", headers=auth)
assert response.get_json()["error"]["code"] == "art_upstream_unavailable" assert response.status_code == 404
assert row("Legacy", "Album").status == "pending" # requeued for the worker to redo
def test_album_art_requires_artist_and_album(client, auth):
assert client.get("/api/v1/art/album?artist=A", headers=auth).status_code == 422
assert client.get("/api/v1/art/album?album=B", headers=auth).status_code == 422