Admin post-weekly command and GoToSocial post interop checks (phase 3, step 10)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m8s
CI / test (push) Successful in 2m56s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

`flask federation post-weekly --user <name> --now` posts a user's
summary for the week still in progress immediately, ignoring the
Monday-09:00 gate - for operators, and so the interop test can produce
a real post without waiting on calendar time. Backed by a new
weekly.post_now(), sharing _post_for_window() with the normal
check_and_post() path so both go through the same has_post/empty-week/
publish logic; only the window (this week so far, vs. the last gated
one) differs.

Extends the GoToSocial interop driver to a second phase: run.sh seeds
one scrobble directly (the driver container has no way to sign a
Last.fm-API request, and doesn't need one just to seed data), triggers
the CLI command via `docker compose exec api`, then re-runs the driver
with --check-posts to confirm the post reaches the already-following
GoToSocial account's home timeline as `private` (followers-only, our
default) with the expected content, deletes it via the existing
DELETE /posts/{id} API, and confirms it disappears from GoToSocial's
timeline too. The main flow now ends by re-following instead of the
previous test's decline, so the post-check phase has a follower to
check against.

Verified end to end against a real GoToSocial 0.22.1 container locally
before pushing (scripts/interop/run.sh), not just left to CI:
    private post: '<p><strong>My week in music: 1 play</strong></p>...'
    All post interop checks passed

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 16:40:34 +01:00
1 parent de1519a066
commit 860d4d0f93
8 files changed
+244 -8

No files matched your search

+59 -1
View File
@@ -210,6 +210,12 @@ class Scrobbler:
if status not in (200, 204):
fail(f"{action} follower: {status} {body}")
def posts(self):
status, body = api("GET", f"{SCROBBLER_API}/federation/posts", self.token)
if status != 200:
fail(f"listing posts: {status} {body}")
return body
class GoToSocial:
def __init__(self, token):
@@ -249,6 +255,12 @@ class GoToSocial:
fail(f"relationship: {status} {body}")
return body[0]
def home_timeline(self):
status, body = api("GET", f"{GTS}/api/v1/timelines/home", self.token)
if status != 200:
fail(f"home timeline: {status} {body}")
return body
def main():
step("Getting a GoToSocial access token")
@@ -347,8 +359,54 @@ def main():
),
)
step("Re-follow: left in place for the post check (run.sh's second driver pass)")
alice.settings(manually_approves_followers=False)
gts.follow(account_id)
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
step("All interop checks passed")
def check_posts():
"""Second phase, run by run.sh after it triggers `flask federation post-weekly
--now` directly in the api container (this container has no docker access to do that
itself). Checks the post reaches the already-following GoToSocial account's home
timeline as a private (followers-only) status with the expected text, then deletes
it and checks it disappears there too."""
step("Getting a GoToSocial access token")
gts = GoToSocial(gotosocial_token())
alice = Scrobbler() # register-or-login: the same account main() set up
account = gts.resolve("@alice@scrobble.test")
account_id = account["id"]
if not gts.relationship(account_id)["following"]:
fail("GoToSocial isn't following alice; run the main interop flow first")
step("The weekly summary reaches GoToSocial's home timeline")
posted = wait_for(
"the weekly summary in GoToSocial's home timeline",
lambda: next(
(s for s in gts.home_timeline() if s["account"]["acct"] == "alice@scrobble.test"),
None,
),
)
if posted["visibility"] != "private":
fail(f"expected private (followers-only) visibility, got {posted['visibility']!r}")
if "My week in music" not in posted["content"]:
fail(f"unexpected content: {posted['content']!r}")
print(f" {posted['visibility']} post: {posted['content'][:80]!r}")
step("Deleting the post removes it from GoToSocial too")
[post, *_] = alice.posts()
status, body = api("DELETE", f"{SCROBBLER_API}/federation/posts/{post['id']}", alice.token)
if status != 204:
fail(f"deleting the post: {status} {body}")
wait_for(
"the post to disappear from GoToSocial's home timeline",
lambda: not any(s["id"] == posted["id"] for s in gts.home_timeline()),
)
step("All post interop checks passed")
if __name__ == "__main__":
main()
check_posts() if "--check-posts" in sys.argv[1:] else main()
+34 -4
View File
@@ -24,10 +24,7 @@ echo "==> Creating the GoToSocial test user"
--username gtsuser --email gtsuser@gts.test --password 'Interop-Test-Password-1' >/dev/null
"$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null
"$compose" build driver >/dev/null
"$compose" run --rm driver
status=$?
if [ $status -ne 0 ]; then
diagnose() {
echo "==> Scrobbler federation state"
"$compose" exec -T db psql -U scrobbler -d scrobbler -c \
"select activity_type, status, reason, attempts from federation_inbox order by id" -c \
@@ -35,5 +32,38 @@ if [ $status -ne 0 ]; then
from federation_deliveries d join federation_activities a on a.id = d.activity_id order by d.id"
echo "==> Recent logs"
"$compose" logs --tail 200 worker gotosocial | grep -v "api/v1/accounts/relationships" | tail -40
}
"$compose" build driver >/dev/null
"$compose" run --rm driver
status=$?
if [ $status -ne 0 ]; then
diagnose
exit $status
fi
echo "==> Alice scrobbles something, for the weekly summary to have content"
"$compose" exec -T api python3 -c "
from datetime import UTC, datetime
from scrobbler import create_app
from scrobbler.config import Config
from scrobbler.extensions import db
from scrobbler.models import Scrobble, User
app = create_app(Config)
with app.app_context():
user = db.session.scalar(db.select(User).filter_by(username='alice'))
db.session.add(Scrobble(user_id=user.id, artist='Interop Artist', track='Interop Track', played_at=datetime.now(UTC)))
db.session.commit()
"
echo "==> Posting alice's weekly summary immediately"
"$compose" exec -T api flask --app scrobbler federation post-weekly --user alice --now
echo "==> Checking the post reaches GoToSocial, then is removed there when deleted"
"$compose" run --rm driver python /interop/gotosocial_interop.py --check-posts
status=$?
if [ $status -ne 0 ]; then
diagnose
fi
exit $status
+2
View File
@@ -30,11 +30,13 @@ def init_app(app: Flask) -> None:
from scrobbler.api import get_api
from scrobbler.federation import api, openapi, web
from scrobbler.federation.cli import federation_cli
app.register_blueprint(web.bp)
core_api = get_api(app)
core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation")
openapi.register(app, core_api)
app.cli.add_command(federation_cli)
from scrobbler import events, worker
from scrobbler.federation import delivery, inbox
+38
View File
@@ -0,0 +1,38 @@
"""Fediverse admin commands (`flask federation ...`)."""
import click
from flask.cli import AppGroup, with_appcontext
federation_cli = AppGroup("federation", help="Fediverse admin commands.")
@federation_cli.command("post-weekly")
@click.option("--user", "username", required=True, help="Username to post for.")
@click.option(
"--now",
"immediately",
is_flag=True,
required=True,
help="Post about the week still in progress right now, ignoring the Monday-09:00 "
"gate (the only mode this command supports, for operators and testing).",
)
@with_appcontext
def post_weekly(username: str, immediately: bool) -> None:
"""Post one user's weekly summary immediately."""
from scrobbler.extensions import db
from scrobbler.federation.publishing import weekly
from scrobbler.services import accounts
user = accounts.find_user(username)
if user is None:
raise click.ClickException(f"No such user: {username}")
result = weekly.post_now(user.id)
db.session.commit()
if result == "posted":
click.echo(f"Posted a weekly summary for {username}.")
elif result == "already_posted":
click.echo(f"{username} already has a post for this week.")
elif result == "skipped_empty":
click.echo(f"{username} hasn't scrobbled anything this week.")
else:
raise click.ClickException(f"{username} isn't sharing weekly summaries.")
@@ -4,12 +4,18 @@ Weeks run Monday 00:00 to Sunday 24:00 *local time*, computed in the zone itself
a fixed UTC offset), so the window is correct across a daylight-saving change.
"""
from datetime import UTC, datetime, timedelta
from datetime import UTC, date, datetime, timedelta
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
POST_HOUR = 9 # local time a week's summary becomes postable, on the following Monday
def week_key(day: date) -> str:
"""The ISO year-week key (e.g. "2026-W02") for the week a date falls in."""
year, week, _ = day.isocalendar()
return f"{year}-W{week:02d}"
def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, str]:
"""The [start, end) UTC window, and ISO year-week key (e.g. "2026-W02"), of the most
recent Monday-Sunday week whose Monday-POST_HOUR-local posting gate has passed.
@@ -26,8 +32,7 @@ def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, st
start_local = datetime(week_start.year, week_start.month, week_start.day, tzinfo=tz)
end_local = start_local + timedelta(days=7) # wall-clock +7 days: DST-correct on conversion
year, week, _ = week_start.isocalendar()
return start_local.astimezone(UTC), end_local.astimezone(UTC), f"{year}-W{week:02d}"
return start_local.astimezone(UTC), end_local.astimezone(UTC), week_key(week_start)
def current_week_start(now_utc: datetime, tz: ZoneInfo) -> datetime:
@@ -76,6 +76,10 @@ def _check_and_post(settings: FederationSettings, now_utc: datetime) -> str:
tz = schedule.resolve_timezone(settings.timezone)
start, end, key = schedule.target_week(now_utc, tz)
return _post_for_window(user, key, start, end)
def _post_for_window(user, key: str, start: datetime, end: datetime) -> str:
if publishing.has_post(user.id, KIND, key):
return "already_posted" # the common case: checked before, nothing new to do
@@ -90,6 +94,28 @@ def _check_and_post(settings: FederationSettings, now_utc: datetime) -> str:
return "posted" if post is not None else "already_posted" # lost a race with another pass
def post_now(user_id: int, now_utc: datetime | None = None) -> str:
"""Post this user's summary immediately, for the week still in progress, ignoring
the Monday-09:00 gate. For operators (`flask federation post-weekly --now`) and the
interop test - not part of the automated pipeline (check_and_post/check_all), so it
isn't itself gated on post_weekly_summary being checked by a worker pass."""
settings = sharing.settings_for(user_id)
if not (settings.enabled and settings.post_weekly_summary):
result = "disabled"
else:
user = accounts.get_user(user_id)
if user is None:
result = "disabled"
else:
now_utc = now_utc or datetime.now(UTC)
tz = schedule.resolve_timezone(settings.timezone)
start = schedule.current_week_start(now_utc, tz)
key = schedule.week_key(start.astimezone(tz).date())
result = _post_for_window(user, key, start, now_utc)
fed_metrics.weekly_total.labels(result=result).inc()
return result
def preview(user_id: int, now_utc: datetime | None = None) -> tuple[str, str] | None:
"""What a weekly summary would say right now, for the week still in progress. Never
stored or posted: for the Sharing page's live preview. None if the account is gone."""
+14
View File
@@ -82,3 +82,17 @@ def test_resolve_timezone_falls_back_to_utc_for_bad_names(name):
def test_resolve_timezone_passes_through_valid_names():
assert schedule.resolve_timezone("Europe/London") == ZoneInfo("Europe/London")
assert schedule.resolve_timezone("UTC") == ZoneInfo("UTC")
def test_week_key():
assert schedule.week_key(datetime(2025, 12, 29).date()) == "2026-W01"
assert schedule.week_key(datetime(2026, 1, 5).date()) == "2026-W02"
assert schedule.week_key(datetime(2026, 1, 12).date()) == "2026-W03"
def test_current_week_start_is_this_weeks_monday_local():
tz = ZoneInfo("Europe/London")
# A Wednesday, mid-morning UTC
now = local("UTC", 2026, 1, 7, 10)
start = schedule.current_week_start(now, tz)
assert start.astimezone(tz) == local("Europe/London", 2026, 1, 5)
+63
View File
@@ -165,3 +165,66 @@ def test_deleting_a_weekly_post_works_like_any_other_post(fed_ctx, user, sharing
db.session.commit()
assert activity.activity_type == "Delete"
assert db.session.get(FederationPost, post.id).deleted_at is not None
# --- post_now: for operators (flask federation post-weekly --now) and the interop test ---
# Wednesday of the same week a_scrobble_in_the_target_week plays into (2026-01-06 is the
# Tuesday of ISO week 2026-W02, Jan 5-11), well before that week's own posting gate.
MID_WEEK = datetime(2026, 1, 7, 15, tzinfo=UTC)
def test_post_now_posts_the_week_in_progress(fed_ctx, user, sharing_settings):
a_scrobble_in_the_target_week(user)
outcome = weekly.post_now(user.id, MID_WEEK)
assert outcome == "posted"
[post] = posts_for(user.id)
assert post.key == "weekly:2026-W02"
assert "1 play" in post.content_text
def test_post_now_is_idempotent(fed_ctx, user, sharing_settings):
a_scrobble_in_the_target_week(user)
first = weekly.post_now(user.id, MID_WEEK)
second = weekly.post_now(user.id, MID_WEEK)
assert (first, second) == ("posted", "already_posted")
assert len(posts_for(user.id)) == 1
def test_post_now_skips_an_empty_week(fed_ctx, user, sharing_settings):
assert weekly.post_now(user.id, MID_WEEK) == "skipped_empty"
assert posts_for(user.id) == []
def test_post_now_requires_sharing(fed_ctx, user):
a_scrobble_in_the_target_week(user)
assert weekly.post_now(user.id, MID_WEEK) == "disabled"
def test_post_now_requires_weekly_summaries_on(fed_ctx, user, sharing_settings):
sharing.update(user.id, {"post_weekly_summary": False})
a_scrobble_in_the_target_week(user)
assert weekly.post_now(user.id, MID_WEEK) == "disabled"
def test_post_weekly_cli_command(fed_app, fed_ctx, user, sharing_settings):
played(user, "Radiohead", "Reckoner", datetime.now(UTC))
result = fed_app.test_cli_runner().invoke(
args=["federation", "post-weekly", "--user", "alice", "--now"]
)
assert result.exit_code == 0, result.output
assert "Posted" in result.output
assert len(posts_for(user.id)) == 1
def test_post_weekly_cli_command_requires_the_now_flag(fed_app):
result = fed_app.test_cli_runner().invoke(args=["federation", "post-weekly", "--user", "alice"])
assert result.exit_code != 0
def test_post_weekly_cli_command_rejects_an_unknown_user(fed_app, fed_ctx):
result = fed_app.test_cli_runner().invoke(
args=["federation", "post-weekly", "--user", "nobody", "--now"]
)
assert result.exit_code != 0
assert "No such user" in result.output