From ba30d5cb15be47dc652d60702bfcc886a853dd8e Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:13:10 +0100 Subject: [PATCH] Now-playing publisher and worker task (phase 4, step 3) publishing/now_playing.py: a periodic scan (federation.now_playing, every 30s) that pushes a throttled Update(Person) for the profile field (5 minutes) and, for users opted into posts, publishes a Note after a track's been playing 30+ seconds (throttled to 30 minutes), deleting the previous now-playing post once the new one is confirmed published - not before, so a failed publish never leaves a user with none showing. Reuses publishing.publish()/delete_post() unchanged; now_playing is just another post kind. Fixed a real bug before it ever ran against Postgres: the key (artist/track/started_at) was going straight into federation_posts.key (VARCHAR(64)), which routinely overflows for real track and artist names. Hashed instead - it's an idempotency token, not something anyone needs to read. New metric scrobbler_federation_profile_updates_total{result}; posts already get scrobbler_federation_posts_total{kind="now_playing",...} for free from the existing publish() instrumentation. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/__init__.py | 3 +- src/scrobbler/federation/metrics.py | 8 +- src/scrobbler/federation/models.py | 7 +- .../federation/publishing/now_playing.py | 155 +++++++++++++ tests/test_federation_now_playing.py | 214 ++++++++++++++++++ 5 files changed, 382 insertions(+), 5 deletions(-) create mode 100644 src/scrobbler/federation/publishing/now_playing.py create mode 100644 tests/test_federation_now_playing.py diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 5043468..5eedd3f 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -40,7 +40,7 @@ def init_app(app: Flask) -> None: from scrobbler import events, worker from scrobbler.federation import delivery, inbox - from scrobbler.federation.publishing import milestones, weekly + from scrobbler.federation.publishing import milestones, now_playing, weekly worker.register_task(app, "federation.inbox", inbox.work_once) worker.register_task(app, "federation.deliver", delivery.work_once) @@ -48,6 +48,7 @@ def init_app(app: Flask) -> None: worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance) worker.register_periodic(app, "federation.gauges", 30, delivery.maintenance) worker.register_periodic(app, "federation.weekly", 900, weekly.check_all) + worker.register_periodic(app, "federation.now_playing", 30, now_playing.check_all) # blinker signals are process-wide, not per-app: once any app in a process enables # federation these stay connected for every app in it, including one built with diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index 75016ec..a58ce4c 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -53,7 +53,7 @@ followers = Gauge( ) posts_total = Counter( "scrobbler_federation_posts_total", - "Posts published: weekly summaries and milestones", + "Posts published: weekly summaries, milestones and now-playing", ["kind", "visibility"], ) post_deletions_total = Counter( @@ -71,3 +71,9 @@ weekly_total = Counter( "Weekly summary checks, by result: disabled, skipped_empty, already_posted or posted", ["result"], ) +profile_updates_total = Counter( + "scrobbler_federation_profile_updates_total", + "Now-playing Update(Person) pushes: sent, or throttled (still within the 5-minute " + "window since the last one)", + ["result"], +) diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index 031b295..e01904e 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -254,9 +254,10 @@ class FederationPendingCheck(db.Model): class FederationNowPlaying(db.Model): """What we've last told the fediverse is playing, as opposed to `now_playing` in the - core schema, which is what's actually playing. A "key" is `artist\\x1ftrack\\x1f - started_at`: playing the same track again later is a new now-playing moment, not a - stale repeat, and it doubles as federation_posts.key for the posts side.""" + core schema, which is what's actually playing. A "key" is a short hash of `artist, + track, started_at` (see publishing/now_playing.py): playing the same track again + later is a new now-playing moment, not a stale repeat, and it doubles as + federation_posts.key for the posts side.""" __tablename__ = "federation_now_playing" diff --git a/src/scrobbler/federation/publishing/now_playing.py b/src/scrobbler/federation/publishing/now_playing.py new file mode 100644 index 0000000..6eeafdd --- /dev/null +++ b/src/scrobbler/federation/publishing/now_playing.py @@ -0,0 +1,155 @@ +"""Now playing: a live field on the actor profile (actors.py handles that part), and +opt-in posts. + +No event receiver or pending-checks queue like milestones has: the throttle windows (5 +minutes for the profile push, 30 for posts) are far longer than a 30-second poll, so a +plain periodic scan - the same shape as weekly.check_all - is simplest and cheapest. +There's no baseline/import concern either: this only ever reflects what's playing right +now, never history. +""" + +import hashlib +import logging +from datetime import UTC, datetime, timedelta + +from flask import current_app + +from scrobbler.extensions import db +from scrobbler.federation import activities, actors, followers, publishing, sharing +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings +from scrobbler.federation.protocol import content, vocab +from scrobbler.services import accounts +from scrobbler.services.scrobbles import get_now_playing + +KIND = "now_playing" +PROFILE_THROTTLE = timedelta(minutes=5) +POST_THROTTLE = timedelta(minutes=30) +MIN_PLAYED = timedelta(seconds=30) + +log = logging.getLogger(__name__) + + +def _key(playing) -> str: + """A short, fixed-length identifier for "this track, starting at this instant" - + hashed rather than the raw artist/track/timestamp, since federation_posts.key is only + VARCHAR(64) and real artist and track names routinely blow past that on their own.""" + raw = f"{playing.artist}\x1f{playing.track}\x1f{playing.started_at.isoformat()}" + return hashlib.sha256(raw.encode()).hexdigest()[:16] + + +def _state_for(user_id: int) -> FederationNowPlaying: + state = db.session.get(FederationNowPlaying, user_id) + if state is None: + state = FederationNowPlaying(user_id=user_id) + db.session.add(state) + return state + + +def _due(last: datetime | None, throttle: timedelta, now: datetime) -> bool: + return last is None or now - last >= throttle + + +def _urls_for(username: str) -> vocab.ActorUrls: + config = current_app.extensions["federation"] + profile_page = f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}" + return vocab.actor_urls(config.base_url, username, profile_page) + + +def _push_profile(user, settings) -> None: + urls = _urls_for(user.username) + doc = actors.build_document(urls, user, settings) + activity = activities.store( + user.id, lambda url: vocab.update(url, urls.id, doc, to=[urls.followers]) + ) + inboxes = followers.accepted_inboxes(user.id) + if inboxes: + activities.queue(activity, inboxes) + + +def _build_content(playing) -> tuple[str, str]: + text = "\n".join( + [ + f"Now playing: {playing.track} by {playing.artist}", + f"{content.hashtag_line()} #NowPlaying", + ] + ) + html = content.paragraph( + f"Now playing: {content.escape(playing.track)} by {content.escape(playing.artist)}" + ) + content.paragraph(f"{content.hashtag_line()} #NowPlaying") + return text, html + + +def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str: + text, html = _build_content(playing) + post = publishing.publish( + user.id, user.username, KIND, key, text=text, html=html, tags=("Scrobbler", "NowPlaying") + ) + if post is None: + return "none" + if state.post_key is not None: + previous = db.session.scalar( + db.select(FederationPost).filter_by(user_id=user.id, key=f"{KIND}:{state.post_key}") + ) + if previous is not None and previous.deleted_at is None: + publishing.delete_post(user.id, user.username, previous) + state.post_key = key + state.post_posted_at = now + return "posted" + + +def check_and_post(user_id: int, now_utc: datetime | None = None) -> dict[str, str]: + """For one user: push a throttled profile update and/or post, whichever their + now_playing_mode calls for. Returns {"profile": ..., "post": ...}; "profile" is + "unchanged", "throttled" or "sent", "post" is "off", "none" or "posted".""" + settings = sharing.settings_for(user_id) + if settings.now_playing_mode == "off": + return {"profile": "off", "post": "off"} + user = accounts.get_user(user_id) + if user is None: # the account was deleted; federation_settings should follow, but be safe + return {"profile": "off", "post": "off"} + + now_utc = now_utc or datetime.now(UTC) + playing = get_now_playing(user) + current_key = _key(playing) if playing else None + state = _state_for(user_id) + + profile_result = "unchanged" + if current_key != state.profile_key: + if _due(state.profile_updated_at, PROFILE_THROTTLE, now_utc): + _push_profile(user, settings) + state.profile_key = current_key + state.profile_updated_at = now_utc + profile_result = "sent" + else: + profile_result = "throttled" + fed_metrics.profile_updates_total.labels(result=profile_result).inc() + + post_result = "off" + if settings.now_playing_mode == "posts": + post_result = "none" + if ( + playing is not None + and now_utc - playing.started_at >= MIN_PLAYED + and current_key != state.post_key + and _due(state.post_posted_at, POST_THROTTLE, now_utc) + ): + post_result = _post_now_playing(user, playing, current_key, state, now_utc) + + db.session.commit() + return {"profile": profile_result, "post": post_result} + + +def check_all(now_utc: datetime | None = None) -> None: + """Worker task (periodic, every 30 seconds): check every user with now playing on. + One user's failure is logged and doesn't stop the rest from being checked.""" + now_utc = now_utc or datetime.now(UTC) + user_ids = db.session.scalars( + db.select(FederationSettings.user_id).filter(FederationSettings.now_playing_mode != "off") + ).all() + for user_id in user_ids: + try: + check_and_post(user_id, now_utc) + except Exception: + log.exception("now playing check failed for user %s", user_id) + db.session.rollback() diff --git a/tests/test_federation_now_playing.py b/tests/test_federation_now_playing.py new file mode 100644 index 0000000..094e7e0 --- /dev/null +++ b/tests/test_federation_now_playing.py @@ -0,0 +1,214 @@ +"""Now playing end to end: publishing/now_playing.py against a real database.""" + +from datetime import UTC, datetime, timedelta + +import pytest + +from scrobbler.extensions import db +from scrobbler.federation import sharing +from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost +from scrobbler.federation.publishing import now_playing +from scrobbler.models import NowPlaying +from scrobbler.services.scrobbles import TrackInput, update_now_playing + + +def play(user, artist="Radiohead", track="Reckoner") -> datetime: + """Sets the track as playing (started_at = now) and returns that now, so tests + always measure elapsed/throttle time relative to when it actually started, not a + fixed constant that would drift from real test-execution time.""" + update_now_playing(user, TrackInput(artist=artist, track=track)) + return datetime.now(UTC) + + +def stop_playing(user): + """Expire (rather than delete) the row, matching how it naturally goes away.""" + db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1) + db.session.commit() + + +def state_for(user_id): + return db.session.get(FederationNowPlaying, user_id) + + +def updates_for(user_id): + return db.session.scalars( + db.select(FederationActivity).filter_by(user_id=user_id, activity_type="Update") + ).all() + + +def posts_for(user_id): + return db.session.scalars( + db.select(FederationPost).filter_by(user_id=user_id, kind=now_playing.KIND) + ).all() + + +@pytest.fixture +def profile_user(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "now_playing_mode": "profile"}) + return user + + +@pytest.fixture +def posting_user(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "now_playing_mode": "posts"}) + return user + + +def test_off_mode_does_nothing(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) # now_playing_mode defaults to off + now = play(user) + result = now_playing.check_and_post(user.id, now) + assert result == {"profile": "off", "post": "off"} + assert state_for(user.id) is None + assert updates_for(user.id) == [] + + +def test_profile_update_sent_on_a_genuine_change(fed_ctx, profile_user, metric_delta): + now = play(profile_user) + sent = metric_delta("scrobbler_federation_profile_updates_total", result="sent") + result = now_playing.check_and_post(profile_user.id, now) + assert result["profile"] == "sent" + [activity] = updates_for(profile_user.id) + assert activity.document["object"]["attachment"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] + assert sent.delta == 1 + + +def test_profile_update_is_a_noop_when_nothing_changed(fed_ctx, profile_user): + now = play(profile_user) + now_playing.check_and_post(profile_user.id, now) + result = now_playing.check_and_post(profile_user.id, now + timedelta(seconds=30)) + assert result["profile"] == "unchanged" + assert len(updates_for(profile_user.id)) == 1 # not sent again + + +def test_profile_update_throttled_within_5_minutes(fed_ctx, profile_user, metric_delta): + now = play(profile_user, track="Reckoner") + now_playing.check_and_post(profile_user.id, now) + play(profile_user, track="Karma Police") # a genuine change + throttled = metric_delta("scrobbler_federation_profile_updates_total", result="throttled") + result = now_playing.check_and_post(profile_user.id, now + timedelta(minutes=2)) + assert result["profile"] == "throttled" + assert len(updates_for(profile_user.id)) == 1 # still just the first + assert throttled.delta == 1 + + +def test_profile_update_sent_again_once_the_throttle_clears(fed_ctx, profile_user): + now = play(profile_user, track="Reckoner") + now_playing.check_and_post(profile_user.id, now) + play(profile_user, track="Karma Police") + result = now_playing.check_and_post(profile_user.id, now + timedelta(minutes=6)) + assert result["profile"] == "sent" + assert len(updates_for(profile_user.id)) == 2 + + +def test_profile_cleared_when_playback_stops(fed_ctx, profile_user): + now = play(profile_user) + now_playing.check_and_post(profile_user.id, now) + stop_playing(profile_user) + result = now_playing.check_and_post(profile_user.id, now + timedelta(minutes=6)) + assert result["profile"] == "sent" + [_, cleared] = updates_for(profile_user.id) + assert cleared.document["object"]["attachment"] == [] + + +def test_profile_mode_never_posts(fed_ctx, profile_user): + now = play(profile_user) + result = now_playing.check_and_post(profile_user.id, now + timedelta(seconds=31)) + assert result["post"] == "off" + assert posts_for(profile_user.id) == [] + + +def test_post_needs_at_least_30_seconds_played(fed_ctx, posting_user): + now = play(posting_user) + result = now_playing.check_and_post(posting_user.id, now + timedelta(seconds=10)) + assert result["post"] == "none" + assert posts_for(posting_user.id) == [] + + +def test_post_sent_after_30_seconds(fed_ctx, posting_user): + now = play(posting_user) + result = now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + assert result["post"] == "posted" + [post] = posts_for(posting_user.id) + assert "Now playing: Reckoner by Radiohead" in post.content_text + activity = db.session.get(FederationActivity, post.activity_id) + assert activity.activity_type == "Create" + assert activity.document["object"]["tag"] == [ + {"type": "Hashtag", "name": "#Scrobbler"}, + {"type": "Hashtag", "name": "#NowPlaying"}, + ] + + +def test_post_throttled_within_30_minutes(fed_ctx, posting_user): + now = play(posting_user, track="Reckoner") + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + play(posting_user, track="Karma Police") + result = now_playing.check_and_post(posting_user.id, now + timedelta(minutes=10)) + assert result["post"] == "none" + assert len(posts_for(posting_user.id)) == 1 + + +def test_previous_post_deleted_when_a_new_one_goes_out(fed_ctx, posting_user): + now = play(posting_user, track="Reckoner") + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + [first] = posts_for(posting_user.id) + assert first.deleted_at is None + + play(posting_user, track="Karma Police") + now_playing.check_and_post(posting_user.id, now + timedelta(minutes=31)) + + assert db.session.get(FederationPost, first.id).deleted_at is not None + live = [p for p in posts_for(posting_user.id) if p.deleted_at is None] + assert len(live) == 1 + assert "Karma Police" in live[0].content_text + + +def test_stopping_does_not_post_or_delete(fed_ctx, posting_user): + now = play(posting_user) + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + stop_playing(posting_user) + result = now_playing.check_and_post(posting_user.id, now + timedelta(minutes=35)) + assert result["post"] == "none" + live = [p for p in posts_for(posting_user.id) if p.deleted_at is None] + assert len(live) == 1 # the one post from before stopping is left alone + + +def test_check_all_covers_every_user_with_now_playing_on(fed_ctx, make_user): + alice = make_user(username="alice_np") + bob = make_user(username="bob_np") + sharing.update(alice.id, {"enabled": True, "now_playing_mode": "profile"}) + sharing.update(bob.id, {"enabled": True}) # stays off + play(alice) + now = play(bob) + + now_playing.check_all(now) + + assert len(updates_for(alice.id)) == 1 + assert updates_for(bob.id) == [] + + +def test_check_all_isolates_one_users_failure(fed_ctx, make_user, monkeypatch): + alice = make_user(username="alice_np2") + sharing.update(alice.id, {"enabled": True, "now_playing_mode": "profile"}) + now = play(alice) + + def boom(user_id, now_utc=None): + raise RuntimeError("boom") + + monkeypatch.setattr(now_playing, "check_and_post", boom) + now_playing.check_all(now) # doesn't raise + assert state_for(alice.id) is None # never got past the monkeypatched call + + +def test_the_task_is_registered_when_federation_is_on(fed_app): + from scrobbler import worker + + assert "federation.now_playing" in worker.registered(fed_app) + + +def test_the_task_is_not_registered_when_federation_is_off(app): + from scrobbler import worker + + assert "federation.now_playing" not in worker.registered(app)