diff --git a/.env.example b/.env.example index ffd6774..149253d 100644 --- a/.env.example +++ b/.env.example @@ -22,3 +22,8 @@ UI_PORT=8080 PROMETHEUS_PORT=9090 GRAFANA_PORT=3000 GRAFANA_ADMIN_PASSWORD=admin + +# ActivityPub federation (in development; off by default). See src/scrobbler/federation/README.md. +FEDERATION_ENABLED=0 +FEDERATION_DOMAIN= +FEDERATION_BASE_URL= diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 515c14f..3615b1d 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: - run: uv sync --locked - name: Migrations are in sync with the models run: | - uv run flask --app scrobbler db upgrade + uv run flask --app scrobbler db upgrade heads uv run flask --app scrobbler db check - run: uv run pytest diff --git a/README.md b/README.md index 001cfad..56d16ec 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ Unlike live scrobbles, imports keep plays of any age. They still skip rows with ```sh docker compose up -d db # Postgres with a scrobbler_test database uv sync -uv run flask --app scrobbler db upgrade +uv run flask --app scrobbler db upgrade heads uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) python -m http.server 8080 -d frontend # UI uv run flask --app scrobbler worker # background work (imports, …) @@ -105,7 +105,7 @@ uv run pytest # needs TEST_DATABASE_URL (see .env uv run ruff check && uv run ruff format --check ``` -- **Migrations**: after changing `models.py`, run `uv run flask --app scrobbler db migrate -m "…"`. CI fails if the models and migrations disagree. +- **Migrations** come in two branches, `core` and `federation`. After changing core models, run `uv run flask --app scrobbler db migrate --head core@head -m "…"`; federation tables use `--head federation@head` (see `src/scrobbler/federation/README.md`). Apply them with `db upgrade heads`. CI fails if the models and migrations disagree. - **API docs**: after changing an endpoint, run `uv run flask --app scrobbler openapi write --format=json docs/openapi.json`. A test fails if the committed spec is stale. Every route has to appear in the spec, and every UI route has to declare bearer auth. - **Demo traffic**: `uv run python scripts/generate_traffic.py --minutes 5` sends a realistic mix of scrobbles and errors, so the dashboards have something to show. diff --git a/docker/api-entrypoint.sh b/docker/api-entrypoint.sh index 72c75ea..443db7a 100755 --- a/docker/api-entrypoint.sh +++ b/docker/api-entrypoint.sh @@ -3,6 +3,6 @@ set -e if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then # Not under gunicorn, so don't use (or pollute) the multiprocess metrics directory. - env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade + env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade heads fi exec "$@" diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index 59b9f86..1433f55 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -30,6 +30,10 @@ def create_app(config_object=None): app.register_blueprint(lastfm_bp) api.init_app(app) + + from scrobbler import federation # the only place the core touches federation + + federation.init_app(app) CORS( app, resources={r"/api/v1/*": {"origins": app.config["CORS_ORIGINS"]}}, diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md new file mode 100644 index 0000000..b2ffd4a --- /dev/null +++ b/src/scrobbler/federation/README.md @@ -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@`. **Permanent once anyone follows.** | +| `FEDERATION_BASE_URL` | Public `https://` URL of the API, where actors live (`/users/`) | + +## 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. diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py new file mode 100644 index 0000000..b6e95ce --- /dev/null +++ b/src/scrobbler/federation/__init__.py @@ -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. diff --git a/src/scrobbler/federation/config.py b/src/scrobbler/federation/config.py new file mode 100644 index 0000000..a305aff --- /dev/null +++ b/src/scrobbler/federation/config.py @@ -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@ + base_url: str = "" # where actors live: /users/ + + @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." + ) diff --git a/src/scrobbler/federation/protocol/__init__.py b/src/scrobbler/federation/protocol/__init__.py new file mode 100644 index 0000000..e76b2cb --- /dev/null +++ b/src/scrobbler/federation/protocol/__init__.py @@ -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.) +""" diff --git a/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py b/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py index 2157b84..680cf66 100644 --- a/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py +++ b/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py @@ -12,7 +12,7 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd6113d27cce6' down_revision = None -branch_labels = None +branch_labels = ('core',) depends_on = None diff --git a/src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py b/src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py new file mode 100644 index 0000000..7cbc1fb --- /dev/null +++ b/src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py @@ -0,0 +1,25 @@ +"""federation branch root + +Root of the federation branch: federation_* tables are added in revisions on this +branch (flask db migrate --head federation@head) so they stay independent of core +migrations. Intentionally empty. + +Revision ID: federation_0001 +Revises: +Create Date: 2026-09-25 19:58:27.552417 + +""" +# revision identifiers, used by Alembic. +revision = 'federation_0001' +down_revision = None +branch_labels = ('federation',) +# Federation tables reference users, created by the core's first revision. +depends_on = 'd6113d27cce6' + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/tests/conftest.py b/tests/conftest.py index 0346354..0b7739c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,7 +13,7 @@ def app(): app = create_app(TestConfig) with app.app_context(): downgrade(revision="base") # clean slate if a previous run was interrupted - upgrade() + upgrade(revision="heads") # core and federation branches yield app db.session.remove() downgrade(revision="base") diff --git a/tests/test_migrations.py b/tests/test_migrations.py new file mode 100644 index 0000000..c777a62 --- /dev/null +++ b/tests/test_migrations.py @@ -0,0 +1,42 @@ +import pytest +from alembic.script import ScriptDirectory +from flask_migrate import downgrade, upgrade +from sqlalchemy import text + +from scrobbler.extensions import db + + +@pytest.fixture +def scripts(app): + return ScriptDirectory(app.extensions["migrate"].directory) + + +def applied() -> set[str]: + return set(db.session.execute(text("SELECT version_num FROM alembic_version")).scalars()) + + +def head_of(scripts: ScriptDirectory, branch: str) -> str: + return scripts.get_revision(f"{branch}@head").revision + + +def test_there_are_exactly_two_branches(scripts): + labels = {label for rev in scripts.walk_revisions() for label in rev.branch_labels} + assert labels == {"core", "federation"} + assert len(scripts.get_heads()) == 2 + + +def test_both_branches_are_applied(app, scripts): + assert applied() == {head_of(scripts, "core"), head_of(scripts, "federation")} + + +def test_federation_branch_can_be_removed_without_touching_core(app, scripts, user): + core, federation = head_of(scripts, "core"), head_of(scripts, "federation") + try: + db.session.commit() + downgrade(revision="federation@base") + assert applied() == {core} + assert db.session.execute(text("SELECT count(*) FROM users")).scalar_one() == 1 + finally: + db.session.rollback() + upgrade(revision="heads") + assert applied() == {core, federation}