From f8cba88d2e87d7029f7cfcfc57f3a90459a63d24 Mon Sep 17 00:00:00 2001 From: BukeLy Date: Mon, 23 Nov 2026 14:23:45 +0800 Subject: [PATCH] refactor: mailbox.py becomes messages.py, so it no longer hides the standard library's mailbox Run from outside server/, import mailbox got the standard library's module, and ruff needed known-first-party to sort it as ours. The module keeps its contents. Three panel tests name their transcript transcript, not messages, so no local hides the module. --- server/Dockerfile | 2 +- server/accounts.py | 2 +- server/instance.py | 12 ++--- server/{mailbox.py => messages.py} | 0 server/panel.py | 8 ++-- server/pyproject.toml | 3 -- server/server.py | 52 ++++++++++----------- server/tests/test_inbox.py | 72 +++++++++++++++--------------- 8 files changed, 75 insertions(+), 76 deletions(-) rename server/{mailbox.py => messages.py} (100%) diff --git a/server/Dockerfile b/server/Dockerfile index c4656a9..d1be124 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -9,7 +9,7 @@ FROM python:3.15-slim-trixie LABEL io.modelcontextprotocol.server.name="io.github.BukeLy/peerbox" WORKDIR /app COPY --from=build /app/.venv /app/.venv -COPY server.py instance.py accounts.py mailbox.py bucket.py panel.py icon.png schema.sql ./ +COPY server.py instance.py accounts.py messages.py bucket.py panel.py icon.png schema.sql ./ COPY panel ./panel ENV PATH="/app/.venv/bin:$PATH" CMD exec granian --interface asgi --loop uvloop --http 1 --no-ws --host 0.0.0.0 --port "${PORT:-8000}" server:app diff --git a/server/accounts.py b/server/accounts.py index 632d135..feb13f2 100644 --- a/server/accounts.py +++ b/server/accounts.py @@ -7,7 +7,7 @@ from asyncpg import Connection, UniqueViolationError -from mailbox import Address, Refused, wake_known_by +from messages import Address, Refused, wake_known_by # Letters, digits and single hyphens, as in GitHub's logins; matched in any case. USERNAME = r"[A-Za-z0-9]+(-[A-Za-z0-9]+)*" diff --git a/server/instance.py b/server/instance.py index f9dd545..3b36352 100644 --- a/server/instance.py +++ b/server/instance.py @@ -20,7 +20,7 @@ from fastmcp.utilities.logging import get_logger import accounts -import mailbox +import messages HERE = Path(__file__).parent logger = get_logger("peerbox") @@ -83,7 +83,7 @@ async def _expire_hourly() -> None: while True: try: async with get_db() as db: - await mailbox.expire(db) + await messages.expire(db) except Exception: logger.exception("Deleting old messages failed") await asyncio.sleep(3600) @@ -108,7 +108,7 @@ async def database(server): listener = await connect(DATABASE_URL) expiry = asyncio.create_task(_expire_hourly()) try: - await listener.add_listener(mailbox.CHANNEL, waiters.wake) + await listener.add_listener(messages.CHANNEL, waiters.wake) yield {} finally: expiry.cancel() @@ -136,11 +136,11 @@ async def admit(token: str, claims: dict) -> bool: }, timeout=10, ) as github: - if mailbox.GITHUB_ORG is None: + if messages.GITHUB_ORG is None: await _record_organisations(github, claims) admitted = True else: - admitted = await _member_or_guest(github, mailbox.GITHUB_ORG) + admitted = await _member_or_guest(github, messages.GITHUB_ORG) if admitted: now = time.monotonic() for stale in [held for held, until in _admitted_until.items() if until <= now]: @@ -179,4 +179,4 @@ async def _record_organisations(github: httpx2.AsyncClient, claims: dict) -> Non page = installed.links.get("next", {}).get("url") async with get_db() as db: you = await accounts.sign_in(db, claims) - await mailbox.record_memberships(db, you.person, orgs) + await messages.record_memberships(db, you.person, orgs) diff --git a/server/mailbox.py b/server/messages.py similarity index 100% rename from server/mailbox.py rename to server/messages.py diff --git a/server/panel.py b/server/panel.py index 03f81cf..614d541 100644 --- a/server/panel.py +++ b/server/panel.py @@ -17,7 +17,7 @@ import accounts import instance -import mailbox +import messages HERE = Path(__file__).parent CALLBACK_URL = f"{instance.BASE_URL}/login/callback" @@ -152,14 +152,14 @@ async def route(request: Request) -> Response: async def me(db, person: int, request: Request) -> dict | None: shown = await accounts.profile(db, person) - return shown and shown | await mailbox.contacts_and_groups(db, person) + return shown and shown | await messages.contacts_and_groups(db, person) async def conversations(db, person: int, request: Request) -> dict: - return await mailbox.conversations(db, person) + return await messages.conversations(db, person) async def history(db, person: int, request: Request) -> dict: before = request.query_params.get("before", "") - return await mailbox.history( + return await messages.history( db, person, request.path_params["key"], diff --git a/server/pyproject.toml b/server/pyproject.toml index f058f3d..83cecab 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -34,6 +34,3 @@ extend-immutable-calls = [ "fastmcp.dependencies.CurrentContext", "fastmcp.dependencies.Depends", ] - -[tool.ruff.lint.isort] -known-first-party = ["mailbox"] # ours, not the standard library's mailbox diff --git a/server/server.py b/server/server.py index 4b05bb6..13902f4 100644 --- a/server/server.py +++ b/server/server.py @@ -51,7 +51,7 @@ import accounts import instance -import mailbox +import messages import panel from instance import BASE_URL, DATABASE_URL, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET @@ -235,10 +235,10 @@ def limit_key(ctx) -> str: async def me( db: Connection, token: AccessToken, agent: str | None = None -) -> mailbox.Address: +) -> messages.Address: """The caller's address: them, or one of their agents, which must have read its inbox once.""" - return await mailbox.as_agent(db, await accounts.sign_in(db, token.claims), agent) + return await messages.as_agent(db, await accounts.sign_in(db, token.claims), agent) @mcp.tool(annotations=READ) @@ -293,7 +293,7 @@ async def set_remark( """ you = await me(db, token) other = await accounts.resolve(db, username) - kept = await mailbox.set_remark(db, you.person, other, remark) + kept = await messages.set_remark(db, you.person, other, remark) return {"username": str(other), "remark": kept} @@ -312,7 +312,7 @@ async def contacts( name fits, or more than one does, ask your user who they mean. To reach someone who is not a contact, ask with add_contact. """ - return await mailbox.contacts_and_groups(db, (await me(db, token)).person) + return await messages.contacts_and_groups(db, (await me(db, token)).person) @mcp.tool(annotations=WRITE) @@ -348,7 +348,7 @@ async def send( group, with `reply_to` set to its id. """ you = await me(db, token, from_agent) - return await mailbox.send( + return await messages.send( db, you, await accounts.resolve(db, to), text, reply_to, attachments ) @@ -377,7 +377,7 @@ async def inbox( their ids, and the same agent you read as, once you have handled them. """ you = replace(await me(db, token), agent=agent) - return {"notice": NOTICE} | await mailbox.inbox(db, you, limit) + return {"notice": NOTICE} | await messages.inbox(db, you, limit) @mcp.tool(annotations=IDEMPOTENT_WRITE) @@ -399,7 +399,7 @@ async def mark_read( address you read them as are marked. """ you = await me(db, token, agent) - return {"marked_read": await mailbox.mark_read(db, you, ids)} + return {"marked_read": await messages.mark_read(db, you, ids)} @mcp.tool(annotations=WRITE) @@ -418,7 +418,7 @@ async def create_group( agents with invite. """ you = await me(db, token, from_agent) - return {"group": str(await mailbox.create_group(db, you, name))} + return {"group": str(await messages.create_group(db, you, name))} @mcp.tool(annotations=IDEMPOTENT_WRITE) @@ -432,7 +432,7 @@ async def invite( """Add an address to a group you are in: one of your own joins at once; a contact's is invited and joins when they accept.""" you = await me(db, token, from_agent) - status = await mailbox.invite( + status = await messages.invite( db, you, await accounts.resolve(db, group), await accounts.resolve(db, address) ) return {"group": group, "address": address, "status": status} @@ -462,7 +462,7 @@ async def leave( """ you = await me(db, token, from_agent) member = await accounts.resolve(db, address) if address else you - await mailbox.leave(db, you, await accounts.resolve(db, group), member) + await messages.leave(db, you, await accounts.resolve(db, group), member) return {"group": group, "removed": str(member)} @@ -486,7 +486,7 @@ async def add_contact( """ you = await me(db, token, from_agent) other = await accounts.resolve(db, username) - status = await mailbox.add_contact(db, you, other, greeting) + status = await messages.add_contact(db, you, other, greeting) return await accounts.profile(db, other.person) | {"status": status} @@ -511,7 +511,7 @@ async def answer( from any of them settles it. """ you = await me(db, token, from_agent) - status = await mailbox.answer(db, you, request_id, accept) + status = await messages.answer(db, you, request_id, accept) return {"request": request_id, "status": status} @@ -526,7 +526,7 @@ async def remove_contact( """Remove a contact and block them, so neither of you can write to the other. Ask your user first. add_contact undoes it.""" other = await accounts.resolve(db, username) - await mailbox.remove_contact(db, (await me(db, token)).person, other.person) + await messages.remove_contact(db, (await me(db, token)).person, other.person) return {"removed": str(other)} @@ -560,7 +560,7 @@ async def delete_account( you = await me(db, token) # Before the bucket's deletes, so one of them failing can't skip it. signed_out = await revoke_grant(token.token) - await mailbox.delete_account(db, you.person) + await messages.delete_account(db, you.person) return {"deleted": you.username, "signed_out": signed_out} @@ -617,7 +617,7 @@ async def content() -> tuple[str, str, bytes | None]: try: data, content_type = await fetch_public(source) except httpx2.HTTPError as error: - raise mailbox.Refused(f"Could not fetch the file: {error}") from error + raise messages.Refused(f"Could not fetch the file: {error}") from error named = ( name or (file and file.file_name) @@ -633,7 +633,7 @@ async def content() -> tuple[str, str, bytes | None]: ) return named, typed, data - return await mailbox.attach(db, you, content) + return await messages.attach(db, you, content) SHOWN_AS_IMAGES = {"image/png", "image/jpeg", "image/gif", "image/webp"} @@ -650,7 +650,7 @@ async def open_attachment( ) -> Image | EmbeddedResource: """Open an attachment of a message you sent or received, to see what it holds.""" person = (await me(db, token)).person - name, mime, data = await mailbox.open_attachment(db, person, id) + name, mime, data = await messages.open_attachment(db, person, id) if mime in SHOWN_AS_IMAGES: return Image(data=data, format=mime.removeprefix("image/")) uri = f"attachment://{id}/{name}" @@ -823,7 +823,7 @@ class Challenge(BaseModel): async def save(subscription: Subscription) -> None: """Store the subscription so a restarted server resumes its deliveries.""" async with instance.get_db() as db: - await mailbox.save_subscription( + await messages.save_subscription( db, subscription.id, subscription.expires_at, @@ -930,11 +930,11 @@ async def fetch_public(url: str) -> tuple[bytes, str | None]: data = bytearray() async for chunk in response.aiter_bytes(): data += chunk - if len(data) > mailbox.MAX_ATTACHMENT: - raise mailbox.Refused(mailbox.TOO_LARGE) + if len(data) > messages.MAX_ATTACHMENT: + raise messages.Refused(messages.TOO_LARGE) content_type = response.headers.get("content-type", "") return bytes(data), content_type.split(";")[0] or None - raise mailbox.Refused(f"{url} redirects too many times.") + raise messages.Refused(f"{url} redirects too many times.") async def verify(subscription: Subscription) -> None: @@ -1022,7 +1022,7 @@ def methods(self) -> tuple[MethodBinding, ...]: @asynccontextmanager async def lifespan(self): async with instance.get_db() as db: - states = await mailbox.subscriptions(db) + states = await messages.subscriptions(db) for state in states: # A rotated GITHUB_CLIENT_SECRET drops the row; the client resubscribes. with suppress(InvalidToken): @@ -1102,7 +1102,7 @@ async def subscribe( truncated=False, ) async with instance.get_db() as db: - position, truncated = await mailbox.start_position( + position, truncated = await messages.start_position( db, None if params.cursor is None else int(params.cursor), params.max_age_ms, @@ -1154,14 +1154,14 @@ async def unsubscribe( async def pump(self, subscription: Subscription) -> None: """Deliver the subscription's new deliveries in order until it expires.""" - reader = mailbox.Address(subscription.person, subscription.agent) + reader = messages.Address(subscription.person, subscription.agent) try: with instance.waiters.watch(subscription.person) as woken: while datetime.now(UTC) < subscription.expires_at: woken.clear() try: async with instance.get_db() as db: - events = await mailbox.waiting( + events = await messages.waiting( db, reader, subscription.position ) for event in events: diff --git a/server/tests/test_inbox.py b/server/tests/test_inbox.py index 0334f4d..165f2b3 100644 --- a/server/tests/test_inbox.py +++ b/server/tests/test_inbox.py @@ -36,7 +36,7 @@ import accounts import bucket import instance -import mailbox +import messages import panel import server from server import ( @@ -267,8 +267,8 @@ async def remarks(token, db) -> dict[str, str]: async def test_a_remark_is_private_names_one_person_and_outlives_removal(db, public): turing, church = signed_in("turing"), signed_in("church") - await mailbox.record_memberships(db, await account_id(db, "turing"), ["acme"]) - await mailbox.record_memberships(db, await account_id(db, "church"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "turing"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "church"), ["acme"]) await whoami(token=signed_in("kleene"), db=db) await set_remark("Turing", "Prof", token=church, db=db) @@ -290,11 +290,11 @@ async def test_contacts_lists_the_members_of_your_groups_who_are_no_contacts( db, public ): turing, church = signed_in("turing"), signed_in("church") - await mailbox.record_memberships( + await messages.record_memberships( db, await account_id(db, "turing"), ["acme", "recursion"] ) - await mailbox.record_memberships(db, await account_id(db, "church"), ["acme"]) - await mailbox.record_memberships(db, await account_id(db, "kleene"), ["recursion"]) + await messages.record_memberships(db, await account_id(db, "church"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "kleene"), ["recursion"]) group = (await create_group("logic", token=turing, db=db))["group"] await join(db, group, turing, "church", "kleene") @@ -349,7 +349,7 @@ def github_token(): async def test_active_org_member_is_admitted(github_token, monkeypatch): - monkeypatch.setattr(mailbox, "GITHUB_ORG", os.environ["PEERBOX_TEST_ORG"]) + monkeypatch.setattr(messages, "GITHUB_ORG", os.environ["PEERBOX_TEST_ORG"]) # The login only matters without GITHUB_ORG, which records its organisations. token = AccessToken( token=github_token, client_id="test", scopes=[], claims={"login": "member"} @@ -370,8 +370,8 @@ async def test_members_and_plugin_repo_guests_are_admitted( monkeypatch, membership, plugin_repo, admitted ): routes = { - f"/user/memberships/orgs/{mailbox.GITHUB_ORG}": membership, - f"/repos/{mailbox.GITHUB_ORG}/peerbox-plugin": plugin_repo, + f"/user/memberships/orgs/{messages.GITHUB_ORG}": membership, + f"/repos/{messages.GITHUB_ORG}/peerbox-plugin": plugin_repo, } def github(request): @@ -589,7 +589,7 @@ async def test_an_ended_subscription_is_deleted_by_the_next_expiry(db, webhook): "where id = $1", ended, ) - await mailbox.expire(db) + await messages.expire(db) assert [ row["id"] for row in await db.fetch("select id from event_subscriptions") ] == [running] @@ -753,7 +753,7 @@ async def test_owner_address_hands_over_on_leaving(db): await leave(group, "church/bot", token=church, db=db) assert await contacts(token=church, db=db) == {"people": ANY, "groups": []} # nobody is left and nothing was said, so the next expiry deletes the group - await mailbox.expire(db) + await messages.expire(db) assert await db.fetchval("select count(*) from groups") == 0 @@ -777,14 +777,14 @@ async def test_an_emptied_group_keeps_its_messages_until_they_expire(db): await leave(group, token=church, db=db) await leave(group, token=turing, db=db) - await mailbox.expire(db) + await messages.expire(db) with browser(await account_id(db, "church")) as page: [talk] = page.get("/api/conversations").json()["conversations"] assert (talk["key"], talk["name"]) == (group, "compilers") [kept] = page.get(f"/api/conversations/{quote(group)}").json()["messages"] assert kept["text"] == "plan" await db.execute("update messages set created_at = now() - interval '31 days'") - await mailbox.expire(db) + await messages.expire(db) assert await db.fetchval("select count(*) from groups") == 0 @@ -809,7 +809,7 @@ async def test_a_reply_to_a_deleted_message_is_refused(db): await whoami(token=turing, db=db) question = await send("turing", "old question", token=church, db=db) await db.execute("update messages set created_at = now() - interval '31 days'") - await mailbox.expire(db) + await messages.expire(db) with pytest.raises(ToolError, match="No message"): await send("church", "late", reply_to=question["id"], token=turing, db=db) @@ -828,7 +828,7 @@ async def test_expiry_deletes_old_messages_and_keeps_replies_to_them(db): [question["id"], answer["id"]], ) - await mailbox.expire(db) + await messages.expire(db) [thanks] = (await inbox(token=turing, db=db))["messages"] assert (thanks["text"], thanks["reply_to"]) == ("thanks", None) assert await db.fetchval("select count(*) from deliveries") == 1 @@ -837,7 +837,7 @@ async def test_expiry_deletes_old_messages_and_keeps_replies_to_them(db): @pytest.fixture def public(monkeypatch): """The public instance, where only contacts and fellow group members write.""" - monkeypatch.setattr(mailbox, "GITHUB_ORG", None) + monkeypatch.setattr(messages, "GITHUB_ORG", None) async def requests_of(token, db, agent=None) -> list[dict]: @@ -927,7 +927,7 @@ async def test_unanswered_requests_expire(db, public): await whoami(token=turing, db=db) await add_contact("turing", token=signed_in("church"), db=db) await db.execute("update requests set created_at = now() - interval '31 days'") - await mailbox.expire(db) + await messages.expire(db) assert await requests_of(turing, db) == [] @@ -942,8 +942,8 @@ async def test_asking_someone_who_asked_you_makes_contacts_at_once(db, public): async def test_removing_a_contact_blocks_them_despite_a_shared_organisation(db, public): turing, church = signed_in("turing"), signed_in("church") - await mailbox.record_memberships(db, await account_id(db, "turing"), ["acme"]) - await mailbox.record_memberships(db, await account_id(db, "church"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "turing"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "church"), ["acme"]) await send("turing", "hi", token=church, db=db) added = await add_contact("turing", token=church, db=db) assert added["status"] == "already your contact" @@ -961,8 +961,8 @@ async def test_removing_a_contact_blocks_them_despite_a_shared_organisation(db, async def test_an_invited_contact_joins_on_accepting(db, public): turing, church = signed_in("turing"), signed_in("church") - await mailbox.record_memberships(db, await account_id(db, "turing"), ["acme"]) - await mailbox.record_memberships(db, await account_id(db, "church"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "turing"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "church"), ["acme"]) await whoami(token=signed_in("kleene"), db=db) await inbox(agent="bot", token=church, db=db) group = (await create_group("compilers", token=turing, db=db))["group"] @@ -1036,12 +1036,14 @@ async def test_deleting_an_account_wakes_who_saw_its_copies_in_groups_it_left( ): # church shares an organisation with turing only: kleene and post are no # contacts of church's. - await mailbox.record_memberships( + await messages.record_memberships( db, await account_id(db, "turing"), ["lambda", "recursion"] ) - await mailbox.record_memberships(db, await account_id(db, "church"), ["lambda"]) + await messages.record_memberships(db, await account_id(db, "church"), ["lambda"]) for login in ("kleene", "post"): - await mailbox.record_memberships(db, await account_id(db, login), ["recursion"]) + await messages.record_memberships( + db, await account_id(db, login), ["recursion"] + ) turing, church = signed_in("turing"), signed_in("church") group = (await create_group("logic", token=turing, db=db))["group"] await join(db, group, turing, "church", "kleene", "post") @@ -1103,7 +1105,7 @@ def github(request): async def test_a_github_outage_keeps_the_recorded_organisations( db, monkeypatch, public ): - await mailbox.record_memberships(db, await account_id(db, "turing"), ["acme"]) + await messages.record_memberships(db, await account_id(db, "turing"), ["acme"]) down = httpx2.MockTransport(lambda request: httpx2.Response(503)) client = httpx2.AsyncClient monkeypatch.setattr( @@ -1235,7 +1237,7 @@ async def test_an_attachment_another_send_claimed_meanwhile_is_refused(db, monke async def checked_before_either_sent(db, owner, ids): return [(upload["id"], 6)] - monkeypatch.setattr(mailbox, "_sendable", checked_before_either_sent) + monkeypatch.setattr(messages, "_sendable", checked_before_either_sent) await send("turing", "one", attachments=[upload["id"]], token=church, db=db) with pytest.raises(ToolError, match="sent once"): await send("turing", "two", attachments=[upload["id"]], token=church, db=db) @@ -1305,7 +1307,7 @@ async def test_signing_in_to_the_panel_sets_a_session(db, monkeypatch): replies = { "/login/oauth/access_token": {"access_token": os.urandom(8).hex()}, "/user": {"id": 1, "login": "turing", "name": "Alan Turing"}, - f"/user/memberships/orgs/{mailbox.GITHUB_ORG}": {"state": "active"}, + f"/user/memberships/orgs/{messages.GITHUB_ORG}": {"state": "active"}, } client = httpx2.AsyncClient monkeypatch.setattr( @@ -1451,10 +1453,10 @@ async def test_the_panel_shows_each_delivery_without_marking_it_read(db): ["turing", "turing/bot"], 1, ) - messages = page.get("/api/conversations/church").json()["messages"] + transcript = page.get("/api/conversations/church").json()["messages"] shown = [ (m["text"], [(d["to"], d["read_at"] is not None) for d in m["deliveries"]]) - for m in messages + for m in transcript ] assert shown == [ ("review the plan", [("turing/bot", True)]), @@ -1462,7 +1464,7 @@ async def test_the_panel_shows_each_delivery_without_marking_it_read(db): ("lunch?", [("turing", False)]), ] async with httpx2.AsyncClient() as client: - file = messages[0]["attachments"][0] + file = transcript[0]["attachments"][0] assert (await client.get(file["url"])).content == b"step 1" expires = datetime.fromisoformat(file["url_expires_at"]) assert abs(expires - in_an_hour) < timedelta(seconds=5) @@ -1491,8 +1493,8 @@ async def test_two_of_your_agents_talk_in_one_conversation(db): "turing/codex", ["turing/claude-code", "turing/codex"], ) - messages = page.get("/api/conversations/turing/codex").json()["messages"] - assert [m["text"] for m in messages] == ["run the suite", "412 passed"] + transcript = page.get("/api/conversations/turing/codex").json()["messages"] + assert [m["text"] for m in transcript] == ["run the suite", "412 passed"] async def test_a_group_conversation_shows_every_members_messages(db): @@ -1505,15 +1507,15 @@ async def test_a_group_conversation_shows_every_members_messages(db): with browser(await account_id(db, "kleene")) as page: [talk] = page.get("/api/conversations").json()["conversations"] assert (talk["key"], talk["name"], talk["waiting"]) == (group, "compilers", 2) - messages = page.get(f"/api/conversations/{quote(group)}").json()["messages"] + transcript = page.get(f"/api/conversations/{quote(group)}").json()["messages"] earlier = page.get( f"/api/conversations/{quote(group)}?before={agreed['id']}" ).json()["messages"] - assert [(m["from"], m["text"]) for m in messages] == [ + assert [(m["from"], m["text"]) for m in transcript] == [ ("turing", "standup at ten"), ("church", "agreed"), ] - assert [d["to"] for d in messages[0]["deliveries"]] == ["church", "kleene"] + assert [d["to"] for d in transcript[0]["deliveries"]] == ["church", "kleene"] assert [m["text"] for m in earlier] == ["standup at ten"]