From 48fba1e0e20c0310cc74cf719db9d9c617c9ec4b Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 6 Oct 2026 21:56:18 +0100 Subject: [PATCH] Add album art observability metrics, dashboard and alerts 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 Claude-Session: https://claude.ai/code/session_01QHPkt2v797pphGCFKfTFmv --- deploy/grafana/dashboards/album-art.json | 755 +++++++++++++++++++++++ deploy/prometheus/alerts.yml | 18 + src/scrobbler/api/art.py | 7 + src/scrobbler/metrics/__init__.py | 36 ++ src/scrobbler/metrics/collectors.py | 23 + src/scrobbler/services/art.py | 32 +- tests/test_art.py | 53 ++ tests/test_dashboards.py | 1 + tests/test_metrics.py | 3 + 9 files changed, 925 insertions(+), 3 deletions(-) create mode 100644 deploy/grafana/dashboards/album-art.json diff --git a/deploy/grafana/dashboards/album-art.json b/deploy/grafana/dashboards/album-art.json new file mode 100644 index 0000000..496f2e1 --- /dev/null +++ b/deploy/grafana/dashboards/album-art.json @@ -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 + } + } + ] +} diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml index 1a14936..9bb7d7e 100644 --- a/deploy/prometheus/alerts.yml +++ b/deploy/prometheus/alerts.yml @@ -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 diff --git a/src/scrobbler/api/art.py b/src/scrobbler/api/art.py index 92db203..3131154 100644 --- a/src/scrobbler/api/art.py +++ b/src/scrobbler/api/art.py @@ -1,6 +1,7 @@ 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 @@ -28,12 +29,18 @@ def album_art(args): 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") + 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 diff --git a/src/scrobbler/metrics/__init__.py b/src/scrobbler/metrics/__init__.py index 61c8f1b..0c27fa1 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -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", } diff --git a/src/scrobbler/metrics/collectors.py b/src/scrobbler/metrics/collectors.py index 6c38d6f..40c4c74 100644 --- a/src/scrobbler/metrics/collectors.py +++ b/src/scrobbler/metrics/collectors.py @@ -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"], + ) diff --git a/src/scrobbler/services/art.py b/src/scrobbler/services/art.py index 64986e7..4588205 100644 --- a/src/scrobbler/services/art.py +++ b/src/scrobbler/services/art.py @@ -23,6 +23,7 @@ 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 @@ -31,11 +32,28 @@ from flask import current_app 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'([+\-&|!(){}\[\]^"~*?:\\/])') @@ -100,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: @@ -128,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: @@ -199,6 +220,7 @@ def lookup(artist: str, album: str) -> ArtResult: 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 @@ -238,7 +260,7 @@ def read_file(row_id: int) -> bytes | 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 @@ -281,6 +303,7 @@ def resolve_one_pending() -> bool: 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: @@ -288,16 +311,19 @@ def resolve_one_pending() -> bool: 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 diff --git a/tests/test_art.py b/tests/test_art.py index 9773036..058e0f8 100644 --- a/tests/test_art.py +++ b/tests/test_art.py @@ -369,3 +369,56 @@ def test_album_art_requeues_a_found_row_with_a_missing_file(client, auth, art_co 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 + + +# --- 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 diff --git a/tests/test_dashboards.py b/tests/test_dashboards.py index 339138a..4c39b72 100644 --- a/tests/test_dashboards.py +++ b/tests/test_dashboards.py @@ -50,6 +50,7 @@ def test_the_expected_dashboards_exist(): "usage", "database", "federation", + "album-art", } diff --git a/tests/test_metrics.py b/tests/test_metrics.py index 1a7da4b..e4f91f3 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -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):