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 / assets (push) Successful in 8s
CI / python-package (push) Successful in 13s
CI / images (push) Successful in 1m37s
CI / trigger-deploy (push) Successful in 3s
CI / notify (push) Successful in 5s
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 / assets (push) Successful in 8s
CI / python-package (push) Successful in 13s
CI / images (push) Successful in 1m37s
CI / trigger-deploy (push) Successful in 3s
CI / notify (push) Successful in 5s
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
This commit is contained in:
1 parent
6cd17d7586
commit
48fba1e0e2
9 files changed
+925
-3
No files matched your search
@@ -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
|
||||
@@ -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",
|
||||
}
|
||||
@@ -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"],
|
||||
)
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user