3 Commits
Author SHA1 Message Date
mattandClaude Sonnet 5.5 48fba1e0e2 Add album art observability metrics, dashboard and alerts
CI / lint (push) Successful in 18s
CI / validate-monitoring (push) Successful in 13s
CI / federation-interop (push) Successful in 1m36s
CI / test (push) Successful in 3m37s
CI / python-package (push) Successful in 13s
CI / trigger-deploy (push) Successful in 3s
CI / notify (push) Successful in 5s
CI / assets (push) Successful in 8s
CI / images (push) Successful in 1m37s
Endpoint result counters, worker resolution/latency/image-size metrics,
per-upstream latency and error counters, cache-status and oldest-pending
gauges, an Album Art Grafana dashboard, and backlog/upstream-error alerts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv
2026-10-06 21:56:18 +01:00
mattandClaude Sonnet 5 6cd17d7586 Merge fix/album-art-performance into main
CI / python-package (push) Successful in 13s
CI / lint (push) Successful in 13s
CI / test (push) Successful in 4m27s
CI / validate-monitoring (push) Successful in 8s
CI / federation-interop (push) Successful in 1m9s
CI / assets (push) Successful in 7s
CI / notify (push) Successful in 6s
CI / images (push) Successful in 29s
CI / trigger-deploy (push) Successful in 3s
Stops album art lookups from blocking page loads: the art endpoint is
now cache-only (never calls MusicBrainz/Cover Art Archive in the
request path), a background worker task resolves and downloads art
asynchronously, and resolved images are cached on a disk volume
instead of re-fetched on every view.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011Hn2QwS1HRT8tFAzo8ew63
2026-10-06 21:29:23 +01:00
mattandClaude Sonnet 5 83b27d7ba1 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
2026-10-06 21:27:50 +01:00
17 changed files with 1268 additions and 69 deletions

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).
# MusicBrainz asks for a contact URL/email in requests; falls back to UI_BASE_URL if unset.
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)
API_PORT=5050
+1
View File
@@ -15,6 +15,7 @@ htmlcov/
# Runtime
prometheus_multiproc/
var/album-art/
# IDEs
.idea/
+755
View File
@@ -0,0 +1,755 @@
{
"uid": "scrobbler-album-art",
"title": "Scrobbler: Album Art",
"description": "Album art endpoint, background resolver and MusicBrainz / Cover Art Archive upstreams",
"tags": [
"scrobbler"
],
"timezone": "browser",
"editable": true,
"graphTooltip": 1,
"refresh": "30s",
"time": {
"from": "now-6h",
"to": "now"
},
"schemaVersion": 41,
"version": 1,
"templating": {
"list": []
},
"annotations": {
"list": []
},
"links": [
{
"type": "dashboards",
"tags": [
"scrobbler"
],
"asDropdown": true,
"title": "Scrobbler",
"includeVars": false
}
],
"panels": [
{
"type": "row",
"title": "Cache",
"id": 1,
"collapsed": false,
"gridPos": {
"x": 0,
"y": 0,
"w": 24,
"h": 1
},
"panels": []
},
{
"type": "stat",
"title": "Cached: found",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_art_cache{status=\"found\"})",
"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": 2,
"gridPos": {
"x": 0,
"y": 1,
"w": 6,
"h": 5
}
},
{
"type": "stat",
"title": "Cached: not found",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_art_cache{status=\"not_found\"})",
"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": 3,
"gridPos": {
"x": 6,
"y": 1,
"w": 6,
"h": 5
}
},
{
"type": "stat",
"title": "Cached: error",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_art_cache{status=\"error\"})",
"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": 4,
"gridPos": {
"x": 12,
"y": 1,
"w": 6,
"h": 5
}
},
{
"type": "stat",
"title": "Oldest pending request",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(scrobbler_art_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": 5,
"gridPos": {
"x": 18,
"y": 1,
"w": 6,
"h": 5
}
},
{
"type": "row",
"title": "Endpoint",
"id": 6,
"collapsed": false,
"gridPos": {
"x": 0,
"y": 6,
"w": 24,
"h": 1
},
"panels": []
},
{
"type": "timeseries",
"title": "Responses / min by result",
"description": "queued = first sighting of an album; pending = still being resolved; unavailable = settled with no art.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (result) (rate(scrobbler_art_requests_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": 7,
"gridPos": {
"x": 0,
"y": 7,
"w": 12,
"h": 8
}
},
{
"type": "timeseries",
"title": "Endpoint latency (p95)",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"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",
"refId": "A"
}
],
"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": 8,
"gridPos": {
"x": 12,
"y": 7,
"w": 12,
"h": 8
}
},
{
"type": "row",
"title": "Worker",
"id": 9,
"collapsed": false,
"gridPos": {
"x": 0,
"y": 15,
"w": 24,
"h": 1
},
"panels": []
},
{
"type": "timeseries",
"title": "Resolutions / min by result",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (source, result) (rate(scrobbler_art_resolutions_total[$__rate_interval])) * 60",
"legendFormat": "{{source}} {{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": 10,
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
}
},
{
"type": "timeseries",
"title": "Time to resolve one album (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_worker_resolve_seconds_bucket[$__rate_interval])))",
"legendFormat": "p50",
"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": "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": 11,
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
}
},
{
"type": "timeseries",
"title": "Cache rows by status",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max by (status) (scrobbler_art_cache)",
"legendFormat": "{{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": 12,
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
}
},
{
"type": "timeseries",
"title": "Downloaded image 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_image_bytes_bucket[$__rate_interval])))",
"legendFormat": "p50",
"refId": "A"
},
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_art_image_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": 13,
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
}
},
{
"type": "row",
"title": "Upstreams",
"id": 14,
"collapsed": false,
"gridPos": {
"x": 0,
"y": 32,
"w": 24,
"h": 1
},
"panels": []
},
{
"type": "timeseries",
"title": "Upstream latency (p95)",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le, service) (rate(scrobbler_art_upstream_seconds_bucket[$__rate_interval])))",
"legendFormat": "{{service}}",
"refId": "A"
}
],
"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": 15,
"gridPos": {
"x": 0,
"y": 33,
"w": 12,
"h": 8
}
},
{
"type": "timeseries",
"title": "Upstream errors / min",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service, error) (rate(scrobbler_art_upstream_errors_total[$__rate_interval])) * 60",
"legendFormat": "{{service}} {{error}}",
"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": 16,
"gridPos": {
"x": 12,
"y": 33,
"w": 12,
"h": 8
}
}
]
}
+18
View File
@@ -107,6 +107,24 @@ groups:
summary: More than 20% of incoming fediverse signatures are failing
description: Check the Federation dashboard for the reason (e.g. a clock problem shows as 'expired').
- alert: AlbumArtBacklog
expr: max(scrobbler_art_oldest_pending_seconds) > 900
for: 10m
labels: {severity: warning}
annotations:
summary: Album art requests have been waiting over 15 minutes
description: The worker is probably stopped, or MusicBrainz / Cover Art Archive is failing.
- alert: AlbumArtUpstreamErrors
expr: |
sum by (service) (rate(scrobbler_art_upstream_errors_total[15m]))
/ sum by (service) (rate(scrobbler_art_upstream_seconds_count[15m])) > 0.5
for: 15m
labels: {severity: warning}
annotations:
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: PostgresDown
expr: pg_up == 0
for: 2m
+8
View File
@@ -35,6 +35,7 @@ services:
FORWARDED_ALLOW_IPS: "*"
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_DOMAIN: ${FEDERATION_DOMAIN:-}
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
@@ -43,6 +44,8 @@ services:
- "${API_PORT:-5050}:8000"
expose:
- "9100" # metrics: internal network only
volumes:
- album-art-data:/data/album-art
depends_on:
db:
condition: service_healthy
@@ -58,6 +61,8 @@ services:
DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler
SECRET_KEY: ${SECRET_KEY:-change-me}
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_DOMAIN: ${FEDERATION_DOMAIN:-}
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
@@ -65,6 +70,8 @@ services:
RUN_MIGRATIONS: "0" # the api service applies them
expose:
- "9101" # metrics: internal network only
volumes:
- album-art-data:/data/album-art
healthcheck:
disable: true
depends_on:
@@ -124,5 +131,6 @@ services:
volumes:
db-data:
album-art-data:
prometheus-data:
grafana-data:
+2
View File
@@ -13,6 +13,8 @@ RUN uv sync --locked --no-dev --no-editable
FROM python:3.13-slim
LABEL org.opencontainers.image.licenses="BSD-3-Clause"
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
COPY --from=build /app/.venv /app/.venv
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.
- **`ui`**: nginx serving the static frontend (`frontend/`, no build step).
- **`worker`**: `flask worker` — history imports and background tasks for optional
modules (federation's deliveries, scheduled posts, and so on).
- **`worker`**: `flask worker` — history imports, resolving and downloading album art
(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.
- 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 |
| `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)) |
| `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 |
| `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 |
@@ -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
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
```sh
+3 -13
View File
@@ -1531,18 +1531,8 @@
"422": {
"$ref": "#/components/responses/UNPROCESSABLE_CONTENT"
},
"502": {
"description": "MusicBrainz or Cover Art Archive is unreachable",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "No cover art found for this album",
"description": "No cover art available yet",
"content": {
"application/json": {
"schema": {
@@ -1569,7 +1559,7 @@
}
},
"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": [
"Art"
],
@@ -3453,7 +3443,7 @@
},
{
"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",
+2
View File
@@ -42,11 +42,13 @@ def create_app(config_object=None):
)
from scrobbler.cli import imports_cli, worker_command
from scrobbler.services import art as art_service
from scrobbler.services import imports as import_service
app.cli.add_command(worker_command)
app.cli.add_command(imports_cli)
import_service.register_worker_tasks(app)
art_service.register_worker_tasks(app)
from scrobbler.metrics import db as db_metrics
+24 -20
View File
@@ -1,12 +1,15 @@
from flask import Response
from flask_smorest import Blueprint, abort
from scrobbler import metrics
from scrobbler.api.decorators import authenticated
from scrobbler.schemas import AlbumArtArgsSchema, ErrorSchema
from scrobbler.services import art
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 +17,30 @@ blp = Blueprint(
@authenticated(blp)
@blp.arguments(AlbumArtArgsSchema, location="query")
@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(
502, schema=ErrorSchema, description="MusicBrainz or Cover Art Archive is unreachable"
)
@blp.alt_response(404, schema=ErrorSchema, description="No cover art available yet")
def album_art(args):
"""An album's cover art
Resolved via MusicBrainz + Cover Art Archive and cached; bytes are proxied on every
call, so cache this response client-side.
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.
"""
result = art.lookup(args["artist"], args["album"])
if result.status == "not_found":
row = art.get_cached(args["artist"], args["album"])
if row is None:
art.want(args["artist"], args["album"])
metrics.art_requests_total.labels("queued").inc()
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
result = "file_missing"
else:
result = "pending" if row.status == "pending" else "unavailable"
metrics.art_requests_total.labels(result).inc()
abort(404, code="no_album_art", message="No cover art found for this album")
if result.status == "error":
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)
metrics.art_requests_total.labels("served").inc()
response = Response(image, mimetype="image/jpeg")
response.headers["Cache-Control"] = "private, max-age=604800" # 7 days; art rarely changes
return response
+3
View File
@@ -64,6 +64,9 @@ class Config:
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_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)))
MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests
+36
View File
@@ -122,6 +122,40 @@ worker_tasks_total = Counter(
["task", "outcome"],
)
# Album art (endpoint + background resolver)
art_requests_total = Counter(
"scrobbler_art_requests_total",
"Album art endpoint responses: served, queued (first sighting), pending (still "
"resolving), unavailable (no art found), file_missing (re-queued)",
["result"],
)
art_resolutions_total = Counter(
"scrobbler_art_resolutions_total",
"Album art resolutions by outcome (found, not_found, error) and caller (worker, inline)",
["source", "result"],
)
art_upstream_seconds = Histogram(
"scrobbler_art_upstream_seconds",
"Latency of one album art upstream call, by service (musicbrainz, coverart, download)",
["service", "outcome"],
buckets=(0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 40),
)
art_upstream_errors_total = Counter(
"scrobbler_art_upstream_errors_total",
"Failed album art upstream calls, by service and exception class",
["service", "error"],
)
art_worker_resolve_seconds = Histogram(
"scrobbler_art_worker_resolve_seconds",
"Time for the worker to resolve and download one album's art",
buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80),
)
art_image_bytes = Histogram(
"scrobbler_art_image_bytes",
"Size of downloaded album art images",
buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000),
)
# Database
db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds",
@@ -150,4 +184,6 @@ COLLECTED = {
"active_users": "scrobbler_active_users",
"now_playing_active": "scrobbler_now_playing_active",
"import_jobs": "scrobbler_import_jobs",
"art_cache": "scrobbler_art_cache",
"art_oldest_pending": "scrobbler_art_oldest_pending_seconds",
}
+23
View File
@@ -12,6 +12,7 @@ from sqlalchemy.pool import NullPool
from scrobbler.metrics import COLLECTED
ART_STATUSES = ("pending", "found", "not_found", "error")
ACTIVE_WINDOWS = {"1h": "1 hour", "24h": "24 hours", "7d": "7 days"}
@@ -46,11 +47,22 @@ class DatabaseStatsCollector(Collector):
)
).all()
)
art_cache = dict(
conn.execute(text("SELECT status, count(*) FROM album_art GROUP BY status")).all()
)
oldest_pending = conn.execute(
text(
"SELECT coalesce(extract(epoch FROM now() - min(checked_at)), 0) "
"FROM album_art WHERE status = 'pending'"
)
).scalar_one()
return {
"users": users,
"active": active,
"now_playing": now_playing,
"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),
}
def values(self) -> dict | None:
@@ -85,3 +97,14 @@ class DatabaseStatsCollector(Collector):
for status, count in values["import_jobs"].items():
jobs.add_metric([status], count)
yield jobs
art = GaugeMetricFamily(
COLLECTED["art_cache"], "Album art cache rows by status", labels=["status"]
)
for status, count in values["art_cache"].items():
art.add_metric([status], count)
yield art
yield GaugeMetricFamily(
COLLECTED["art_oldest_pending"],
"Age of the longest-waiting album art request (0 if none pending)",
value=values["art_oldest_pending"],
)
+166 -15
View File
@@ -3,8 +3,17 @@
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.
`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
change `fetch_image()`, not the caching/lookup logic.
from there.
`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
@@ -14,18 +23,37 @@ import time
import urllib.error
import urllib.parse
import urllib.request
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from pathlib import Path
from flask import current_app
from sqlalchemy import func, select
from sqlalchemy import func, or_, select
from sqlalchemy.dialects.postgresql import insert
from scrobbler import metrics
from scrobbler.extensions import db
from scrobbler.models import AlbumArt
log = logging.getLogger(__name__)
@contextmanager
def _upstream_call(service: str):
"""Times one upstream call and counts its failures (the error is re-raised)."""
start = time.perf_counter()
outcome = "ok"
try:
yield
except Exception as err:
outcome = "error"
metrics.art_upstream_errors_total.labels(service, type(err).__name__).inc()
raise
finally:
metrics.art_upstream_seconds.labels(service, outcome).observe(time.perf_counter() - start)
# Lucene special characters MusicBrainz's search syntax requires escaping.
_LUCENE_SPECIAL = re.compile(r'([+\-&|!(){}\[\]^"~*?:\\/])')
@@ -90,7 +118,10 @@ def _find_release_group(artist: str, album: str) -> str | None:
for attempt in range(retries + 1):
request = _throttled_request(f"{api_url}release-group/?{params}")
try:
with urllib.request.urlopen(request, timeout=10) as response:
with (
_upstream_call("musicbrainz"),
urllib.request.urlopen(request, timeout=10) as response,
):
body = json.load(response)
except urllib.error.HTTPError as err:
if attempt == retries or err.code < 500:
@@ -118,7 +149,7 @@ def _cover_art_url(release_group_mbid: str) -> str | None:
for attempt in range(retries + 1):
request = urllib.request.Request(url, method="HEAD")
try:
with urllib.request.urlopen(request, timeout=15):
with _upstream_call("coverart"), urllib.request.urlopen(request, timeout=15):
return url
except urllib.error.HTTPError as err:
if err.code == 404:
@@ -132,29 +163,37 @@ def _cover_art_url(release_group_mbid: str) -> str | None:
raise TimeoutError("Cover Art Archive request exhausted its retries")
def lookup(artist: str, album: str) -> ArtResult:
"""Cached (artist, album) art resolution. Never raises."""
existing = db.session.scalar(
def get_cached(artist: str, album: str) -> AlbumArt | None:
"""Plain cache read by (artist, album). No network, no write."""
return db.session.scalar(
select(AlbumArt).where(
func.lower(AlbumArt.artist) == artist.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
try:
release_group_mbid = _find_release_group(artist, album)
image_url = _cover_art_url(release_group_mbid) if release_group_mbid else None
status = "found" if image_url else "not_found"
result = ArtResult(status, image_url)
error_code = None
return ArtResult(status, image_url), release_group_mbid, None
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)
result = ArtResult("error")
error_code = type(err).__name__
return ArtResult("error"), release_group_mbid, type(err).__name__
def _store(
artist: str,
album: str,
result: ArtResult,
release_group_mbid: str | None,
error_code: str | None,
) -> None:
values = {
"artist": artist,
"album": album,
@@ -170,13 +209,125 @@ def lookup(artist: str, album: str) -> ArtResult:
)
db.session.execute(stmt)
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)
metrics.art_resolutions_total.labels("inline", result.status).inc()
_store(artist, album, result, release_group_mbid, error_code)
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:
"""Streams the bytes from image_url. Raises ArtFetchFailed on any problem."""
try:
with urllib.request.urlopen(image_url, timeout=10) as response:
with _upstream_call("download"), urllib.request.urlopen(image_url, timeout=10) as response:
return ImageBytes(response.read(), response.headers.get("Content-Type", "image/jpeg"))
except (urllib.error.URLError, TimeoutError) as 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
start = time.perf_counter()
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)
metrics.art_image_bytes.observe(len(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"
metrics.art_resolutions_total.labels("worker", result.status).inc()
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()
metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start)
return True
def register_worker_tasks(app) -> None:
from scrobbler import worker
worker.register_task(app, "art", resolve_one_pending)
+208 -18
View File
@@ -1,4 +1,5 @@
import json
import pathlib
import threading
import urllib.parse
from datetime import UTC, datetime, timedelta
@@ -14,7 +15,8 @@ from scrobbler.services import art
_RELEASE_GROUPS = {
"In Rainbows": "rg-found", # has art
"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")])
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")])
return [b"not found"]
@@ -58,12 +67,13 @@ def fake_art_api():
@pytest.fixture
def art_config(app, fake_art_api):
def art_config(app, fake_art_api, tmp_path):
keys = (
"MUSICBRAINZ_API_URL",
"COVERART_API_URL",
"MUSICBRAINZ_REQUEST_INTERVAL",
"MUSICBRAINZ_RETRIES",
"ART_STORAGE_DIR",
)
saved = {k: app.config[k] for k in keys}
app.config.update(
@@ -71,6 +81,7 @@ def art_config(app, fake_art_api):
COVERART_API_URL=fake_art_api,
MUSICBRAINZ_REQUEST_INTERVAL=0,
MUSICBRAINZ_RETRIES=0,
ART_STORAGE_DIR=str(tmp_path),
)
yield
app.config.update(saved)
@@ -98,7 +109,7 @@ def insert(artist, album, status, days_ago=0.0, image_url=None):
db.session.commit()
# --- lookup() ------------------------------------------------------------------------------
# --- lookup() (still live-resolving: used by ActivityPub posting, out of scope here) -----------
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):
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(
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"
# --- fetch_image() ---------------------------------------------------------------------------
# --- fetch_image() -------------------------------------------------------------------------
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")
# --- 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):
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)
assert response.status_code == 200
assert response.data == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
@@ -217,18 +357,68 @@ def test_album_art_returns_the_image(client, auth, art_config):
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)
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):
response = client.get("/api/v1/art/album?artist=Someone&album=Boom+Album", headers=auth)
assert response.status_code == 502
assert response.get_json()["error"]["code"] == "art_upstream_unavailable"
def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_config):
insert("Legacy", "Album", "found", image_url="https://example.com/old.jpg")
response = client.get("/api/v1/art/album?artist=Legacy&album=Album", headers=auth)
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
# --- metrics ------------------------------------------------------------------------------
def test_worker_counts_resolutions_and_times_upstreams(art_config, metric_delta):
found = metric_delta("scrobbler_art_resolutions_total", source="worker", result="found")
resolve = metric_delta("scrobbler_art_worker_resolve_seconds_count")
image = metric_delta("scrobbler_art_image_bytes_count")
musicbrainz = metric_delta(
"scrobbler_art_upstream_seconds_count", service="musicbrainz", outcome="ok"
)
download = metric_delta(
"scrobbler_art_upstream_seconds_count", service="download", outcome="ok"
)
art.want("Radiohead", "In Rainbows")
art.resolve_one_pending()
assert (found.delta, resolve.delta, image.delta) == (1, 1, 1)
assert musicbrainz.delta == 1
assert download.delta == 1
def test_worker_counts_download_failure_as_one_error(art_config, metric_delta):
errors = metric_delta("scrobbler_art_resolutions_total", source="worker", result="error")
found = metric_delta("scrobbler_art_resolutions_total", source="worker", result="found")
failed = metric_delta(
"scrobbler_art_upstream_errors_total", service="download", error="HTTPError"
)
art.want("Someone", "Download Fail Album")
art.resolve_one_pending()
assert (errors.delta, found.delta) == (1, 0)
assert failed.delta == 1
def test_endpoint_counts_queued_pending_and_unavailable(client, auth, art_config, metric_delta):
queued = metric_delta("scrobbler_art_requests_total", result="queued")
pending = metric_delta("scrobbler_art_requests_total", result="pending")
unavailable = metric_delta("scrobbler_art_requests_total", result="unavailable")
url = "/api/v1/art/album?artist=Nobody&album=Nothing"
client.get(url, headers=auth)
client.get(url, headers=auth)
art.resolve_one_pending()
client.get(url, headers=auth)
assert (queued.delta, pending.delta, unavailable.delta) == (1, 1, 1)
def test_endpoint_counts_served(client, auth, art_config, metric_delta):
served = metric_delta("scrobbler_art_requests_total", result="served")
url = "/api/v1/art/album?artist=Radiohead&album=In+Rainbows"
client.get(url, headers=auth)
art.resolve_one_pending()
assert client.get(url, headers=auth).status_code == 200
assert served.delta == 1
+1
View File
@@ -50,6 +50,7 @@ def test_the_expected_dashboards_exist():
"usage",
"database",
"federation",
"album-art",
}
+3
View File
@@ -87,6 +87,9 @@ def test_database_stats_collector(app, user, make_user):
active = {s.labels["window"]: s.value for s in families["scrobbler_active_users"].samples}
assert active == {"1h": 1, "24h": 1, "7d": 1}
assert families["scrobbler_now_playing_active"].samples[0].value == 1
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
def test_database_stats_collector_caches(app, user):