App factory, data model, initial migration and HTTP metrics
CI / lint (push) Successful in 9s
CI / test (push) Failing after 22s
CI / notify (push) Successful in 5s

- Flask app factory with env-driven config (.env loaded at import)
- SQLAlchemy models: users, API apps, UI tokens, Last.fm auth tokens,
  sessions, scrobbles (deduplicated) and now-playing
- Initial Alembic migration; CI checks migrations match the models
- Prometheus metric definitions, per-endpoint RED hooks with bounded
  labels, and a standalone metrics server
- docker compose Postgres with a test database; CI test job runs
  against a Postgres service container

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 13:55:04 +01:00
1 parent 606348800b
commit 98c8f2e824
21 files changed
+1777 -6

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
"""All Prometheus metrics for the service, defined in one place.
Labels are deliberately low-cardinality: Flask endpoint names (never raw paths),
Last.fm method names from the handler registry, and small fixed enums. Never add
user, api_key or track labels.
"""
import platform
from prometheus_client import Counter, Gauge, Histogram
from scrobbler import __version__
LATENCY_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
# HTTP (RED)
http_requests_total = Counter(
"scrobbler_http_requests_total",
"HTTP requests handled",
["endpoint", "http_method", "status"],
)
http_request_duration_seconds = Histogram(
"scrobbler_http_request_duration_seconds",
"HTTP request latency",
["endpoint", "http_method"],
buckets=LATENCY_BUCKETS,
)
http_requests_in_progress = Gauge(
"scrobbler_http_requests_in_progress",
"HTTP requests currently being handled",
["endpoint"],
multiprocess_mode="livesum",
)
# Last.fm API
lastfm_requests_total = Counter(
"scrobbler_lastfm_requests_total",
"Last.fm API calls",
["lastfm_method", "format", "outcome"],
)
lastfm_request_duration_seconds = Histogram(
"scrobbler_lastfm_request_duration_seconds",
"Last.fm API call latency",
["lastfm_method"],
buckets=LATENCY_BUCKETS,
)
lastfm_errors_total = Counter(
"scrobbler_lastfm_errors_total",
"Last.fm API errors by error code",
["lastfm_method", "code"],
)
# Scrobbling
scrobbles_total = Counter(
"scrobbler_scrobbles_total",
"Scrobbles submitted, by result",
["result"],
)
scrobbles_ignored_total = Counter(
"scrobbler_scrobbles_ignored_total",
"Scrobbles ignored, by Last.fm ignored-message code",
["reason"],
)
scrobble_batch_size = Histogram(
"scrobbler_scrobble_batch_size",
"Tracks per track.scrobble call",
buckets=(1, 2, 5, 10, 25, 50),
)
scrobble_lag_seconds = Histogram(
"scrobbler_scrobble_lag_seconds",
"Delay between a track being played and its scrobble arriving",
buckets=(10, 60, 300, 900, 3600, 6 * 3600, 86400, 7 * 86400, 14 * 86400),
)
now_playing_updates_total = Counter(
"scrobbler_now_playing_updates_total",
"track.updateNowPlaying calls that were stored",
)
# Auth
auth_sessions_created_total = Counter(
"scrobbler_auth_sessions_created_total",
"Last.fm session keys issued",
["flow"],
)
auth_failures_total = Counter(
"scrobbler_auth_failures_total",
"Authentication failures",
["reason"],
)
ui_logins_total = Counter(
"scrobbler_ui_logins_total",
"Web UI login attempts",
["result"],
)
registrations_total = Counter(
"scrobbler_registrations_total",
"User registrations",
)
# Database
db_query_duration_seconds = Histogram(
"scrobbler_db_query_duration_seconds",
"Database statement latency",
["operation"],
buckets=(0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5),
)
db_pool_connections = Gauge(
"scrobbler_db_pool_connections",
"Database connection pool state",
["state"],
multiprocess_mode="livesum",
)
build_info = Gauge(
"scrobbler_build_info",
"Build information",
["version", "python_version"],
multiprocess_mode="max",
)
build_info.labels(version=__version__, python_version=platform.python_version()).set(1)
+36
View File
@@ -0,0 +1,36 @@
import time
from flask import Flask, g, request
from scrobbler import metrics
def _endpoint() -> str:
return request.url_rule.endpoint if request.url_rule else "unmatched"
def init_app(app: Flask) -> None:
@app.before_request
def _start_timer():
g._metrics_endpoint = _endpoint()
g._metrics_start = time.perf_counter()
metrics.http_requests_in_progress.labels(endpoint=g._metrics_endpoint).inc()
@app.after_request
def _record(response):
endpoint = g.get("_metrics_endpoint", _endpoint())
start = g.get("_metrics_start")
if start is not None:
metrics.http_request_duration_seconds.labels(
endpoint=endpoint, http_method=request.method
).observe(time.perf_counter() - start)
metrics.http_requests_total.labels(
endpoint=endpoint, http_method=request.method, status=str(response.status_code)
).inc()
return response
@app.teardown_request
def _finish(_exc):
endpoint = g.pop("_metrics_endpoint", None)
if endpoint is not None:
metrics.http_requests_in_progress.labels(endpoint=endpoint).dec()
+25
View File
@@ -0,0 +1,25 @@
import logging
import os
from prometheus_client import REGISTRY, CollectorRegistry, multiprocess, start_http_server
log = logging.getLogger(__name__)
def metrics_registry() -> CollectorRegistry:
"""Registry to expose: aggregated across workers when running under gunicorn."""
if os.environ.get("PROMETHEUS_MULTIPROC_DIR"):
registry = CollectorRegistry()
multiprocess.MultiProcessCollector(registry)
return registry
return REGISTRY
def start_metrics_server(port: int, registry: CollectorRegistry | None = None) -> bool:
try:
start_http_server(port, registry=registry or metrics_registry())
except OSError as exc: # e.g. the dev-server reloader's second process
log.warning("metrics server not started on port %s: %s", port, exc)
return False
log.info("metrics server listening on :%s/metrics", port)
return True