Federation tables for followers, inbox and deliveries (phase 2, step 3)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 1m42s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 11s
CI / test (push) Successful in 1m42s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
52b9f0b27b
commit
d49aa72be1
3 files changed
+272
-6
No files matched your search
@@ -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"),
|
||||
)
|
||||
@@ -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
|
||||
|
||||
+148
@@ -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 ###
|
||||
Reference in new issue
Block a user