Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aadb1c6def | ||
|
|
2c4c42a42b | ||
|
|
ad383b602e | ||
|
|
65cd610468 | ||
|
|
735556bf21 |
No files matched your search
@@ -10,6 +10,10 @@ CORS_ORIGINS=http://localhost:8080
|
||||
# Where Last.fm clients are redirected to approve desktop auth tokens.
|
||||
UI_BASE_URL=http://localhost:8080
|
||||
|
||||
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format ("text", or "json" for log aggregators).
|
||||
LOG_LEVEL=INFO
|
||||
LOG_FORMAT=text
|
||||
|
||||
# Prometheus metrics are served on a separate port.
|
||||
METRICS_PORT=9100
|
||||
|
||||
|
||||
@@ -87,11 +87,10 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Scrobbler <-> GoToSocial
|
||||
env:
|
||||
# Own compose project, network and image tags, so concurrent runs can't collide
|
||||
INTEROP_PROJECT: interop-${{ github.run_id }}
|
||||
run: |
|
||||
# A subnet of its own, so concurrent runs can't collide
|
||||
export INTEROP_SUBNET="172.30.$(( ${{ github.run_number }} % 200 + 20 )).0/24"
|
||||
scripts/interop/run.sh
|
||||
SCROBBLER_IMAGE_TAG: interop-${{ github.run_id }}
|
||||
run: scripts/interop/run.sh
|
||||
|
||||
# ---- Publishing (main and v* tags only) -------------------------------------
|
||||
|
||||
|
||||
@@ -18,11 +18,10 @@ x-federation: &federation
|
||||
FEDERATION_INSECURE_TESTING: "1"
|
||||
UI_BASE_URL: https://scrobble.test
|
||||
|
||||
# Docker picks the network's subnet, so concurrent runs can't collide on one. GoToSocial
|
||||
# is therefore told to trust any private range rather than one specific /24.
|
||||
networks:
|
||||
fedi:
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${INTEROP_SUBNET:-172.30.0.0/24}
|
||||
|
||||
services:
|
||||
db:
|
||||
@@ -63,9 +62,9 @@ services:
|
||||
GTS_PORT: "80"
|
||||
GTS_DB_TYPE: sqlite
|
||||
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
|
||||
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_SUBNET:-172.30.0.0/24} # let it reach Scrobbler on this network
|
||||
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16} # let it reach Scrobbler on this network
|
||||
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
|
||||
GTS_TRUSTED_PROXIES: ${INTEROP_SUBNET:-172.30.0.0/24}
|
||||
GTS_TRUSTED_PROXIES: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16}
|
||||
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
|
||||
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
|
||||
sysctls:
|
||||
|
||||
@@ -33,6 +33,8 @@ services:
|
||||
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
|
||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||
FORWARDED_ALLOW_IPS: "*"
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||
@@ -68,6 +70,8 @@ services:
|
||||
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
|
||||
RUN_MIGRATIONS: "0" # the api service applies them
|
||||
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||
expose:
|
||||
- "9101" # metrics: internal network only
|
||||
volumes:
|
||||
|
||||
@@ -54,6 +54,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
|
||||
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from |
|
||||
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under |
|
||||
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
|
||||
| `LOG_LEVEL` | api, worker | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. The worker logs each task pass that did work at `INFO` (with its duration); idle polls show at `DEBUG` |
|
||||
| `LOG_FORMAT` | api, worker | `text` | `json` writes one JSON object per line (with `task` and `duration_ms` fields for worker tasks), for log aggregators |
|
||||
| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network |
|
||||
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
||||
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
|
||||
|
||||
+12
-1
@@ -1778,7 +1778,7 @@
|
||||
}
|
||||
},
|
||||
"summary": "Correct a failed lookup",
|
||||
"description": "Queues a new lookup with different search text, or straight from a MusicBrainz\nrelease-group ID. The background worker resolves it; poll the failures list, or just\nfetch the art later. Replaces any earlier upload or correction of yours.",
|
||||
"description": "Queues a new lookup with different search text, or straight from a MusicBrainz\nrelease-group or release ID. The background worker resolves it; poll the failures list, or just\nfetch the art later. Replaces any earlier upload or correction of yours.",
|
||||
"tags": [
|
||||
"Art"
|
||||
],
|
||||
@@ -4534,6 +4534,12 @@
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"release_mbid": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -4567,6 +4573,11 @@
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"description": "A MusicBrainz release-group ID; skips the search"
|
||||
},
|
||||
"release_mbid": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"description": "A MusicBrainz release ID, as an alternative to a release-group ID; skips the search"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -119,10 +119,11 @@ function albumRow(item) {
|
||||
correction.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const body = { artist, album };
|
||||
const { search_artist, search_album, release_group_mbid } = correction.elements;
|
||||
const { search_artist, search_album, release_group_mbid, release_mbid } = correction.elements;
|
||||
if (search_artist.value.trim()) body.search_artist = search_artist.value.trim();
|
||||
if (search_album.value.trim()) body.search_album = search_album.value.trim();
|
||||
if (release_group_mbid.value.trim()) body.release_group_mbid = release_group_mbid.value.trim();
|
||||
if (release_mbid.value.trim()) body.release_mbid = release_mbid.value.trim();
|
||||
act(() => api("/art/album/correction", { method: "PUT", body }), `Queued a corrected lookup for ${album}.`);
|
||||
});
|
||||
|
||||
@@ -165,6 +166,13 @@ function correctionForm(item, query) {
|
||||
"If you know it, paste the ID from the album's MusicBrainz page. It skips the search.",
|
||||
{ placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" },
|
||||
),
|
||||
field(
|
||||
"release_mbid",
|
||||
"MusicBrainz release ID (optional)",
|
||||
own.release_mbid,
|
||||
"Or a specific release's ID, if that's the one you have. Use either this or the release-group ID.",
|
||||
{ placeholder: "00000000-0000-0000-0000-000000000000", pattern: "[0-9a-fA-F-]{36}" },
|
||||
),
|
||||
h("button", { type: "submit", class: "button" }, "Look it up"),
|
||||
);
|
||||
}
|
||||
@@ -11,11 +11,21 @@ wsgi_app = "scrobbler:create_app()"
|
||||
bind = os.environ.get("BIND", "0.0.0.0:8000")
|
||||
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
||||
accesslog = "-"
|
||||
loglevel = os.environ.get("LOG_LEVEL", "INFO").lower()
|
||||
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
|
||||
# gunicorn 26's control socket lives in $HOME, which the container user doesn't have.
|
||||
control_socket_disable = True
|
||||
|
||||
|
||||
def post_fork(server, worker):
|
||||
# Gunicorn's own messages go through the app's handler too, so the format is uniform.
|
||||
import logging
|
||||
|
||||
gunicorn_error = logging.getLogger("gunicorn.error")
|
||||
gunicorn_error.handlers.clear()
|
||||
gunicorn_error.propagate = True
|
||||
|
||||
|
||||
def on_starting(server):
|
||||
# Stale files from a previous run would double-count.
|
||||
shutil.rmtree(MULTIPROC_DIR, ignore_errors=True)
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
|
||||
set -euo pipefail
|
||||
root="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
# INTEROP_PROJECT and INTEROP_SUBNET let concurrent runs (e.g. in CI) stay apart.
|
||||
# INTEROP_PROJECT (with a distinct SCROBBLER_IMAGE_TAG) lets concurrent runs (e.g. in CI) stay apart.
|
||||
exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \
|
||||
-f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
|
||||
@@ -6,7 +6,14 @@ here="$(cd "$(dirname "$0")" && pwd)"
|
||||
compose="$here/compose.sh"
|
||||
keep=0; [ "${1:-}" = "--keep" ] && keep=1
|
||||
|
||||
cleanup() { [ "$keep" = 1 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; }
|
||||
cleanup() {
|
||||
[ "$keep" = 1 ] && return 0
|
||||
"$compose" down -v --remove-orphans --rmi local >/dev/null 2>&1
|
||||
# Per-run api/ui images (tagged with SCROBBLER_IMAGE_TAG) would otherwise pile up
|
||||
[ -n "${SCROBBLER_IMAGE_TAG:-}" ] && "$compose" config --images 2>/dev/null \
|
||||
| grep ":${SCROBBLER_IMAGE_TAG}$" | xargs -r docker rmi >/dev/null 2>&1
|
||||
return 0
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
"$compose" down -v --remove-orphans >/dev/null 2>&1
|
||||
|
||||
@@ -19,6 +19,10 @@ def create_app(config_object=None):
|
||||
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
|
||||
app.config.from_object(config_object or Config)
|
||||
|
||||
from scrobbler.logsetup import configure_logging
|
||||
|
||||
configure_logging(app.config["LOG_LEVEL"], app.config["LOG_FORMAT"])
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db, directory=_migrations_dir())
|
||||
http_metrics.init_app(app)
|
||||
|
||||
@@ -127,10 +127,11 @@ def correct_art(body):
|
||||
"""Correct a failed lookup
|
||||
|
||||
Queues a new lookup with different search text, or straight from a MusicBrainz
|
||||
release-group ID. The background worker resolves it; poll the failures list, or just
|
||||
release-group or release ID. The background worker resolves it; poll the failures list, or just
|
||||
fetch the art later. Replaces any earlier upload or correction of yours.
|
||||
"""
|
||||
mbid = body.get("release_group_mbid")
|
||||
release_mbid = body.get("release_mbid")
|
||||
art.request_correction(
|
||||
g.user.id,
|
||||
body["artist"],
|
||||
@@ -138,6 +139,7 @@ def correct_art(body):
|
||||
body.get("search_artist"),
|
||||
body.get("search_album"),
|
||||
str(mbid) if mbid else None,
|
||||
str(release_mbid) if release_mbid else None,
|
||||
)
|
||||
return art.get_override(g.user.id, body["artist"], body["album"])
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ from flask.cli import AppGroup, with_appcontext
|
||||
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
|
||||
from scrobbler import worker
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
if serve_metrics:
|
||||
from scrobbler.metrics.server import start_metrics_server
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@ class Config:
|
||||
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
|
||||
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
|
||||
LOG_FORMAT = os.environ.get("LOG_FORMAT", "text").lower() # "text" or "json"
|
||||
|
||||
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
|
||||
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
|
||||
# server is started by gunicorn.conf.py instead, so this stays off there.
|
||||
@@ -92,6 +95,8 @@ class TestConfig(Config):
|
||||
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
|
||||
)
|
||||
START_METRICS_SERVER = False
|
||||
LOG_LEVEL = "INFO"
|
||||
LOG_FORMAT = "text"
|
||||
# Tests never inherit optional features or URLs from a developer's .env or
|
||||
# environment; tests that need them turn them on, or override them, explicitly.
|
||||
LASTFM_API_KEY = ""
|
||||
|
||||
@@ -68,6 +68,13 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
|
||||
delivery.last_status, delivery.last_error = status, error[:1000]
|
||||
if _now() - delivery.created_at >= GIVE_UP_AFTER:
|
||||
delivery.status = "abandoned"
|
||||
log.warning(
|
||||
"delivery %s to %s abandoned after %s attempts: %s",
|
||||
delivery.id,
|
||||
delivery.inbox,
|
||||
delivery.attempts,
|
||||
error[:200],
|
||||
)
|
||||
return "abandoned"
|
||||
delay = (
|
||||
RETRY_DELAYS[delivery.attempts - 1]
|
||||
@@ -75,6 +82,14 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
|
||||
else LATER_DELAY
|
||||
)
|
||||
delivery.next_attempt_at = _now() + delay
|
||||
log.warning(
|
||||
"delivery %s to %s failed (attempt %s), retrying in %s: %s",
|
||||
delivery.id,
|
||||
delivery.inbox,
|
||||
delivery.attempts,
|
||||
delay,
|
||||
error[:200],
|
||||
)
|
||||
return "retry"
|
||||
|
||||
|
||||
@@ -135,7 +150,7 @@ def _deliver_in_context(app, delivery_id: int) -> str:
|
||||
try:
|
||||
return deliver(delivery_id)
|
||||
except Exception:
|
||||
log.exception("delivery %s failed unexpectedly", delivery_id)
|
||||
log.exception("delivery %s failed unexpectedly (will be retried)", delivery_id)
|
||||
db.session.rollback()
|
||||
return "retry" # the lease expires and it becomes due again
|
||||
finally:
|
||||
|
||||
@@ -224,7 +224,13 @@ def process(item: FederationInboxItem) -> None:
|
||||
db.session.rollback()
|
||||
transient = isinstance(err, FetchError) and err.reason == "network"
|
||||
if not transient:
|
||||
log.exception("inbox item %s failed", item.id)
|
||||
log.exception(
|
||||
"inbox item %s (%s) failed on attempt %s of %s",
|
||||
item.id,
|
||||
item.activity_type,
|
||||
item.attempts,
|
||||
MAX_ATTEMPTS,
|
||||
)
|
||||
if item.attempts < MAX_ATTEMPTS:
|
||||
_finish(item, "queued", f"retrying: {err}"[:255], done=False)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Logging set-up shared by the API and the worker (`LOG_LEVEL`, `LOG_FORMAT`).
|
||||
|
||||
`text` is human-readable; `json` is one object per line for log aggregators. Fields passed
|
||||
as `extra=` to a log call (e.g. `task`, `duration_ms`) appear as keys in the JSON output.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import UTC, datetime
|
||||
|
||||
TEXT_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"
|
||||
|
||||
# Attributes every LogRecord has; anything else on a record came from `extra=`.
|
||||
_STANDARD = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime", "taskName"}
|
||||
_HANDLER_FLAG = "_scrobbler_handler"
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
entry = {
|
||||
"time": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"),
|
||||
"level": record.levelname,
|
||||
"logger": record.name,
|
||||
"message": record.getMessage(),
|
||||
}
|
||||
entry.update((k, v) for k, v in record.__dict__.items() if k not in _STANDARD)
|
||||
if record.exc_info:
|
||||
entry["exception"] = self.formatException(record.exc_info)
|
||||
return json.dumps(entry, default=str)
|
||||
|
||||
|
||||
def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
|
||||
"""Point the root logger at stderr. Safe to call repeatedly (it replaces its own
|
||||
handler); an unknown level falls back to INFO."""
|
||||
root = logging.getLogger()
|
||||
for handler in [h for h in root.handlers if getattr(h, _HANDLER_FLAG, False)]:
|
||||
root.removeHandler(handler)
|
||||
handler = logging.StreamHandler(sys.stderr)
|
||||
setattr(handler, _HANDLER_FLAG, True)
|
||||
handler.setFormatter(JsonFormatter() if fmt == "json" else logging.Formatter(TEXT_FORMAT))
|
||||
root.addHandler(handler)
|
||||
resolved = logging.getLevelName(str(level).upper())
|
||||
root.setLevel(resolved if isinstance(resolved, int) else logging.INFO)
|
||||
@@ -172,9 +172,14 @@ art_override_actions_total = Counter(
|
||||
"Manual album art actions: correction_requested, retry_requested, override_deleted",
|
||||
["action"],
|
||||
)
|
||||
art_mbid_lookups_total = Counter(
|
||||
"scrobbler_art_mbid_lookups_total",
|
||||
"Album art lookups that tried a scrobble's recording MBID, by result (matched, missed)",
|
||||
["result"],
|
||||
)
|
||||
art_correction_resolutions_total = Counter(
|
||||
"scrobbler_art_correction_resolutions_total",
|
||||
"Worker outcome of a manual correction, by input (mbid or search) and result",
|
||||
"Worker outcome of a manual correction, by input (mbid, release_mbid or search) and result",
|
||||
["input", "result"],
|
||||
)
|
||||
art_correction_wait_seconds = Histogram(
|
||||
|
||||
@@ -11,7 +11,7 @@ config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
fileConfig(config.config_file_name)
|
||||
fileConfig(config.config_file_name, disable_existing_loggers=False)
|
||||
logger = logging.getLogger('alembic.env')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""user album art release mbid
|
||||
|
||||
Revision ID: c7d2f08a19e4
|
||||
Revises: a41c9e2d7b53
|
||||
Create Date: 2026-10-06 23:10:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "c7d2f08a19e4"
|
||||
down_revision = "a41c9e2d7b53"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("user_album_art", sa.Column("release_mbid", sa.String(length=36), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column("user_album_art", "release_mbid")
|
||||
@@ -205,6 +205,7 @@ class UserAlbumArt(db.Model):
|
||||
search_artist: Mapped[str | None] = mapped_column(Text) # correction inputs
|
||||
search_album: Mapped[str | None] = mapped_column(Text)
|
||||
release_group_mbid: Mapped[str | None] = mapped_column(String(36))
|
||||
release_mbid: Mapped[str | None] = mapped_column(String(36)) # alternative to the group ID
|
||||
content_type: Mapped[str | None] = mapped_column(String(32)) # set iff status == "found"
|
||||
error_code: Mapped[str | None] = mapped_column(String(64)) # set iff status == "error"
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
|
||||
|
||||
@@ -176,11 +176,22 @@ class AlbumArtCorrectionSchema(AlbumArtArgsSchema):
|
||||
release_group_mbid = fields.UUID(
|
||||
metadata={"description": "A MusicBrainz release-group ID; skips the search"}
|
||||
)
|
||||
release_mbid = fields.UUID(
|
||||
metadata={
|
||||
"description": "A MusicBrainz release ID, as an alternative to a release-group ID; "
|
||||
"skips the search"
|
||||
}
|
||||
)
|
||||
|
||||
@validates_schema
|
||||
def _needs_a_correction(self, data, **kwargs):
|
||||
if not any(k in data for k in ("search_artist", "search_album", "release_group_mbid")):
|
||||
raise ValidationError("Give a search_artist, search_album or release_group_mbid")
|
||||
ids = ("release_group_mbid", "release_mbid")
|
||||
if not any(k in data for k in ("search_artist", "search_album", *ids)):
|
||||
raise ValidationError(
|
||||
"Give a search_artist, search_album, release_group_mbid or release_mbid"
|
||||
)
|
||||
if all(k in data for k in ids):
|
||||
raise ValidationError("Give a release_group_mbid or a release_mbid, not both")
|
||||
|
||||
|
||||
class AlbumArtOverrideSchema(Schema):
|
||||
@@ -190,6 +201,7 @@ class AlbumArtOverrideSchema(Schema):
|
||||
search_artist = fields.String(allow_none=True)
|
||||
search_album = fields.String(allow_none=True)
|
||||
release_group_mbid = fields.String(allow_none=True)
|
||||
release_mbid = fields.String(allow_none=True)
|
||||
|
||||
|
||||
class AlbumArtFailureSchema(Schema):
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
"""Album art: MusicBrainz release-group search + Cover Art Archive, both free and keyless.
|
||||
|
||||
A scrobble's MBID (the recording) is tried first when we have one for the album: it names
|
||||
the release-group exactly, where the text search can only guess. Without one, or without a
|
||||
matching release, the text search is used as before.
|
||||
|
||||
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
|
||||
@@ -109,42 +113,77 @@ def _stale(row: AlbumArt) -> bool:
|
||||
return now - row.checked_at > threshold
|
||||
|
||||
|
||||
def _find_release_group(artist: str, album: str) -> str | None:
|
||||
"""A matching release-group's MBID, or None if MusicBrainz has no match."""
|
||||
def _musicbrainz_get(path: str, params: dict[str, str], missing_ok: bool = False) -> dict | None:
|
||||
"""GET a MusicBrainz JSON document, retrying server errors and timeouts. With
|
||||
`missing_ok`, a 404 returns None; other client errors and exhausted retries raise."""
|
||||
api_url = current_app.config["MUSICBRAINZ_API_URL"]
|
||||
query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"'
|
||||
params = urllib.parse.urlencode({"query": query, "fmt": "json", "limit": "5"})
|
||||
query = urllib.parse.urlencode({**params, "fmt": "json"})
|
||||
retries = current_app.config["MUSICBRAINZ_RETRIES"]
|
||||
for attempt in range(retries + 1):
|
||||
request = _throttled_request(f"{api_url}release-group/?{params}")
|
||||
request = _throttled_request(f"{api_url}{path}?{query}")
|
||||
try:
|
||||
with (
|
||||
_upstream_call("musicbrainz"),
|
||||
urllib.request.urlopen(request, timeout=10) as response,
|
||||
):
|
||||
body = json.load(response)
|
||||
return json.load(response)
|
||||
except urllib.error.HTTPError as err:
|
||||
if missing_ok and err.code == 404:
|
||||
return None
|
||||
if attempt == retries or err.code < 500:
|
||||
raise
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
if attempt == retries:
|
||||
raise
|
||||
else:
|
||||
groups = body.get("release-groups") or []
|
||||
return groups[0]["id"] if groups else None
|
||||
time.sleep(min(10, 2**attempt))
|
||||
raise TimeoutError("MusicBrainz request exhausted its retries")
|
||||
|
||||
|
||||
def _cover_art_url(release_group_mbid: str) -> str | None:
|
||||
"""The release-group's front cover URL, or None if Cover Art Archive has none.
|
||||
def _find_release_group(artist: str, album: str) -> str | None:
|
||||
"""A matching release-group's MBID, or None if MusicBrainz has no match."""
|
||||
query = f'releasegroup:"{_escape(album)}" AND artist:"{_escape(artist)}"'
|
||||
body = _musicbrainz_get("release-group/", {"query": query, "limit": "5"}) or {}
|
||||
groups = body.get("release-groups") or []
|
||||
return groups[0]["id"] if groups else None
|
||||
|
||||
|
||||
def _release_group_of_recording(recording_mbid: str, album: str) -> str | None:
|
||||
"""The release-group of the recording's release titled `album`, or None if MusicBrainz
|
||||
doesn't know the recording or none of its releases has that title."""
|
||||
body = _musicbrainz_get(
|
||||
f"recording/{recording_mbid}", {"inc": "releases+release-groups"}, missing_ok=True
|
||||
)
|
||||
for release in (body or {}).get("releases") or []:
|
||||
group = release.get("release-group") or {}
|
||||
if (release.get("title") or "").casefold() == album.casefold() and group.get("id"):
|
||||
return group["id"]
|
||||
return None
|
||||
|
||||
|
||||
def _scrobbled_recording_mbid(artist: str, album: str) -> str | None:
|
||||
"""A recording MBID some scrobble of this album carried (the newest), if any."""
|
||||
return db.session.scalar(
|
||||
select(Scrobble.mbid)
|
||||
.where(
|
||||
func.lower(Scrobble.artist) == artist.lower(),
|
||||
func.lower(Scrobble.album) == album.lower(),
|
||||
Scrobble.mbid.is_not(None),
|
||||
)
|
||||
.order_by(Scrobble.played_at.desc())
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
|
||||
def _cover_art_url(mbid: str, entity: str = "release-group") -> str | None:
|
||||
"""The release-group's (or release's) front cover URL, or None if Cover Art Archive
|
||||
has none.
|
||||
|
||||
Cover Art Archive redirects to archive.org for the actual image, which is
|
||||
occasionally slow — retried the same way as the MusicBrainz search, with a longer
|
||||
per-attempt timeout to give that redirect room.
|
||||
"""
|
||||
coverart_url = current_app.config["COVERART_API_URL"]
|
||||
url = f"{coverart_url}release-group/{release_group_mbid}/front-500"
|
||||
url = f"{coverart_url}{entity}/{mbid}/front-500"
|
||||
retries = current_app.config["MUSICBRAINZ_RETRIES"]
|
||||
for attempt in range(retries + 1):
|
||||
request = urllib.request.Request(url, method="HEAD")
|
||||
@@ -173,12 +212,19 @@ def get_cached(artist: str, album: str) -> AlbumArt | None:
|
||||
)
|
||||
|
||||
|
||||
def _resolve(artist: str, album: str) -> tuple[ArtResult, str | None, str | None]:
|
||||
def _resolve(
|
||||
artist: str, album: str, use_scrobble_mbid: bool = True
|
||||
) -> 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)
|
||||
if use_scrobble_mbid and (recording := _scrobbled_recording_mbid(artist, album)):
|
||||
release_group_mbid = _release_group_of_recording(recording, album)
|
||||
outcome = "matched" if release_group_mbid else "missed"
|
||||
metrics.art_mbid_lookups_total.labels(outcome).inc()
|
||||
if release_group_mbid is None:
|
||||
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"
|
||||
return ArtResult(status, image_url), release_group_mbid, None
|
||||
@@ -357,9 +403,10 @@ def request_correction(
|
||||
search_artist: str | None,
|
||||
search_album: str | None,
|
||||
release_group_mbid: str | None,
|
||||
release_mbid: str | None = None,
|
||||
) -> None:
|
||||
"""Queue a corrected lookup (different search text, or a known MusicBrainz
|
||||
release-group) for the worker. A fast, network-free write."""
|
||||
release-group or release) for the worker. A fast, network-free write."""
|
||||
_upsert_override(
|
||||
user_id,
|
||||
artist,
|
||||
@@ -370,6 +417,7 @@ def request_correction(
|
||||
search_artist=search_artist,
|
||||
search_album=search_album,
|
||||
release_group_mbid=release_group_mbid,
|
||||
release_mbid=release_mbid,
|
||||
error_code=None,
|
||||
)
|
||||
metrics.art_override_actions_total.labels("correction_requested").inc()
|
||||
@@ -465,6 +513,7 @@ def list_failures(user_id: int, page: int, limit: int) -> tuple[list[dict], int]
|
||||
"search_artist": override.search_artist,
|
||||
"search_album": override.search_album,
|
||||
"release_group_mbid": override.release_group_mbid,
|
||||
"release_mbid": override.release_mbid,
|
||||
}
|
||||
if override
|
||||
else None
|
||||
@@ -518,15 +567,20 @@ def _claim_correction() -> UserAlbumArt | None:
|
||||
|
||||
|
||||
def _resolve_correction(row: UserAlbumArt) -> tuple[ArtResult, str | None]:
|
||||
"""Live resolution of a user's correction: a known release-group goes straight to
|
||||
Cover Art Archive, otherwise the (corrected) text is searched. Never raises."""
|
||||
if not row.release_group_mbid:
|
||||
"""Live resolution of a user's correction: a known release-group or release goes
|
||||
straight to Cover Art Archive, otherwise the (corrected) text is searched. Never raises."""
|
||||
if not (row.release_group_mbid or row.release_mbid):
|
||||
result, _, error_code = _resolve(
|
||||
row.search_artist or row.artist, row.search_album or row.album
|
||||
row.search_artist or row.artist,
|
||||
row.search_album or row.album,
|
||||
use_scrobble_mbid=False, # the user gave different text: don't second-guess it
|
||||
)
|
||||
return result, error_code
|
||||
try:
|
||||
image_url = _cover_art_url(row.release_group_mbid)
|
||||
if row.release_mbid:
|
||||
image_url = _cover_art_url(row.release_mbid, "release")
|
||||
else:
|
||||
image_url = _cover_art_url(row.release_group_mbid)
|
||||
except Exception as err: # noqa: BLE001 - any upstream failure is recorded on the row
|
||||
log.warning("Corrected art lookup failed for %r/%r: %s", row.artist, row.album, err)
|
||||
return ArtResult("error"), type(err).__name__
|
||||
@@ -540,7 +594,7 @@ def resolve_one_correction() -> bool:
|
||||
if row is None:
|
||||
return False
|
||||
start = time.perf_counter()
|
||||
source = "mbid" if row.release_group_mbid else "search"
|
||||
source = "release_mbid" if row.release_mbid else "mbid" if row.release_group_mbid else "search"
|
||||
result, error_code = _resolve_correction(row)
|
||||
content_type = None
|
||||
if result.status == "found":
|
||||
@@ -602,6 +656,7 @@ def resolve_one_pending() -> bool:
|
||||
row.checked_at = datetime.now(UTC)
|
||||
db.session.commit()
|
||||
metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start)
|
||||
log.info("album art for %r/%r: %s", row.artist, row.album, result.status)
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -549,7 +549,7 @@ def process_job(job: ImportJob) -> None:
|
||||
db.session.rollback()
|
||||
_finish(job, "failed", err.message)
|
||||
except Exception:
|
||||
log.exception("import job %s failed", job.id)
|
||||
log.exception("import job %s (%s) for user %s failed", job.id, job.source, job.user_id)
|
||||
db.session.rollback()
|
||||
_finish(
|
||||
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
|
||||
|
||||
+28
-2
@@ -50,18 +50,44 @@ def registered(app: Flask | None = None) -> list[str]:
|
||||
|
||||
|
||||
def _call(task: _Task) -> bool:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
worked = bool(task.fn())
|
||||
result = task.fn()
|
||||
except Exception:
|
||||
log.exception("worker task %s failed", task.name)
|
||||
log.exception(
|
||||
"worker task %s failed after %.0f ms",
|
||||
task.name,
|
||||
_elapsed_ms(started),
|
||||
extra={"task": task.name, "outcome": "error", "duration_ms": _elapsed_ms(started)},
|
||||
)
|
||||
db.session.rollback()
|
||||
metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc()
|
||||
return False
|
||||
worked = bool(result)
|
||||
if worked or task.every is not None:
|
||||
metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc()
|
||||
duration = _elapsed_ms(started)
|
||||
# Queue tasks are polled every couple of seconds, so only passes that did work are
|
||||
# worth an INFO line; periodic tasks say so only when they report work (a truthy result).
|
||||
log.log(
|
||||
logging.INFO if worked else logging.DEBUG,
|
||||
"worker task %s %s in %.0f ms",
|
||||
task.name,
|
||||
"worked" if worked else "ran (nothing to do)",
|
||||
duration,
|
||||
extra={
|
||||
"task": task.name,
|
||||
"outcome": "worked" if worked else "idle",
|
||||
"duration_ms": duration,
|
||||
},
|
||||
)
|
||||
return worked
|
||||
|
||||
|
||||
def _elapsed_ms(started: float) -> float:
|
||||
return round((time.monotonic() - started) * 1000, 1)
|
||||
|
||||
|
||||
def run_once() -> bool:
|
||||
"""One pass: due periodic tasks, then each queue task once. True if any queue
|
||||
task did work (so there may be more waiting)."""
|
||||
|
||||
+105
-1
@@ -25,6 +25,18 @@ _RELEASE_GROUPS = {
|
||||
}
|
||||
|
||||
|
||||
# Canned recordings (a scrobble's MBID) and the releases MusicBrainz lists them on.
|
||||
RECORDING_MBID = "22222222-2222-2222-2222-222222222222"
|
||||
UNMATCHED_RECORDING_MBID = "33333333-3333-3333-3333-333333333333"
|
||||
_RECORDINGS = {
|
||||
RECORDING_MBID: [
|
||||
{"title": "Some Compilation", "release-group": {"id": "rg-other"}},
|
||||
{"title": "Mbid Album", "release-group": {"id": "rg-found"}},
|
||||
],
|
||||
UNMATCHED_RECORDING_MBID: [{"title": "Another Album", "release-group": {"id": "rg-other"}}],
|
||||
}
|
||||
|
||||
|
||||
def _fake_musicbrainz_caa(environ, start_response):
|
||||
method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]
|
||||
|
||||
@@ -41,7 +53,23 @@ def _fake_musicbrainz_caa(environ, start_response):
|
||||
)
|
||||
return [body]
|
||||
|
||||
if path in ("/release-group/rg-found/front-500", f"/release-group/{FOUND_MBID}/front-500"):
|
||||
if path.startswith("/recording/"):
|
||||
recording = path.rsplit("/", 1)[1]
|
||||
releases = _RECORDINGS.get(recording)
|
||||
if releases is None:
|
||||
start_response("404 Not Found", [("Content-Type", "text/plain")])
|
||||
return [b"not found"]
|
||||
body = json.dumps({"releases": releases}).encode()
|
||||
start_response(
|
||||
"200 OK", [("Content-Type", "application/json"), ("Content-Length", str(len(body)))]
|
||||
)
|
||||
return [body]
|
||||
|
||||
if path in (
|
||||
"/release-group/rg-found/front-500",
|
||||
f"/release-group/{FOUND_MBID}/front-500",
|
||||
f"/release/{FOUND_MBID}/front-500",
|
||||
):
|
||||
body = b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
||||
headers = [("Content-Type", "image/jpeg"), ("Content-Length", str(len(body)))]
|
||||
start_response("200 OK", headers)
|
||||
@@ -746,3 +774,79 @@ def test_failures_endpoint(client, auth, art_config, user):
|
||||
|
||||
def test_failures_requires_auth(client):
|
||||
assert client.get("/api/v1/art/failures").status_code == 401
|
||||
|
||||
|
||||
def scrobble_with_mbid(user, artist, track, album, mbid):
|
||||
scrobbles.submit_scrobbles(
|
||||
user, None, [TrackInput(artist, track, album=album, mbid=mbid, timestamp=int(time.time()))]
|
||||
)
|
||||
|
||||
|
||||
def test_scrobble_mbid_finds_the_release_group_without_a_text_match(art_config, user, metric_delta):
|
||||
# "Mbid Album" matches nothing in the fake's text search, so only the recording can find it
|
||||
matched = metric_delta("scrobbler_art_mbid_lookups_total", result="matched")
|
||||
scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID)
|
||||
art.want("Radiohead", "Mbid Album")
|
||||
assert art.resolve_one_pending() is True
|
||||
found = row("Radiohead", "Mbid Album")
|
||||
assert (found.status, found.release_group_mbid) == ("found", "rg-found")
|
||||
assert matched.delta == 1
|
||||
|
||||
|
||||
def test_scrobble_mbid_with_no_matching_release_falls_back_to_text_search(
|
||||
art_config, user, metric_delta
|
||||
):
|
||||
missed = metric_delta("scrobbler_art_mbid_lookups_total", result="missed")
|
||||
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", UNMATCHED_RECORDING_MBID)
|
||||
art.want("Radiohead", "In Rainbows")
|
||||
art.resolve_one_pending()
|
||||
assert row("Radiohead", "In Rainbows").release_group_mbid == "rg-found"
|
||||
assert missed.delta == 1
|
||||
|
||||
|
||||
def test_unknown_scrobble_mbid_falls_back_to_text_search(art_config, user):
|
||||
unknown = "44444444-4444-4444-4444-444444444444"
|
||||
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", unknown)
|
||||
art.want("Radiohead", "In Rainbows")
|
||||
art.resolve_one_pending()
|
||||
assert row("Radiohead", "In Rainbows").status == "found"
|
||||
|
||||
|
||||
def test_no_scrobble_mbid_means_no_recording_lookup(art_config, user, metric_delta):
|
||||
tried = metric_delta("scrobbler_art_mbid_lookups_total", result="missed")
|
||||
scrobble_with_mbid(user, "Radiohead", "Track", "In Rainbows", None)
|
||||
art.want("Radiohead", "In Rainbows")
|
||||
art.resolve_one_pending()
|
||||
assert row("Radiohead", "In Rainbows").status == "found"
|
||||
assert tried.delta == 0
|
||||
|
||||
|
||||
def test_correction_with_search_text_ignores_the_scrobble_mbid(art_config, user):
|
||||
scrobble_with_mbid(user, "Radiohead", "Track", "Mbid Album", RECORDING_MBID)
|
||||
art.request_correction(user.id, "Radiohead", "Mbid Album", None, "No Art Album", None)
|
||||
art.resolve_one_pending()
|
||||
assert override(user, "Radiohead", "Mbid Album").status == "error" # searched the text given
|
||||
|
||||
|
||||
def test_correction_by_release_mbid_is_resolved_from_the_release(art_config, user, metric_delta):
|
||||
resolved = metric_delta(
|
||||
"scrobbler_art_correction_resolutions_total", input="release_mbid", result="found"
|
||||
)
|
||||
art.request_correction(user.id, "Radiohead", "Inrainbows", None, None, None, FOUND_MBID)
|
||||
assert art.resolve_one_pending() is True
|
||||
fixed = override(user, "Radiohead", "Inrainbows")
|
||||
assert (fixed.status, fixed.release_mbid) == ("found", FOUND_MBID)
|
||||
assert art.read_override_file(fixed) == b"\xff\xd8\xff\xe0fake-jpeg-bytes"
|
||||
assert resolved.delta == 1
|
||||
|
||||
|
||||
def test_correction_api_accepts_a_release_mbid_but_not_both_ids(client, auth):
|
||||
url = "/api/v1/art/album/correction"
|
||||
ok = {"artist": "A", "album": "B", "release_mbid": FOUND_MBID}
|
||||
response = client.put(url, headers=auth, json=ok)
|
||||
assert response.status_code == 202
|
||||
assert response.get_json()["release_mbid"] == FOUND_MBID
|
||||
both = {**ok, "release_group_mbid": FOUND_MBID}
|
||||
assert client.put(url, headers=auth, json=both).status_code == 422
|
||||
bad = {"artist": "A", "album": "B", "release_mbid": "nope"}
|
||||
assert client.put(url, headers=auth, json=bad).status_code == 422
|
||||
@@ -0,0 +1,56 @@
|
||||
import json
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from scrobbler.logsetup import JsonFormatter, configure_logging
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def restore_root_logger():
|
||||
root = logging.getLogger()
|
||||
handlers, level = list(root.handlers), root.level
|
||||
yield
|
||||
root.handlers[:] = handlers
|
||||
root.setLevel(level)
|
||||
|
||||
|
||||
def _record(msg="hello %s", args=("world",), **extra):
|
||||
record = logging.LogRecord("test.logger", logging.INFO, __file__, 1, msg, args, None)
|
||||
record.__dict__.update(extra)
|
||||
return record
|
||||
|
||||
|
||||
def test_json_formatter_emits_fields_and_extras():
|
||||
entry = json.loads(JsonFormatter().format(_record(task="art", duration_ms=12.5)))
|
||||
assert entry["message"] == "hello world"
|
||||
assert entry["level"] == "INFO"
|
||||
assert entry["logger"] == "test.logger"
|
||||
assert entry["task"] == "art"
|
||||
assert entry["duration_ms"] == 12.5
|
||||
assert "time" in entry
|
||||
|
||||
|
||||
def test_json_formatter_includes_exceptions():
|
||||
try:
|
||||
raise ValueError("boom")
|
||||
except ValueError:
|
||||
record = _record()
|
||||
import sys
|
||||
|
||||
record.exc_info = sys.exc_info()
|
||||
assert "ValueError: boom" in json.loads(JsonFormatter().format(record))["exception"]
|
||||
|
||||
|
||||
def test_configure_logging_is_idempotent_and_sets_level():
|
||||
root = logging.getLogger()
|
||||
configure_logging("DEBUG", "json")
|
||||
configure_logging("warning", "text")
|
||||
ours = [h for h in root.handlers if getattr(h, "_scrobbler_handler", False)]
|
||||
assert len(ours) == 1
|
||||
assert root.level == logging.WARNING
|
||||
|
||||
|
||||
def test_unknown_level_falls_back_to_info():
|
||||
configure_logging("LOUD", "text")
|
||||
assert logging.getLogger().level == logging.INFO
|
||||
@@ -89,3 +89,32 @@ def test_worker_cli_lists_and_runs_tasks(app, tasks):
|
||||
assert ran == [1]
|
||||
alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"])
|
||||
assert alias.exit_code == 0, alias.output
|
||||
|
||||
|
||||
def test_a_pass_that_did_work_is_logged_with_its_duration(tasks, caplog):
|
||||
tasks.register_task("busy", lambda: True)
|
||||
with caplog.at_level("INFO", logger="scrobbler.worker"):
|
||||
worker.run_once()
|
||||
record = next(r for r in caplog.records if r.__dict__.get("task") == "busy")
|
||||
assert record.levelname == "INFO"
|
||||
assert record.outcome == "worked"
|
||||
assert record.duration_ms >= 0
|
||||
|
||||
|
||||
def test_idle_passes_are_only_logged_at_debug(tasks, caplog):
|
||||
tasks.register_task("idle", lambda: False)
|
||||
with caplog.at_level("INFO", logger="scrobbler.worker"):
|
||||
worker.run_once()
|
||||
assert not [r for r in caplog.records if r.__dict__.get("task") == "idle"]
|
||||
|
||||
|
||||
def test_failures_log_the_task_name_and_duration(tasks, caplog):
|
||||
def boom():
|
||||
raise RuntimeError("nope")
|
||||
|
||||
tasks.register_task("broken", boom)
|
||||
with caplog.at_level("ERROR", logger="scrobbler.worker"):
|
||||
worker.run_once()
|
||||
record = next(r for r in caplog.records if r.__dict__.get("task") == "broken")
|
||||
assert record.outcome == "error"
|
||||
assert "broken" in record.getMessage()
|
||||
Reference in new issue
Block a user