Federation module skeleton and its own migration branch (phase 0, steps 3-4)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 12s
CI / test (push) Successful in 50s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s

- scrobbler.federation with init_app() as its only entry point, called
  from create_app(); does nothing unless FEDERATION_ENABLED
- FederationConfig validates FEDERATION_DOMAIN (bare host) and
  FEDERATION_BASE_URL (https) when enabled, with clear errors
- federation/protocol/ package for pure, framework-free protocol code
- Package README with the boundary rules, configuration and migration
  workflow; .env.example lists the settings (off)
- Alembic: existing history labelled `core`; new empty `federation`
  branch root (depends on the core users table). Everything upgrades
  `heads` (entrypoint, CI, tests); tests check both branches apply and
  that federation can be removed without touching core

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 19:59:47 +01:00
1 parent 098eab025f
commit c79c42ee00
13 files changed
+212 -6

No files matched your search

+46
View File
@@ -0,0 +1,46 @@
# `scrobbler.federation`
ActivityPub support, kept apart from the rest of the app so it can be changed, replaced
or switched off without touching anything else. Design: `docs/design/activitypub.md`.
## Boundary rules (enforced by `tests/test_federation_boundary.py`)
1. **Nothing outside this package imports it**, except `create_app()` calling
`federation.init_app(app)`. The core reports what happened through the domain events
in `scrobbler.events`; this package subscribes to them.
2. **`protocol/` is pure**: no Flask, SQLAlchemy, Werkzeug or `scrobbler` imports.
Signature schemes, vocabulary and document formats live there.
3. **The rest of this package uses only the core's public surface**:
- `scrobbler.events`
- `scrobbler.extensions` (`db`)
- `scrobbler.worker`
- `scrobbler.services.*`
- `scrobbler.api.decorators`
- `scrobbler.schemas`
So no core models and no core metrics; federation defines its own.
4. **Off means off.** With `FEDERATION_ENABLED` unset, `init_app` registers no routes,
no event receivers and no worker tasks.
## Configuration
| Variable | Meaning |
|---|---|
| `FEDERATION_ENABLED` | `1` to turn federation on (default off) |
| `FEDERATION_DOMAIN` | Handle domain: users are `@name@<domain>`. **Permanent once anyone follows.** |
| `FEDERATION_BASE_URL` | Public `https://` URL of the API, where actors live (`<base>/users/<name>`) |
## Migrations
Federation's tables (all prefixed `federation_`) live in their own Alembic branch,
labelled `federation`, so they can be changed or dropped without touching core
migrations:
```sh
uv run flask --app scrobbler db migrate --head federation@head -m "…" # federation tables
uv run flask --app scrobbler db migrate --head core@head -m "…" # everything else
uv run flask --app scrobbler db upgrade heads # apply both branches
```
When generating a federation migration, check it only touches `federation_*` tables.
Autogenerate compares all models, so core changes would otherwise leak into it.
+26
View File
@@ -0,0 +1,26 @@
"""ActivityPub federation: optional, self-contained, replaceable.
The rest of Scrobbler only calls `init_app(app)` (from `create_app`) and sends domain
events (`scrobbler.events`). Everything else about federation lives in this package;
see README.md here and docs/design/activitypub.md.
With FEDERATION_ENABLED off (the default) `init_app` registers nothing: no routes, no
event receivers, no worker tasks.
"""
import logging
from flask import Flask
from scrobbler.federation.config import FederationConfig
log = logging.getLogger(__name__)
def init_app(app: Flask) -> None:
config = FederationConfig.from_mapping(app.config)
app.extensions["federation"] = config
if not config.enabled:
return
log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url)
# Phase 1 onwards registers routes, event receivers and worker tasks here.
+51
View File
@@ -0,0 +1,51 @@
import os
from collections.abc import Mapping
from dataclasses import dataclass
from urllib.parse import urlsplit
class FederationConfigError(ValueError):
pass
def _flag(value) -> bool:
return str(value).strip().lower() in {"1", "true", "yes", "on"}
@dataclass(frozen=True)
class FederationConfig:
enabled: bool = False
domain: str = "" # the handle's domain: @user@<domain>
base_url: str = "" # where actors live: <base_url>/users/<username>
@classmethod
def from_mapping(cls, config: Mapping) -> "FederationConfig":
"""Read FEDERATION_* from the Flask config, falling back to the environment."""
def get(key: str, default: str = "") -> str:
value = config.get(key)
return str(value if value is not None else os.environ.get(key, default))
result = cls(
enabled=_flag(get("FEDERATION_ENABLED", "0")),
domain=get("FEDERATION_DOMAIN").strip().lower(),
base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"),
)
result.validate()
return result
def validate(self) -> None:
if not self.enabled:
return
if not self.domain or "/" in self.domain or ":" in self.domain:
raise FederationConfigError(
"FEDERATION_DOMAIN must be a bare host name (e.g. scrobble.example) when "
"FEDERATION_ENABLED is on. It becomes part of every handle and can't change "
"once people follow."
)
url = urlsplit(self.base_url)
if url.scheme != "https" or not url.netloc or url.query or url.fragment:
raise FederationConfigError(
"FEDERATION_BASE_URL must be the public https:// URL the API is served at "
"(e.g. https://api.scrobble.example) when FEDERATION_ENABLED is on."
)
@@ -0,0 +1,7 @@
"""Pure ActivityPub protocol code: vocabulary builders, addressing, WebFinger and
NodeInfo documents, HTTP signature schemes.
Rule: nothing in this package imports Flask, SQLAlchemy, Werkzeug or any other part of
Scrobbler; only the standard library and `cryptography`. Spec changes land here and are
tested with spec test vectors alone. (Enforced by tests/test_federation_boundary.py.)
"""