Publishing core: post, fan out, delete (phase 3, step 4)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m1s
CI / test (push) Successful in 2m26s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

federation/publishing/base.py:
- publish(user_id, username, kind, key, text=, html=): idempotent —
  refuses (returns None, doesn't post) if the user has stopped sharing
  or a post with that key already exists, including when two worker
  passes race (caught as a duplicate-key error at commit, not raised).
  Builds Note + Create addressed from the user's current visibility,
  stores both, and fans out one delivery per distinct accepted
  follower's inbox (shared inbox preferred).
- delete_post(user_id, username, post): sends Delete(Tombstone) to the
  same followers and tombstones the row; a no-op if already deleted.
  Addressed by the post's own visibility at the time it was posted,
  not the user's current setting.
- delete_all_for(user_id, username): deletes every live post, for
  turning sharing off.

Wired into PATCH /settings: turning sharing off now deletes every live
post *before* rejecting followers (reject_all removes the followers
that accepted_inboxes() needs). The phase 2 farewell-actor mechanism
already covers these deliveries with no changes, since it just checks
for any pending delivery on the user's activities.

Small supporting changes: activities.store() made public (used from
publishing now, not just activities.py's own narrow helpers);
followers.accepted_inboxes() for fan-out; ids.py gains
followers_url/note_url/post_page_url; sharing.settings_for()'s unsaved
default object now sets every field a caller might read, not just the
ones the old callers happened to need.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Sonnet 5 committed 2026-09-26 11:51:06 +01:00
1 parent dce90400e6
commit b16ba116c4
10 files changed
+408 -11

No files matched your search

+10 -7
View File
@@ -13,8 +13,11 @@ from scrobbler.federation.models import (
from scrobbler.federation.protocol import vocab
def _store(user_id: int, document_for, public: bool = False) -> FederationActivity:
"""Create an activity. `document_for(activity_url)` builds its JSON."""
def store(user_id: int, document_for, public: bool = False) -> FederationActivity:
"""Create an activity. `document_for(activity_url)` builds its JSON.
Public: used both for our own narrow activity types below (Accept, Reject, Block,
Undo) and, from publishing/base.py, for Create/Delete of posts."""
activity_uuid = str(uuid.uuid4())
document = document_for(ids.activity_url(activity_uuid))
activity = FederationActivity(
@@ -38,7 +41,7 @@ def queue(activity: FederationActivity, inboxes: list[str]) -> list[FederationDe
def accept_follow(username: str, follower: FederationFollower) -> FederationActivity:
activity = _store(
activity = store(
follower.user_id,
lambda url: vocab.accept(url, ids.actor_id(username), follower.follow_activity),
)
@@ -47,7 +50,7 @@ def accept_follow(username: str, follower: FederationFollower) -> FederationActi
def reject_follow(username: str, follower: FederationFollower) -> FederationActivity:
activity = _store(
activity = store(
follower.user_id,
lambda url: vocab.reject(url, ids.actor_id(username), follower.follow_activity),
)
@@ -59,13 +62,13 @@ def reject_follow_activity(
user_id: int, username: str, follow: dict, actor: FederationRemoteActor
) -> FederationActivity:
"""Reject a Follow that never became a follower (e.g. from a blocked account)."""
activity = _store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow))
activity = store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow))
queue(activity, [actor.inbox])
return activity
def block(user_id: int, username: str, actor: FederationRemoteActor) -> FederationActivity:
activity = _store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri))
activity = store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri))
queue(activity, [actor.inbox])
return activity
@@ -82,7 +85,7 @@ def undo_block(
).first()
if block_activity is None:
return None
activity = _store(
activity = store(
user_id, lambda url: vocab.undo(url, ids.actor_id(username), block_activity.document)
)
queue(activity, [actor.inbox])
+5 -3
View File
@@ -5,7 +5,7 @@ from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.extensions import db
from scrobbler.federation import activities, sharing
from scrobbler.federation import activities, publishing, sharing
from scrobbler.federation import followers as follower_state
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation.models import FederationBlock, FederationFollower
@@ -69,7 +69,7 @@ def update_settings(changes):
Turning sharing on makes you findable as your handle. Your handle can't change once
people follow you. Visibility changes apply to new posts only. Turning sharing off
removes all your followers (each is told).
deletes your posts and removes all your followers (each is told).
"""
try:
settings, toggled = sharing.update(g.user.id, changes)
@@ -78,7 +78,9 @@ def update_settings(changes):
if toggled is not None:
fed_metrics.sharing_changes_total.labels(change="enabled" if toggled else "disabled").inc()
if toggled is False:
# Tell every follower (a Reject each), then forget them
# Delete every live post first: reject_all removes the followers that
# accepted_inboxes() needs to know where to send the Deletes.
publishing.delete_all_for(g.user.id, g.user.username)
follower_state.reject_all(g.user.id, g.user.username)
db.session.commit()
return _settings_body(g.user, settings)
+9
View File
@@ -139,3 +139,12 @@ def counts(user_id: int) -> dict[str, int]:
).all()
found = dict(rows)
return {"accepted": found.get("accepted", 0), "pending": found.get("pending", 0)}
def accepted_inboxes(user_id: int) -> list[str]:
"""Delivery inbox (their shared one, or their own) of every accepted follower, for
fanning out a post. Pending followers are excluded: they haven't been let in yet."""
accepted = db.session.scalars(
db.select(FederationFollower).filter_by(user_id=user_id, state="accepted")
).all()
return [follower.actor.delivery_inbox for follower in accepted]
+14
View File
@@ -11,6 +11,10 @@ def actor_id(username: str) -> str:
return f"{base_url()}/users/{username}"
def followers_url(username: str) -> str:
return f"{actor_id(username)}/followers"
def key_id(username: str) -> str:
return f"{actor_id(username)}#main-key"
@@ -27,6 +31,16 @@ def activity_url(activity_uuid: str) -> str:
return f"{base_url()}/activities/{activity_uuid}"
def note_url(username: str, post_uuid: str) -> str:
"""The Note's ActivityPub id (served at /users/<u>/posts/<uuid>)."""
return f"{actor_id(username)}/posts/{post_uuid}"
def post_page_url(username: str, post_uuid: str) -> str:
"""Where a browser following the Note's `url` lands, in the web UI."""
return f"{current_app.config['UI_BASE_URL']}/post.html?id={post_uuid}"
def username_from_actor_id(uri: str | None) -> str | None:
"""`<base>/users/<name>` -> name; None for anything else."""
prefix = f"{base_url()}/users/"
@@ -0,0 +1,8 @@
"""Posts to followers: weekly summaries (weekly.py) and milestones (milestones.py), and
later now-playing. Shared machinery — idempotent publishing, addressing, fan-out and
deletion — lives in base.py.
"""
from scrobbler.federation.publishing.base import delete_all_for, delete_post, publish
__all__ = ["delete_all_for", "delete_post", "publish"]
+129
View File
@@ -0,0 +1,129 @@
"""Publishing posts: building and storing the Note/Create, fanning out to accepted
followers, and deleting.
Each post kind (weekly.py, milestones.py, and later now-playing) decides *when* to post
and builds the text; this module handles what every post shares: idempotence (one row
per (user, key), enforced by federation_posts' unique constraint), addressing from the
user's current visibility, storage, delivery and deletion.
"""
import uuid
from datetime import UTC, datetime
from sqlalchemy.exc import IntegrityError
from scrobbler.extensions import db
from scrobbler.federation import activities, followers, ids, sharing
from scrobbler.federation.models import FederationActivity, FederationPost
from scrobbler.federation.protocol import addressing, vocab
DEFAULT_TAGS = ("Scrobbler",)
def _now() -> datetime:
return datetime.now(UTC)
def publish(
user_id: int,
username: str,
kind: str,
key: str,
*,
text: str,
html: str,
tags: tuple[str, ...] = DEFAULT_TAGS,
) -> FederationPost | None:
"""Post `text`/`html` for the user, keyed by `kind:key`.
Idempotent: a second call with the same (user, kind, key) is a no-op, including when
two worker passes race each other (caught as a duplicate-key error, not raised).
Returns None, without posting, if the user isn't sharing or the key already exists.
"""
settings = sharing.settings_for(user_id)
if not settings.enabled:
return None
full_key = f"{kind}:{key}"
already = db.session.scalar(
db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key)
)
if already:
return None
published = _now().isoformat().replace("+00:00", "Z")
post_uuid = str(uuid.uuid4())
to, cc = addressing.address(settings.visibility, ids.followers_url(username))
note_doc = vocab.note(
ids.note_url(username, post_uuid),
actor_id=ids.actor_id(username),
content_html=html,
published=published,
url=ids.post_page_url(username, post_uuid),
to=to,
cc=cc,
tags=list(tags),
)
# activity.id is a Python-generated UUID (see activities.store), so it's already
# usable below without a flush.
activity = activities.store(
user_id,
lambda url: vocab.create(url, ids.actor_id(username), note_doc, to=to, cc=cc),
public=addressing.is_public_or_unlisted(settings.visibility),
)
post = FederationPost(
user_id=user_id,
kind=kind,
key=full_key,
activity_id=activity.id,
visibility=settings.visibility,
content_text=text,
content_html=html,
)
db.session.add(post)
inboxes = followers.accepted_inboxes(user_id)
if inboxes:
activities.queue(activity, inboxes)
try:
db.session.commit()
except IntegrityError: # posted with this key by a concurrent pass
db.session.rollback()
return None
return post
def delete_post(user_id: int, username: str, post: FederationPost) -> FederationActivity | None:
"""Delete one post: sends Delete to the same inboxes the Create went to, and
tombstones the row (kept, so its key can never be reused). The caller commits.
None if it's already deleted."""
if post.deleted_at is not None:
return None
return _delete(user_id, username, post)
def delete_all_for(user_id: int, username: str) -> int:
"""Sharing switched off: delete every live post before the Rejects go out (call this
before followers.reject_all — it needs accepted_inboxes() to still have somewhere to
send the Deletes). The caller commits. Returns how many were deleted."""
posts = db.session.scalars(
db.select(FederationPost).filter_by(user_id=user_id, deleted_at=None)
).all()
for post in posts:
_delete(user_id, username, post)
return len(posts)
def _delete(user_id: int, username: str, post: FederationPost) -> FederationActivity:
# The post's own visibility at the time it was posted, not the user's current
# setting: a Delete has to reach whoever could have seen the Create.
note_id = post.activity.document["object"]["id"]
to, cc = addressing.address(post.visibility, ids.followers_url(username))
activity = activities.store(
user_id,
lambda url: vocab.delete(url, ids.actor_id(username), note_id, to=to, cc=cc),
public=addressing.is_public_or_unlisted(post.visibility),
)
inboxes = followers.accepted_inboxes(user_id)
if inboxes:
activities.queue(activity, inboxes)
post.deleted_at = _now()
return activity
+5
View File
@@ -20,6 +20,8 @@ def settings_for(user_id: int) -> FederationSettings:
"""The user's settings; unsaved defaults if they've never changed them."""
settings = db.session.get(FederationSettings, user_id)
if settings is None:
# Not added to the session: the model's column defaults apply on INSERT, not
# here, so every field a caller might read has to be set explicitly.
settings = FederationSettings(
user_id=user_id,
enabled=False,
@@ -27,6 +29,9 @@ def settings_for(user_id: int) -> FederationSettings:
manually_approves_followers=False,
discoverable=False,
indexable=False,
timezone="UTC",
post_weekly_summary=True,
post_milestones=True,
)
return settings