Domain events for optional modules (phase 0, step 1)
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:
1 parent
247c94a79c
commit
59ff1bdfa0
4 files changed
+165
-20
No files matched your search
@@ -0,0 +1,32 @@
|
||||
"""Domain events: how the core tells optional modules (such as federation) what happened.
|
||||
|
||||
The core sends these after committing, so receivers only ever see stored data. Modules
|
||||
subscribe with `signal.connect(receiver)`; the core never imports them.
|
||||
|
||||
scrobbles_stored sender=User, scrobbles=[TrackInput, ...], source="scrobble" | "import"
|
||||
Newly stored plays only: duplicates and ignored ones are left out.
|
||||
now_playing_changed sender=User, track=TrackInput | None (None: stopped or cleared)
|
||||
import_finished sender=User, job=ImportJob (completed, failed or cancelled)
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
from blinker import Namespace, Signal
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_signals = Namespace()
|
||||
|
||||
scrobbles_stored = _signals.signal("scrobbles-stored")
|
||||
now_playing_changed = _signals.signal("now-playing-changed")
|
||||
import_finished = _signals.signal("import-finished")
|
||||
|
||||
|
||||
def send(signal: Signal, sender, **kwargs) -> None:
|
||||
"""Deliver to every receiver. A receiver that raises is logged and skipped: an
|
||||
optional module's bug must never fail a scrobble or an import."""
|
||||
for receiver in signal.receivers_for(sender):
|
||||
try:
|
||||
receiver(sender, **kwargs)
|
||||
except Exception:
|
||||
log.exception("receiver %r of %s failed", receiver, signal.name)
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
|
||||
from scrobbler import events
|
||||
from scrobbler.services import imports, scrobbles
|
||||
from scrobbler.services.scrobbles import TrackInput
|
||||
|
||||
|
||||
@contextmanager
|
||||
def capture(signal):
|
||||
received = []
|
||||
|
||||
def receiver(sender, **kwargs):
|
||||
received.append((sender, kwargs))
|
||||
|
||||
signal.connect(receiver)
|
||||
try:
|
||||
yield received
|
||||
finally:
|
||||
signal.disconnect(receiver)
|
||||
|
||||
|
||||
def track(name, seconds_ago=60, artist="Artist"):
|
||||
return TrackInput(artist=artist, track=name, timestamp=int(time.time()) - seconds_ago)
|
||||
|
||||
|
||||
def test_scrobbles_stored_carries_only_new_plays(app, user):
|
||||
first = track("One")
|
||||
scrobbles.submit_scrobbles(user, None, [first])
|
||||
with capture(events.scrobbles_stored) as received:
|
||||
scrobbles.submit_scrobbles(
|
||||
user,
|
||||
None,
|
||||
[first, track("Two"), TrackInput(artist="", track="x", timestamp=int(time.time()))],
|
||||
)
|
||||
[(sender, kwargs)] = received
|
||||
assert sender.id == user.id
|
||||
assert kwargs["source"] == "scrobble"
|
||||
assert [s.track for s in kwargs["scrobbles"]] == ["Two"]
|
||||
|
||||
|
||||
def test_nothing_is_sent_when_nothing_new_is_stored(app, user):
|
||||
old = track("One")
|
||||
scrobbles.submit_scrobbles(user, None, [old])
|
||||
with capture(events.scrobbles_stored) as received:
|
||||
scrobbles.submit_scrobbles(user, None, [old])
|
||||
assert received == []
|
||||
|
||||
|
||||
def test_now_playing_started_and_cleared(app, user):
|
||||
with capture(events.now_playing_changed) as received:
|
||||
scrobbles.update_now_playing(user, TrackInput(artist="A", track="Song"))
|
||||
scrobbles.submit_scrobbles(user, None, [track("Song", artist="A")])
|
||||
assert [kwargs["track"].track if kwargs["track"] else None for _, kwargs in received] == [
|
||||
"Song",
|
||||
None,
|
||||
]
|
||||
|
||||
|
||||
def test_imports_announce_stored_plays_and_completion(app, user):
|
||||
when = time.strftime("%d %b %Y %H:%M", time.gmtime(time.time() - 86400 * 400))
|
||||
csv = f"Artist,,One,{when}\nArtist,,One,{when}\nArtist,,Two,{when}\n"
|
||||
job = imports.create_file_import(user, "export.csv", csv.encode())
|
||||
with capture(events.scrobbles_stored) as stored, capture(events.import_finished) as finished:
|
||||
imports.run_worker(once=True)
|
||||
[(_, kwargs)] = stored
|
||||
assert kwargs["source"] == "import"
|
||||
assert sorted(s.track for s in kwargs["scrobbles"]) == ["One", "Two"] # the repeat once
|
||||
[(sender, done)] = finished
|
||||
assert sender.id == user.id
|
||||
assert (done["job"].id, done["job"].status) == (job.id, "completed")
|
||||
|
||||
|
||||
def test_cancelling_an_import_announces_it(app, user):
|
||||
job = imports.create_file_import(user, "export.csv", b"A,,T,1600000000\n")
|
||||
with capture(events.import_finished) as finished:
|
||||
imports.cancel_job(user, job.id)
|
||||
assert finished[0][1]["job"].status == "cancelled"
|
||||
|
||||
|
||||
def test_a_failing_receiver_does_not_break_scrobbling(app, user):
|
||||
def broken(sender, **kwargs):
|
||||
raise RuntimeError("listener bug")
|
||||
|
||||
events.scrobbles_stored.connect(broken)
|
||||
try:
|
||||
results = scrobbles.submit_scrobbles(user, None, [track("Still stored")])
|
||||
finally:
|
||||
events.scrobbles_stored.disconnect(broken)
|
||||
assert [r.status for r in results] == ["accepted"]
|
||||
Reference in new issue
Block a user