From d49aa72be1780481f95e4c84ffae3e876934f6c0 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:23:15 +0100 Subject: [PATCH] Federation tables for followers, inbox and deliveries (phase 2, step 3) New tables on the federation migration branch: followers (pending or accepted, with the Follow activity), per-user blocks, the inbox queue (raw deliveries awaiting verification, deduplicated by activity id), our outgoing activities, and deliveries (per inbox, with retry state). Inbox URLs are capped at 1024 characters (remote actors are validated against it) so the delivery unique index stays within Postgres's btree limit; the remote actor inbox columns shrink to match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/models.py | 123 ++++++++++++++- src/scrobbler/federation/remote.py | 7 +- ...3_federation_followers_inbox_deliveries.py | 148 ++++++++++++++++++ 3 files changed, 272 insertions(+), 6 deletions(-) create mode 100644 src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index cd3f297..f8db629 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -3,8 +3,20 @@ is a foreign key to users. Migrations live on the `federation` Alembic branch."" from datetime import UTC, datetime -from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, LargeBinary, String, Text -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import ( + JSON, + Boolean, + DateTime, + ForeignKey, + Index, + Integer, + LargeBinary, + String, + Text, + UniqueConstraint, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column, relationship from scrobbler.extensions import db @@ -56,8 +68,8 @@ class FederationRemoteActor(db.Model): id: Mapped[int] = mapped_column(Integer, primary_key=True) uri: Mapped[str] = mapped_column(String(2048), unique=True) host: Mapped[str] = mapped_column(String(255), index=True) - inbox: Mapped[str] = mapped_column(String(2048)) - shared_inbox: Mapped[str | None] = mapped_column(String(2048)) + inbox: Mapped[str] = mapped_column(String(1024)) + shared_inbox: Mapped[str | None] = mapped_column(String(1024)) username: Mapped[str | None] = mapped_column(String(255)) # preferredUsername display_name: Mapped[str | None] = mapped_column(String(255)) public_key_id: Mapped[str] = mapped_column(String(2048), index=True) @@ -72,3 +84,106 @@ class FederationRemoteActor(db.Model): @property def delivery_inbox(self) -> str: return self.shared_inbox or self.inbox + + +class FederationFollower(db.Model): + """A remote actor following one of our users.""" + + __tablename__ = "federation_followers" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + remote_actor_id: Mapped[int] = mapped_column( + ForeignKey("federation_remote_actors.id", ondelete="CASCADE") + ) + state: Mapped[str] = mapped_column(String(16)) # pending or accepted + follow_activity_id: Mapped[str] = mapped_column(String(2048)) + follow_activity: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql")) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + accepted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + actor: Mapped[FederationRemoteActor] = relationship(lazy="joined") + + __table_args__ = ( + UniqueConstraint("user_id", "remote_actor_id", name="uq_federation_follower"), + ) + + +class FederationBlock(db.Model): + """A user blocking a remote actor (their follows are refused).""" + + __tablename__ = "federation_blocks" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + remote_actor_id: Mapped[int] = mapped_column( + ForeignKey("federation_remote_actors.id", ondelete="CASCADE") + ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + actor: Mapped[FederationRemoteActor] = relationship(lazy="joined") + + __table_args__ = (UniqueConstraint("user_id", "remote_actor_id", name="uq_federation_block"),) + + +class FederationInboxItem(db.Model): + """A delivery received at an inbox, queued for the worker to verify and process.""" + + __tablename__ = "federation_inbox" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + activity_id: Mapped[str] = mapped_column(String(2048), unique=True) + activity_type: Mapped[str] = mapped_column(String(64)) + actor_uri: Mapped[str] = mapped_column(String(2048)) + inbox_path: Mapped[str] = mapped_column(String(512)) # as received, for the signature + headers: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql")) + body: Mapped[bytes] = mapped_column(LargeBinary) + status: Mapped[str] = mapped_column( + String(16), default="queued" + ) # queued, processed, rejected, failed + reason: Mapped[str | None] = mapped_column(String(255)) + attempts: Mapped[int] = mapped_column(Integer, default=0) + received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + __table_args__ = (Index("ix_federation_inbox_status_received", "status", "received_at"),) + + +class FederationActivity(db.Model): + """An activity we sent (Accept, Reject, Block; posts in phase 3).""" + + __tablename__ = "federation_activities" + + id: Mapped[str] = mapped_column(String(36), primary_key=True) # UUID, part of its URL + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + activity_type: Mapped[str] = mapped_column(String(64)) + document: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql")) + public: Mapped[bool] = mapped_column(Boolean, default=False) # may be fetched by anyone + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class FederationDelivery(db.Model): + """One activity to one inbox, with retries.""" + + __tablename__ = "federation_deliveries" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + activity_id: Mapped[str] = mapped_column( + ForeignKey("federation_activities.id", ondelete="CASCADE"), index=True + ) + inbox: Mapped[str] = mapped_column(String(1024)) # keeps the unique index small + # pending, delivered, failed or abandoned + status: Mapped[str] = mapped_column(String(16), default="pending") + attempts: Mapped[int] = mapped_column(Integer, default=0) + next_attempt_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + last_status: Mapped[int | None] = mapped_column(Integer) + last_error: Mapped[str | None] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + activity: Mapped[FederationActivity] = relationship(lazy="joined") + + __table_args__ = ( + UniqueConstraint("activity_id", "inbox", name="uq_federation_delivery"), + Index("ix_federation_deliveries_due", "status", "next_attempt_at"), + ) diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py index 8253c4e..e244236 100644 --- a/src/scrobbler/federation/remote.py +++ b/src/scrobbler/federation/remote.py @@ -19,6 +19,7 @@ from scrobbler.federation.net import FetchError ACTOR_TYPES = {"Person", "Service", "Application", "Group", "Organization"} MAX_AGE = timedelta(hours=24) +MAX_URL = 1024 class ActorError(Exception): @@ -34,17 +35,19 @@ def _text(value, limit: int) -> str | None: def _parse_actor(uri: str, doc: dict) -> dict: + if len(uri) > 2048: + raise ActorError("actor URI too long") if doc.get("id") != uri: raise ActorError(f"{uri} claims to be {doc.get('id')!r}") if doc.get("type") not in ACTOR_TYPES: raise ActorError(f"{uri} isn't an actor ({doc.get('type')!r})") host = _host(uri) inbox = doc.get("inbox") - if not isinstance(inbox, str) or _host(inbox) != host: + if not isinstance(inbox, str) or _host(inbox) != host or len(inbox) > MAX_URL: raise ActorError(f"{uri} has no inbox on its own host") endpoints = doc.get("endpoints") if isinstance(doc.get("endpoints"), dict) else {} shared = endpoints.get("sharedInbox") - if not isinstance(shared, str) or _host(shared) != host: + if not isinstance(shared, str) or _host(shared) != host or len(shared) > MAX_URL: shared = None key = doc.get("publicKey") if isinstance(key, list): # some servers list several diff --git a/src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py b/src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py new file mode 100644 index 0000000..74e77b7 --- /dev/null +++ b/src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py @@ -0,0 +1,148 @@ +"""federation followers inbox deliveries + +Revision ID: a481855fcb93 +Revises: 211d4743f081 +Create Date: 2026-09-25 21:22:22.746321 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'a481855fcb93' +down_revision = '211d4743f081' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('federation_inbox', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('activity_id', sa.String(length=2048), nullable=False), + sa.Column('activity_type', sa.String(length=64), nullable=False), + sa.Column('actor_uri', sa.String(length=2048), nullable=False), + sa.Column('inbox_path', sa.String(length=512), nullable=False), + sa.Column('headers', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False), + sa.Column('body', sa.LargeBinary(), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('reason', sa.String(length=255), nullable=True), + sa.Column('attempts', sa.Integer(), nullable=False), + sa.Column('received_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('processed_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('activity_id') + ) + with op.batch_alter_table('federation_inbox', schema=None) as batch_op: + batch_op.create_index('ix_federation_inbox_status_received', ['status', 'received_at'], unique=False) + + op.create_table('federation_activities', + sa.Column('id', sa.String(length=36), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('activity_type', sa.String(length=64), nullable=False), + sa.Column('document', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False), + sa.Column('public', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('federation_activities', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_activities_user_id'), ['user_id'], unique=False) + + op.create_table('federation_blocks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('remote_actor_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['remote_actor_id'], ['federation_remote_actors.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id', 'remote_actor_id', name='uq_federation_block') + ) + with op.batch_alter_table('federation_blocks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_blocks_user_id'), ['user_id'], unique=False) + + op.create_table('federation_followers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('remote_actor_id', sa.Integer(), nullable=False), + sa.Column('state', sa.String(length=16), nullable=False), + sa.Column('follow_activity_id', sa.String(length=2048), nullable=False), + sa.Column('follow_activity', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('accepted_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['remote_actor_id'], ['federation_remote_actors.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id', 'remote_actor_id', name='uq_federation_follower') + ) + with op.batch_alter_table('federation_followers', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_followers_user_id'), ['user_id'], unique=False) + + op.create_table('federation_deliveries', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('activity_id', sa.String(length=36), nullable=False), + sa.Column('inbox', sa.String(length=1024), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('attempts', sa.Integer(), nullable=False), + sa.Column('next_attempt_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('last_status', sa.Integer(), nullable=True), + sa.Column('last_error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('delivered_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['activity_id'], ['federation_activities.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('activity_id', 'inbox', name='uq_federation_delivery') + ) + with op.batch_alter_table('federation_deliveries', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_deliveries_activity_id'), ['activity_id'], unique=False) + batch_op.create_index('ix_federation_deliveries_due', ['status', 'next_attempt_at'], unique=False) + + with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op: + batch_op.alter_column('inbox', + existing_type=sa.VARCHAR(length=2048), + type_=sa.String(length=1024), + existing_nullable=False) + batch_op.alter_column('shared_inbox', + existing_type=sa.VARCHAR(length=2048), + type_=sa.String(length=1024), + existing_nullable=True) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op: + batch_op.alter_column('shared_inbox', + existing_type=sa.String(length=1024), + type_=sa.VARCHAR(length=2048), + existing_nullable=True) + batch_op.alter_column('inbox', + existing_type=sa.String(length=1024), + type_=sa.VARCHAR(length=2048), + existing_nullable=False) + + with op.batch_alter_table('federation_deliveries', schema=None) as batch_op: + batch_op.drop_index('ix_federation_deliveries_due') + batch_op.drop_index(batch_op.f('ix_federation_deliveries_activity_id')) + + op.drop_table('federation_deliveries') + with op.batch_alter_table('federation_followers', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_followers_user_id')) + + op.drop_table('federation_followers') + with op.batch_alter_table('federation_blocks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_blocks_user_id')) + + op.drop_table('federation_blocks') + with op.batch_alter_table('federation_activities', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_activities_user_id')) + + op.drop_table('federation_activities') + with op.batch_alter_table('federation_inbox', schema=None) as batch_op: + batch_op.drop_index('ix_federation_inbox_status_received') + + op.drop_table('federation_inbox') + # ### end Alembic commands ###