diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py
index f7e26f5..37602b9 100644
--- a/src/scrobbler/federation/__init__.py
+++ b/src/scrobbler/federation/__init__.py
@@ -36,12 +36,21 @@ def init_app(app: Flask) -> None:
core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation")
openapi.register(app, core_api)
- from scrobbler import worker
+ from scrobbler import events, worker
from scrobbler.federation import delivery, inbox
- from scrobbler.federation.publishing import weekly
+ from scrobbler.federation.publishing import milestones, weekly
worker.register_task(app, "federation.inbox", inbox.work_once)
worker.register_task(app, "federation.deliver", delivery.work_once)
+ worker.register_task(app, "federation.milestones", milestones.work_once)
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)
+
+ # 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
+ # federation off (see test_federation_boundary.py for why "off" is instead enforced
+ # by each receiver checking its own app's config). weak=False because the receivers
+ # are plain module functions meant to live as long as the process does.
+ events.scrobbles_stored.connect(milestones.on_scrobbles_stored, weak=False)
+ events.import_finished.connect(milestones.on_import_finished, weak=False)
diff --git a/src/scrobbler/federation/publishing/milestones.py b/src/scrobbler/federation/publishing/milestones.py
new file mode 100644
index 0000000..c14665e
--- /dev/null
+++ b/src/scrobbler/federation/publishing/milestones.py
@@ -0,0 +1,234 @@
+"""Milestones: total scrobbles, plays of one artist, and entries into a user's all-time
+top 10 — each posted once, the first time it's reached.
+
+Checked only for a user's own live scrobbles (never for imports, which would otherwise
+flood years of history through as if it just happened): the `scrobbles_stored` receiver
+below queues a FederationPendingCheck row, drained by the `federation.milestones` worker
+task. Enabling sharing, and finishing an import, instead call `set_baseline` — every
+threshold already passed is marked done without posting, so a new or returning sharer
+never gets a burst of "congratulations" for plays from years ago.
+"""
+
+import logging
+
+from scrobbler.extensions import db
+from scrobbler.federation import publishing, sharing
+from scrobbler.federation.models import FederationMilestoneMark, FederationPendingCheck
+from scrobbler.federation.protocol import content
+from scrobbler.services import accounts, stats
+
+log = logging.getLogger(__name__)
+
+KIND = "milestone"
+
+SCROBBLE_THRESHOLDS = [1000, 5000, 10000, *range(25000, 500_000, 25000)]
+ARTIST_THRESHOLDS = [100, 500, 1000, 2500, 5000]
+TOP_N = 10
+# A top-10 entry and an artist-plays threshold are only ever checked against a user's
+# current top ARTIST_SCAN artists: crossing 100+ plays for one artist keeps it well
+# within a generous slice, and scanning a user's entire artist list on every scrobble
+# would be unbounded. A crossing that (rarely) falls outside this slice is simply
+# missed rather than triggering a full unpaginated scan.
+ARTIST_SCAN = 20
+
+
+def _existing_marks(user_id: int) -> set[str]:
+ rows = db.session.scalars(db.select(FederationMilestoneMark.key).filter_by(user_id=user_id))
+ return set(rows)
+
+
+def _mark(user_id: int, key: str, *, posted: bool) -> None:
+ db.session.add(FederationMilestoneMark(user_id=user_id, key=key, posted=posted))
+
+
+def _scrobbles_content(threshold: int) -> tuple[str, str]:
+ words = content.plural(threshold, "play")
+ headline = f"{threshold:,} {words} scrobbled"
+ text = "\n".join([headline, content.hashtag_line()])
+ html = content.paragraph(f"{content.escape(headline)}") + content.paragraph(
+ content.hashtag_line()
+ )
+ return text, html
+
+
+def _artist_content(artist: str, threshold: int) -> tuple[str, str]:
+ words = content.plural(threshold, "play")
+ headline = f"{threshold:,} {words} of {artist}"
+ text = "\n".join([headline, content.hashtag_line()])
+ html = content.paragraph(
+ f"{threshold:,} {words} of {content.escape(artist)}"
+ ) + content.paragraph(content.hashtag_line())
+ return text, html
+
+
+def _top10_content(artist: str, rank: int) -> tuple[str, str]:
+ headline = f"{artist} entered my all-time top 10 (#{rank})"
+ text = "\n".join([headline, content.hashtag_line()])
+ html = content.paragraph(f"{content.escape(headline)}") + content.paragraph(
+ content.hashtag_line()
+ )
+ return text, html
+
+
+def _scrobble_milestone(user, existing: set[str]) -> tuple[str, str, str] | None:
+ """(key, text, html) for the highest not-yet-marked scrobble-count threshold this
+ user has reached, marking every lower one reached at the same time silently. None if
+ none has been reached."""
+ count = stats.summary(user)["scrobbles"]
+ reached = [t for t in SCROBBLE_THRESHOLDS if t <= count and f"scrobbles:{t}" not in existing]
+ if not reached:
+ return None
+ for threshold in reached[:-1]:
+ _mark(user.id, f"scrobbles:{threshold}", posted=False)
+ top = reached[-1]
+ text, html = _scrobbles_content(top)
+ return f"scrobbles:{top}", text, html
+
+
+def _artist_milestone(user, existing: set[str]) -> tuple[str, str, str] | None:
+ """(key, text, html) for the highest not-yet-marked plays-of-one-artist threshold
+ reached by any artist in the user's current top ARTIST_SCAN. Only one post per
+ check, even if more than one artist or threshold qualifies at once."""
+ top_artists = stats.top_artists(user, per_page=ARTIST_SCAN).items
+ best: tuple[str, str, int, int] | None = None # (key, artist, threshold, playcount)
+ for artist in top_artists:
+ name = artist.name.lower()
+ reached = [
+ t
+ for t in ARTIST_THRESHOLDS
+ if t <= artist.playcount and f"artist:{name}:{t}" not in existing
+ ]
+ for threshold in reached[:-1]:
+ _mark(user.id, f"artist:{name}:{threshold}", posted=False)
+ if reached and (best is None or reached[-1] > best[2]):
+ best = (f"artist:{name}:{reached[-1]}", artist.name, reached[-1], artist.playcount)
+ if best is None:
+ return None
+ key, artist_name, threshold, _ = best
+ text, html = _artist_content(artist_name, threshold)
+ return key, text, html
+
+
+def _top10_milestone(user, existing: set[str]) -> tuple[str, str, str] | None:
+ """(key, text, html) for the highest-ranked, not-yet-marked new entry into the
+ user's current all-time top 10. Only one post per check.
+
+ Nothing is posted until the user actually has TOP_N distinct artists: with fewer
+ than that, every first play of a new artist would trivially "enter the top 10",
+ which isn't a real milestone.
+ """
+ page = stats.top_artists(user, per_page=TOP_N)
+ if page.total < TOP_N:
+ return None
+ for artist in page.items: # already ranked best first
+ key = f"top10:{artist.name.lower()}"
+ if key not in existing:
+ text, html = _top10_content(artist.name, artist.rank)
+ return key, text, html
+ return None
+
+
+def check_and_post(user_id: int) -> str:
+ """For one user, post at most one milestone: the first of scrobble-count, top-10
+ entry, or artist-plays (in that priority) that has a new, unmarked threshold to
+ report. Returns a result: disabled, none or posted."""
+ settings = sharing.settings_for(user_id)
+ if not (settings.enabled and settings.post_milestones):
+ return "disabled"
+ user = accounts.get_user(user_id)
+ if user is None: # the account was deleted; federation_settings should follow, but be safe
+ return "disabled"
+
+ existing = _existing_marks(user_id)
+ found = (
+ _scrobble_milestone(user, existing)
+ or _top10_milestone(user, existing)
+ or _artist_milestone(user, existing)
+ )
+ if found is None:
+ return "none"
+ key, text, html = found
+ post = publishing.publish(user.id, user.username, KIND, key, text=text, html=html)
+ if post is not None:
+ _mark(user.id, key, posted=True)
+ return "posted" if post is not None else "none" # lost a race with another pass
+
+
+def set_baseline(user_id: int) -> None:
+ """Mark every threshold this user has already passed, without posting: called when
+ a user enables sharing, and after an import finishes, so history already on file
+ never produces a flood of retroactive "milestone" posts."""
+ user = accounts.get_user(user_id)
+ if user is None:
+ return
+ existing = _existing_marks(user_id)
+ count = stats.summary(user)["scrobbles"]
+ for threshold in SCROBBLE_THRESHOLDS:
+ if threshold <= count and f"scrobbles:{threshold}" not in existing:
+ _mark(user_id, f"scrobbles:{threshold}", posted=False)
+ top_artists = stats.top_artists(user, per_page=max(TOP_N, ARTIST_SCAN))
+ has_top10 = top_artists.total >= TOP_N
+ for artist in top_artists.items:
+ name = artist.name.lower()
+ if has_top10 and artist.rank <= TOP_N and f"top10:{name}" not in existing:
+ _mark(user_id, f"top10:{name}", posted=False)
+ for threshold in ARTIST_THRESHOLDS:
+ if threshold <= artist.playcount and f"artist:{name}:{threshold}" not in existing:
+ _mark(user_id, f"artist:{name}:{threshold}", posted=False)
+ db.session.commit()
+
+
+def on_scrobbles_stored(sender, *, scrobbles, source, **kwargs) -> None:
+ """Queue a milestone check for the user's own live scrobbles. Imports are never
+ live listening, so they're excluded here and instead handled by set_baseline via
+ on_import_finished."""
+ if source != "scrobble" or not scrobbles:
+ return
+ settings = sharing.settings_for(sender.id)
+ if not (settings.enabled and settings.post_milestones):
+ return
+ if db.session.get(FederationPendingCheck, sender.id) is None:
+ db.session.add(FederationPendingCheck(user_id=sender.id))
+ db.session.commit()
+
+
+def on_import_finished(sender, *, job, **kwargs) -> None:
+ """An import just finished: mark whatever it added as baseline, silently, rather
+ than queuing a live check that would post about years-old history."""
+ settings = sharing.settings_for(sender.id)
+ if not settings.enabled: # skip the computation for users who've never touched federation
+ return
+ set_baseline(sender.id)
+
+
+def work_once() -> bool:
+ """Claim one pending user (oldest first) and check them. On failure, the row is
+ requeued at the back rather than retried immediately, so one persistently-failing
+ user's checks (a pure DB read — unlike delivery, there's no external server to fail
+ against) can't head-of-line-block everyone behind them."""
+ row = db.session.execute(
+ db.select(FederationPendingCheck)
+ .order_by(FederationPendingCheck.since)
+ .limit(1)
+ .with_for_update(skip_locked=True)
+ ).scalar_one_or_none()
+ if row is None:
+ return False
+ user_id = row.user_id
+ try:
+ check_and_post(user_id)
+ except Exception:
+ log.exception("milestone check failed for user %s", user_id)
+ db.session.rollback()
+ db.session.execute(
+ db.update(FederationPendingCheck)
+ .where(FederationPendingCheck.user_id == user_id)
+ .values(since=db.func.now())
+ )
+ db.session.commit()
+ return True
+ db.session.execute(
+ db.delete(FederationPendingCheck).where(FederationPendingCheck.user_id == user_id)
+ )
+ db.session.commit()
+ return True
diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py
index 70f6603..1f76d9a 100644
--- a/src/scrobbler/federation/sharing.py
+++ b/src/scrobbler/federation/sharing.py
@@ -58,6 +58,9 @@ def update(user_id: int, changes: dict) -> tuple[FederationSettings, bool | None
db.session.commit()
if settings.enabled and not was_enabled:
keys.key_for(user_id) # create the key pair before anyone can fetch the actor
+ from scrobbler.federation.publishing import milestones
+
+ milestones.set_baseline(user_id) # history already on file isn't a "milestone"
toggled = None if settings.enabled == was_enabled else bool(settings.enabled)
return settings, toggled
diff --git a/tests/test_federation_boundary.py b/tests/test_federation_boundary.py
index 88a4580..4e0f0f2 100644
--- a/tests/test_federation_boundary.py
+++ b/tests/test_federation_boundary.py
@@ -16,6 +16,7 @@ import pytest
from scrobbler import create_app, events, worker
from scrobbler.config import TestConfig
+from scrobbler.extensions import db
from scrobbler.federation.config import FederationConfigError
SRC = Path(__file__).resolve().parents[1] / "src"
@@ -165,11 +166,26 @@ def test_nothing_is_registered_when_federation_is_off(app):
assert app.extensions["federation"].enabled is False
views = [view for view in app.view_functions.values() if _from_federation(view)]
assert views == []
- for signal in (events.scrobbles_stored, events.now_playing_changed, events.import_finished):
- assert not any(_from_federation(r) for r in signal.receivers_for(None))
assert not any(name.startswith("federation") for name in worker.registered(app))
+def test_federation_event_receivers_are_no_ops_when_this_app_is_off(app, make_user):
+ """Receivers connect to blinker's process-wide signals, which have no notion of
+ "app": once any app in this test process enables federation (fed_app, or the
+ create_app(_Enabled) calls below), the signal keeps those receivers connected for
+ the rest of the run, whatever this test's own `app` says. So "off" can't be shown by
+ an absence of receivers — it's enforced by each receiver checking *this app's own*
+ config at call time. Firing an event inside this off app's context must therefore
+ still be a no-op, whatever else has already run in the process."""
+ from scrobbler.federation.models import FederationPendingCheck
+
+ assert app.extensions["federation"].enabled is False
+ user = make_user()
+ events.send(events.scrobbles_stored, user, scrobbles=["placeholder"], source="scrobble")
+ events.send(events.import_finished, user, job=None)
+ assert db.session.get(FederationPendingCheck, user.id) is None
+
+
class _Enabled(TestConfig):
FEDERATION_ENABLED = "1"
FEDERATION_DOMAIN = "scrobble.example"
diff --git a/tests/test_federation_milestones.py b/tests/test_federation_milestones.py
new file mode 100644
index 0000000..4387b2e
--- /dev/null
+++ b/tests/test_federation_milestones.py
@@ -0,0 +1,337 @@
+"""Milestones end to end: publishing/milestones.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 (
+ FederationMilestoneMark,
+ FederationPendingCheck,
+ FederationPost,
+)
+from scrobbler.federation.publishing import milestones
+from scrobbler.models import Scrobble
+
+
+def played(user, artist, track, n=1, start=None):
+ start = start or datetime(2020, 1, 1, tzinfo=UTC)
+ for i in range(n):
+ db.session.add(
+ Scrobble(
+ user_id=user.id, artist=artist, track=track, played_at=start + timedelta(minutes=i)
+ )
+ )
+ db.session.commit()
+
+
+@pytest.fixture
+def sharing_settings(fed_ctx, user):
+ """Sharing switched on for a user with no scrobbles yet, so tests can add plays
+ afterwards and treat every threshold crossed as genuinely new."""
+ sharing.update(user.id, {"enabled": True})
+ return sharing.settings_for(user.id)
+
+
+def posts_for(user_id):
+ return db.session.scalars(db.select(FederationPost).filter_by(user_id=user_id)).all()
+
+
+def marks_for(user_id) -> dict[str, bool]:
+ rows = db.session.scalars(db.select(FederationMilestoneMark).filter_by(user_id=user_id))
+ return {row.key: row.posted for row in rows}
+
+
+# --- check_and_post: scrobble-count -----------------------------------------------------
+
+
+def test_nothing_reached_posts_nothing(fed_ctx, user, sharing_settings):
+ played(user, "Radiohead", "Reckoner", n=2)
+ assert milestones.check_and_post(user.id) == "none"
+ assert posts_for(user.id) == []
+
+
+def test_a_scrobble_count_threshold_is_posted(fed_ctx, user, sharing_settings, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ outcome = milestones.check_and_post(user.id)
+ assert outcome == "posted"
+ [post] = posts_for(user.id)
+ assert post.key == "milestone:scrobbles:3"
+ assert "3 plays scrobbled" in post.content_text
+ assert marks_for(user.id) == {"scrobbles:3": True}
+
+
+def test_checking_twice_only_posts_once(fed_ctx, user, sharing_settings, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ first = milestones.check_and_post(user.id)
+ second = milestones.check_and_post(user.id)
+ assert (first, second) == ("posted", "none")
+ assert len(posts_for(user.id)) == 1
+
+
+def test_crossing_several_thresholds_at_once_posts_only_the_highest(
+ fed_ctx, user, sharing_settings, monkeypatch
+):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [2, 3, 5])
+ played(user, "Radiohead", "Reckoner", n=5)
+ outcome = milestones.check_and_post(user.id)
+ assert outcome == "posted"
+ [post] = posts_for(user.id)
+ assert post.key == "milestone:scrobbles:5"
+ # The lower thresholds are marked done, silently, so they're never posted later.
+ assert marks_for(user.id) == {"scrobbles:2": False, "scrobbles:3": False, "scrobbles:5": True}
+
+
+# --- check_and_post: top-10 entry -------------------------------------------------------
+
+
+def test_a_top10_entry_is_posted(fed_ctx, user, sharing_settings, monkeypatch):
+ monkeypatch.setattr(milestones, "TOP_N", 1)
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [])
+ played(user, "Radiohead", "Reckoner", n=3)
+ outcome = milestones.check_and_post(user.id)
+ assert outcome == "posted"
+ [post] = posts_for(user.id)
+ assert post.key == "milestone:top10:radiohead"
+ assert "Radiohead entered my all-time top 10 (#1)" in post.content_text
+ assert marks_for(user.id) == {"top10:radiohead": True}
+
+
+# --- check_and_post: artist plays --------------------------------------------------------
+
+
+def test_an_artist_plays_threshold_is_posted(fed_ctx, user, sharing_settings, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [])
+ monkeypatch.setattr(milestones, "TOP_N", 0)
+ monkeypatch.setattr(milestones, "ARTIST_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ outcome = milestones.check_and_post(user.id)
+ assert outcome == "posted"
+ [post] = posts_for(user.id)
+ assert post.key == "milestone:artist:radiohead:3"
+ assert "3 plays of Radiohead" in post.content_text
+ assert marks_for(user.id) == {"artist:radiohead:3": True}
+
+
+def test_scrobble_count_takes_priority_over_top10_and_artist(
+ fed_ctx, user, sharing_settings, monkeypatch
+):
+ """When more than one kind qualifies in the same check, only the highest-priority
+ one (scrobble count) is posted; the others are left unmarked, to be picked up on a
+ later check rather than silently lost."""
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ monkeypatch.setattr(milestones, "TOP_N", 1)
+ monkeypatch.setattr(milestones, "ARTIST_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ outcome = milestones.check_and_post(user.id)
+ assert outcome == "posted"
+ [post] = posts_for(user.id)
+ assert post.key == "milestone:scrobbles:3"
+ assert marks_for(user.id) == {"scrobbles:3": True}
+
+ # Picked up on the very next check, now that the scrobble-count one is out of the way.
+ outcome = milestones.check_and_post(user.id)
+ assert outcome == "posted"
+ assert len(posts_for(user.id)) == 2
+
+
+# --- disabled / missing users -----------------------------------------------------------
+
+
+def test_milestones_can_be_switched_off(fed_ctx, user, sharing_settings, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ sharing.update(user.id, {"post_milestones": False})
+ assert milestones.check_and_post(user.id) == "disabled"
+ assert posts_for(user.id) == []
+
+
+def test_a_user_who_stopped_sharing_is_not_posted_for(fed_ctx, user, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ sharing.update(user.id, {"enabled": True})
+ played(user, "Radiohead", "Reckoner", n=3)
+ sharing.update(user.id, {"enabled": False})
+ assert milestones.check_and_post(user.id) == "disabled"
+ assert posts_for(user.id) == []
+
+
+def test_a_user_id_that_has_never_shared_is_handled_gracefully(fed_ctx):
+ assert milestones.check_and_post(999_999) == "disabled"
+
+
+# --- set_baseline: no retroactive posts -------------------------------------------------
+
+
+def test_set_baseline_marks_existing_thresholds_without_posting(fed_ctx, user, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ monkeypatch.setattr(milestones, "TOP_N", 1)
+ monkeypatch.setattr(milestones, "ARTIST_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+
+ milestones.set_baseline(user.id)
+
+ assert posts_for(user.id) == []
+ assert marks_for(user.id) == {
+ "scrobbles:3": False,
+ "top10:radiohead": False,
+ "artist:radiohead:3": False,
+ }
+
+
+def test_enabling_sharing_baselines_existing_history(fed_ctx, user, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ monkeypatch.setattr(milestones, "TOP_N", 0) # isolate to the scrobble-count check
+ played(user, "Radiohead", "Reckoner", n=3)
+
+ sharing.update(user.id, {"enabled": True}) # history predates sharing
+
+ assert marks_for(user.id) == {"scrobbles:3": False}
+ assert milestones.check_and_post(user.id) == "none"
+ assert posts_for(user.id) == []
+
+
+def test_disabling_and_re_enabling_does_not_re_baseline(
+ fed_ctx, user, sharing_settings, monkeypatch
+):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ milestones.check_and_post(user.id) # posts scrobbles:3
+ [post] = posts_for(user.id)
+
+ sharing.update(user.id, {"enabled": False})
+ sharing.update(user.id, {"enabled": True})
+
+ assert posts_for(user.id) == [post] # unchanged, not re-posted or duplicated
+
+
+def test_import_finished_baselines_when_sharing_is_on(fed_ctx, user, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ monkeypatch.setattr(milestones, "TOP_N", 0) # isolate to the scrobble-count check
+ sharing.update(user.id, {"enabled": True})
+ played(user, "Radiohead", "Reckoner", n=3)
+
+ milestones.on_import_finished(user, job=None)
+
+ assert marks_for(user.id) == {"scrobbles:3": False}
+
+
+def test_import_finished_skips_users_who_have_never_shared(fed_ctx, user, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+
+ milestones.on_import_finished(user, job=None) # settings.enabled is False
+
+ assert marks_for(user.id) == {}
+
+
+# --- the scrobbles_stored receiver: live plays only --------------------------------------
+
+
+def pending_for(user_id) -> FederationPendingCheck | None:
+ return db.session.get(FederationPendingCheck, user_id)
+
+
+def test_a_live_scrobble_queues_a_pending_check(fed_ctx, user, sharing_settings):
+ milestones.on_scrobbles_stored(user, scrobbles=["placeholder"], source="scrobble")
+ assert pending_for(user.id) is not None
+
+
+def test_an_import_does_not_queue_a_pending_check(fed_ctx, user, sharing_settings):
+ milestones.on_scrobbles_stored(user, scrobbles=["placeholder"], source="import")
+ assert pending_for(user.id) is None
+
+
+def test_an_empty_batch_does_not_queue_a_pending_check(fed_ctx, user, sharing_settings):
+ milestones.on_scrobbles_stored(user, scrobbles=[], source="scrobble")
+ assert pending_for(user.id) is None
+
+
+def test_a_scrobble_is_a_noop_when_milestones_are_off(fed_ctx, user, sharing_settings):
+ sharing.update(user.id, {"post_milestones": False})
+ milestones.on_scrobbles_stored(user, scrobbles=["placeholder"], source="scrobble")
+ assert pending_for(user.id) is None
+
+
+def test_a_scrobble_is_a_noop_when_not_sharing(fed_ctx, user):
+ milestones.on_scrobbles_stored(user, scrobbles=["placeholder"], source="scrobble")
+ assert pending_for(user.id) is None
+
+
+def test_repeated_scrobbles_collapse_into_one_pending_row(fed_ctx, user, sharing_settings):
+ milestones.on_scrobbles_stored(user, scrobbles=["a"], source="scrobble")
+ milestones.on_scrobbles_stored(user, scrobbles=["b"], source="scrobble") # no error, no 2nd row
+ assert (
+ db.session.scalar(
+ db.select(db.func.count())
+ .select_from(FederationPendingCheck)
+ .filter_by(user_id=user.id)
+ )
+ == 1
+ )
+
+
+# --- work_once: draining the queue --------------------------------------------------------
+
+
+def test_work_once_returns_false_when_nothing_is_pending(fed_ctx):
+ assert milestones.work_once() is False
+
+
+def test_work_once_checks_and_clears_a_pending_user(fed_ctx, user, sharing_settings, monkeypatch):
+ monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3])
+ played(user, "Radiohead", "Reckoner", n=3)
+ db.session.add(FederationPendingCheck(user_id=user.id))
+ db.session.commit()
+
+ assert milestones.work_once() is True
+
+ assert pending_for(user.id) is None
+ assert len(posts_for(user.id)) == 1
+
+
+def test_work_once_processes_the_oldest_pending_user_first(fed_ctx, make_user, sharing_settings):
+ later = make_user(username="later")
+ sharing.update(later.id, {"enabled": True})
+ earlier = sharing_settings # the sharing_settings fixture's own user
+
+ now = datetime.now(UTC)
+ db.session.add(FederationPendingCheck(user_id=later.id, since=now))
+ db.session.add(
+ FederationPendingCheck(user_id=earlier.user_id, since=now - timedelta(minutes=5))
+ )
+ db.session.commit()
+
+ milestones.work_once()
+
+ assert pending_for(earlier.user_id) is None
+ assert pending_for(later.id) is not None
+
+
+def test_work_once_requeues_on_failure(fed_ctx, user, sharing_settings, monkeypatch):
+ def boom(user_id):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(milestones, "check_and_post", boom)
+ db.session.add(FederationPendingCheck(user_id=user.id, since=datetime(2020, 1, 1, tzinfo=UTC)))
+ db.session.commit()
+
+ assert milestones.work_once() is True
+
+ row = pending_for(user.id)
+ assert row is not None # requeued, not dropped
+ assert row.since > datetime(2020, 1, 1, tzinfo=UTC) # pushed to the back of the queue
+
+
+def test_the_task_is_registered_when_federation_is_on(fed_app):
+ from scrobbler import worker
+
+ assert "federation.milestones" in worker.registered(fed_app)
+
+
+def test_the_task_is_not_registered_when_federation_is_off(app):
+ from scrobbler import worker
+
+ assert "federation.milestones" not in worker.registered(app)