Domain events for optional modules (phase 0, step 1)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 9s
CI / test (push) Successful in 48s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s

scrobbler/events.py defines blinker signals sent after commit:
scrobbles_stored (newly stored plays only, source scrobble/import),
now_playing_changed (track or None) and import_finished. A receiver
that raises is logged and skipped, so optional modules can't break
scrobbling or imports. store_chunk now reports which plays it stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 19:54:27 +01:00
1 parent 247c94a79c
commit 59ff1bdfa0
4 files changed
+165 -20

No files matched your search

+29 -15
View File
@@ -29,7 +29,7 @@ from flask import current_app
from sqlalchemy import update
from sqlalchemy.dialects.postgresql import insert
from scrobbler import metrics
from scrobbler import events, metrics
from scrobbler.extensions import db
from scrobbler.models import ImportJob, Scrobble, User
from scrobbler.services.scrobbles import MAX_TEXT, TrackInput
@@ -314,6 +314,7 @@ def cancel_job(user: User, job_id: int) -> ImportJob | None:
job.payload = None
db.session.commit()
metrics.imports_total.labels(source=job.source, status="cancelled").inc()
events.send(events.import_finished, user, job=job)
return job
@@ -328,10 +329,13 @@ def _usable(item: TrackInput | None, now: datetime) -> bool:
return datetime.fromtimestamp(item.timestamp, UTC) - now <= timedelta(seconds=limit)
def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None:
"""Insert one chunk and update the job's counters (the caller commits)."""
def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> list[TrackInput]:
"""Insert one chunk and update the job's counters (the caller commits).
Returns the plays that were newly stored (not duplicates or skipped rows).
"""
now = _now()
rows, seen = [], set()
rows, seen = [], {}
skipped = repeated = 0
for item in items:
if not _usable(item, now):
@@ -342,7 +346,7 @@ def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None:
if key in seen: # the same play twice in one chunk: ON CONFLICT can't handle that
repeated += 1
continue
seen.add(key)
seen[key] = item
rows.append(
{
"user_id": job.user_id,
@@ -355,16 +359,18 @@ def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None:
"submitted_at": now,
}
)
inserted = 0
stored: list[TrackInput] = []
if rows:
inserted = len(
db.session.execute(
stored = [
seen[tuple(row)]
for row in db.session.execute(
insert(Scrobble)
.values(rows)
.on_conflict_do_nothing(constraint="uq_scrobbles_dedupe")
.returning(Scrobble.id)
).all()
)
.returning(Scrobble.played_at, Scrobble.artist, Scrobble.track)
)
]
inserted = len(stored)
duplicates = len(rows) - inserted + repeated
job.imported += inserted
job.duplicates += duplicates
@@ -375,6 +381,15 @@ def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None:
counter.labels(source=job.source, result="imported").inc(inserted)
counter.labels(source=job.source, result="duplicate").inc(duplicates)
counter.labels(source=job.source, result="skipped").inc(skipped)
return stored
def _store_and_commit(job: ImportJob, items: list[TrackInput | None]) -> None:
stored = store_chunk(job, items)
db.session.commit()
if stored:
user = db.session.get(User, job.user_id)
events.send(events.scrobbles_stored, user, scrobbles=stored, source="import")
def _cancelled(job: ImportJob) -> bool:
@@ -402,8 +417,7 @@ def _process_file(job: ImportJob) -> None:
for chunk in _chunks(items):
if _cancelled(job):
return
store_chunk(job, chunk)
db.session.commit()
_store_and_commit(job, chunk)
# --- Last.fm API pull ------------------------------------------------------------------
@@ -484,9 +498,8 @@ def _process_lastfm(job: ImportJob) -> None:
total_pages = int(attrs.get("totalPages") or 0)
job.total = int(attrs.get("total") or 0)
tracks = list(_json_tracks(body))
store_chunk(job, [_track_from_json(t) for t in tracks])
job.next_page = page + 1
db.session.commit()
_store_and_commit(job, [_track_from_json(t) for t in tracks])
if page >= total_pages or not tracks:
return
page += 1
@@ -553,6 +566,7 @@ def _finish(job: ImportJob, status: str, error: str | None = None) -> None:
job.payload = None
db.session.commit()
metrics.imports_total.labels(source=job.source, status=status).inc()
events.send(events.import_finished, db.session.get(User, job.user_id), job=job)
def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None:
+14 -5
View File
@@ -8,7 +8,7 @@ from flask import current_app
from sqlalchemy import func
from sqlalchemy.dialects.postgresql import insert
from scrobbler import metrics
from scrobbler import events, metrics
from scrobbler.extensions import db
from scrobbler.models import ApiApp, NowPlaying, Scrobble, User
@@ -147,9 +147,15 @@ def submit_scrobbles(user: User, api_app: ApiApp | None, items: list[TrackInput]
if inserted:
metrics.scrobble_lag_seconds.observe(max(0.0, (now - played_at).total_seconds()))
_clear_now_playing(user, [r.item for r in results if r.status != "ignored"])
cleared = _clear_now_playing(user, [r.item for r in results if r.status != "ignored"])
db.session.commit()
stored = [r.item for r in results if r.status == "accepted"]
if stored:
events.send(events.scrobbles_stored, user, scrobbles=stored, source="scrobble")
if cleared:
events.send(events.now_playing_changed, user, track=None)
metrics.scrobble_batch_size.observe(len(items))
for result in results:
metrics.scrobbles_total.labels(result=result.status).inc()
@@ -158,17 +164,19 @@ def submit_scrobbles(user: User, api_app: ApiApp | None, items: list[TrackInput]
return results
def _clear_now_playing(user: User, scrobbled: list[TrackInput]) -> None:
def _clear_now_playing(user: User, scrobbled: list[TrackInput]) -> bool:
"""Remove now-playing if one of the scrobbled tracks is it. Returns True if removed."""
now_playing = db.session.get(NowPlaying, user.id)
if now_playing is None:
return
return False
for item in scrobbled:
if (item.artist.lower(), item.track.lower()) == (
now_playing.artist.lower(),
now_playing.track.lower(),
):
db.session.delete(now_playing)
return
return True
return False
# --- Now playing ---------------------------------------------------------------
@@ -198,6 +206,7 @@ def update_now_playing(user: User, item: TrackInput) -> int:
)
db.session.commit()
metrics.now_playing_updates_total.inc()
events.send(events.now_playing_changed, user, track=item)
return NOT_IGNORED