From 11203a28c50351a7021120439f54a2a69a9203cc Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 00:05:24 +0100 Subject: [PATCH 1/4] Report the guilds of each shard to the hub --- .coderabbit.yaml | 11 +- pyproject.toml | 7 +- src/librebots/kit/__init__.py | 18 ++- src/librebots/kit/config.py | 2 + src/librebots/kit/guilds.py | 120 +++++++++++++++ src/librebots/kit/hub.py | 2 + src/librebots/kit/i18n.py | 2 + tests/test_config.py | 2 + tests/test_guilds.py | 282 ++++++++++++++++++++++++++++++++++ tests/test_hub.py | 6 +- tests/test_i18n.py | 2 + tests/test_import.py | 2 + uv.lock | 8 +- 13 files changed, 452 insertions(+), 12 deletions(-) create mode 100644 src/librebots/kit/guilds.py create mode 100644 tests/test_guilds.py diff --git a/.coderabbit.yaml b/.coderabbit.yaml index bf496fd..30774cd 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -82,10 +82,13 @@ reviews: The shared toolbox every Libre Bot uses, published as librebots-kit. It is not a framework: nothing may run at import time or in the background unless the bot calls it or loads an extension by name. Public functions and classes are typed and have short docstrings. User-facing text comes from the Fluent catalogs, never from - hard-coded strings, and every key exists in every language. Replies are built with the shared UI helpers so - all bots look the same. A process acts only for the guilds of its own shards; flag code that assumes one - process sees every guild. Only Discord ids are stored or sent to the hub; flag logging or storing message - contents, user names or tokens. Changes to public names need a major version once 1.0 is out. + hard-coded strings, and every key exists in every language. Replies are Components V2 containers built with + risa directly, with no kit helper in between, and look like every other bot's: an accent bar in the bot's + colour (#E24B4A for errors), a ### title, one or two sentences, at most one row of buttons at the bottom, and + set-up replies, errors and confirmations visible to the caller only. A process acts only for the guilds of + its own shards; flag code that assumes one process sees every guild. Only Discord ids are stored or sent to + the hub; flag logging or storing message contents, user names or tokens. Changes to public names need a + major version once 1.0 is out. - path: "src/librebots/kit/ext/**" instructions: >- Lightbulb extensions are thin loaders around the functions next to them. Logic belongs in those functions, diff --git a/pyproject.toml b/pyproject.toml index c9bc51a..f4072bd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ dependencies = [ "hikari>=2.6.0", "hikari-lightbulb>=3.2.7", "hikari-risa>=1.3.0", - "librebots-hub>=0.1.0", + "librebots-hub>=0.1.1", "msgspec>=0.22.0", ] @@ -48,8 +48,13 @@ target-version = "py312" [tool.ruff.lint] select = ["E", "F", "I", "UP", "B"] +[tool.ruff.lint.isort] +required-imports = ["from __future__ import annotations"] + [tool.pyright] pythonVersion = "3.12" typeCheckingMode = "strict" include = ["src/librebots/kit", "tests"] extraPaths = ["src"] +venvPath = "." +venv = ".venv" diff --git a/src/librebots/kit/__init__.py b/src/librebots/kit/__init__.py index a3007d2..fbcafa3 100644 --- a/src/librebots/kit/__init__.py +++ b/src/librebots/kit/__init__.py @@ -1,5 +1,21 @@ +from __future__ import annotations + from librebots.kit.config import Config, ConfigError +from librebots.kit.guilds import GuildLister, GuildReporter, ListedGuild, SyncResult from librebots.kit.hub import Hub, HubError, ShardedApp, connect_hub from librebots.kit.i18n import Catalog, CatalogError -__all__ = ["Catalog", "CatalogError", "Config", "ConfigError", "Hub", "HubError", "ShardedApp", "connect_hub"] +__all__ = [ + "Catalog", + "CatalogError", + "Config", + "ConfigError", + "GuildLister", + "GuildReporter", + "Hub", + "HubError", + "ListedGuild", + "ShardedApp", + "SyncResult", + "connect_hub", +] diff --git a/src/librebots/kit/config.py b/src/librebots/kit/config.py index c27abec..fd7d826 100644 --- a/src/librebots/kit/config.py +++ b/src/librebots/kit/config.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import os from collections.abc import Mapping from pathlib import Path diff --git a/src/librebots/kit/guilds.py b/src/librebots/kit/guilds.py new file mode 100644 index 0000000..829dc70 --- /dev/null +++ b/src/librebots/kit/guilds.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +from collections.abc import AsyncIterable, Awaitable, Callable, Collection +from typing import Protocol + +import grpc.aio +import msgspec +from librebots.hub.v1.guilds_pb2 import GuildJoinedRequest, GuildLeftRequest, SyncedGuild, SyncGuildsRequest +from librebots.hub.v1.shards_pb2 import ShardSet + +from librebots.kit.hub import Hub, HubError + +__all__ = ["GuildLister", "GuildReporter", "ListedGuild", "SyncResult"] + +_LOGGER = logging.getLogger(__name__) + + +class ListedGuild(Protocol): + """A guild as Discord's guild list returns it, such as hikari's `OwnGuild`.""" + + @property + def id(self) -> int: ... + + @property + def approximate_member_count(self) -> int: ... + + +class GuildLister(Protocol): + """Anything that lists the bot's guilds with their member counts, such as hikari's `RESTClient`.""" + + def fetch_my_guilds(self) -> AsyncIterable[ListedGuild]: ... + + +class SyncResult(msgspec.Struct, frozen=True, kw_only=True): + """How many guilds a sync registered and how many it marked as left.""" + + joined: int + left: int + + +class GuildReporter: + """Reports to the hub which guilds the shards of this process are in. + + Call `joined` and `left` for the gateway's join and leave events, and `sync` once the shards have started, after + a shard opens a new session and once a day. A join or leave reported while a sync runs is sent again after it, so + the older guild list the sync read cannot undo it. + """ + + def __init__(self, hub: Hub) -> None: + self._hub = hub + self._sync_lock = asyncio.Lock() + self._during_sync: dict[int, Callable[[], Awaitable[object]]] = {} + + async def joined(self, guild_id: int, *, preferred_locale: str, member_count: int | None) -> str: + """Report that the bot joined a guild and return the guild's language. Raises `HubError` if the hub fails.""" + report = functools.partial(self._report_join, guild_id, preferred_locale, member_count) + self._remember(guild_id, report) + return await report() + + async def left(self, guild_id: int) -> None: + """Report that the bot left or was removed from a guild. Raises `HubError` if the hub fails.""" + report = functools.partial(self._report_leave, guild_id) + self._remember(guild_id, report) + await report() + + async def sync(self, rest: GuildLister, shard_ids: Collection[int], shard_count: int) -> SyncResult: + """Send every guild on these shards, and the hub marks the bot's other guilds on them as left. + + Syncs run one at a time. Raises `HubError` if the hub fails. + """ + shards = frozenset(shard_ids) + async with self._sync_lock: + try: + guilds = [ + SyncedGuild(guild_id=guild.id, member_count=guild.approximate_member_count) + async for guild in rest.fetch_my_guilds() + if (guild.id >> 22) % shard_count in shards + ] + request = SyncGuildsRequest( + shards=ShardSet(shard_ids=sorted(shards), shard_count=shard_count), guilds=guilds + ) + response = await _call("SyncGuilds", self._hub.guilds.SyncGuilds(request)) + except BaseException: + self._during_sync.clear() + raise + await self._report_again() + return SyncResult(joined=response.joined, left=response.left) + + def _remember(self, guild_id: int, report: Callable[[], Awaitable[object]]) -> None: + if self._sync_lock.locked(): + self._during_sync[guild_id] = report + + async def _report_again(self) -> None: + while self._during_sync: + changes, self._during_sync = self._during_sync, {} + for guild_id, report in changes.items(): + try: + await report() + except HubError as exc: + _LOGGER.warning("Could not report guild %s again after a sync: %s", guild_id, exc) + + async def _report_join(self, guild_id: int, preferred_locale: str, member_count: int | None) -> str: + request = GuildJoinedRequest( + guild_id=guild_id, preferred_locale=preferred_locale, member_count=member_count or 0 + ) + response = await _call("GuildJoined", self._hub.guilds.GuildJoined(request)) + return response.settings.locale + + async def _report_leave(self, guild_id: int) -> None: + await _call("GuildLeft", self._hub.guilds.GuildLeft(GuildLeftRequest(guild_id=guild_id))) + + +async def _call[T](method: str, call: Awaitable[T]) -> T: + try: + return await call + except grpc.aio.AioRpcError as exc: + raise HubError(f"{method} failed with {exc.code().name}: {exc.details()}") from exc diff --git a/src/librebots/kit/hub.py b/src/librebots/kit/hub.py index d9fdf5e..c191e0e 100644 --- a/src/librebots/kit/hub.py +++ b/src/librebots/kit/hub.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import asyncio import logging import re diff --git a/src/librebots/kit/i18n.py b/src/librebots/kit/i18n.py index 13b683b..8d14c40 100644 --- a/src/librebots/kit/i18n.py +++ b/src/librebots/kit/i18n.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import logging from collections.abc import Iterable, Mapping from pathlib import Path diff --git a/tests/test_config.py b/tests/test_config.py index 0d80626..8221530 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import os from pathlib import Path diff --git a/tests/test_guilds.py b/tests/test_guilds.py new file mode 100644 index 0000000..59f73ce --- /dev/null +++ b/tests/test_guilds.py @@ -0,0 +1,282 @@ +from __future__ import annotations + +import asyncio +import logging +from collections.abc import AsyncGenerator, AsyncIterator, Awaitable + +import grpc +import grpc.aio +import hikari +import pytest +from librebots.hub.v1 import guilds_pb2, guilds_pb2_grpc +from librebots.hub.v1.guilds_pb2_grpc import GuildServiceStub +from librebots.hub.v1.privacy_pb2_grpc import PrivacyServiceStub +from librebots.hub.v1.stats_pb2_grpc import StatsServiceStub + +from librebots.kit import GuildLister, GuildReporter, Hub, HubError, SyncResult + +type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] + + +def on_shard(shard: int, nth: int = 1, count: int = 4) -> int: + return (count * nth + shard) << 22 + + +class FakeGuilds(guilds_pb2_grpc.GuildServiceServicer): + def __init__(self) -> None: + self.log: list[str] = [] + self.joined: list[guilds_pb2.GuildJoinedRequest] = [] + self.synced: list[guilds_pb2.SyncGuildsRequest] = [] + self.failing: set[str] = set() + + async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: + if name in self.failing: + await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") + + async def GuildJoined( + self, + request: guilds_pb2.GuildJoinedRequest, + context: Context[guilds_pb2.GuildJoinedRequest, guilds_pb2.GuildJoinedResponse], + ) -> guilds_pb2.GuildJoinedResponse: + await self._check("joined", context) + self.log.append(f"joined {request.guild_id}") + self.joined.append(request) + return guilds_pb2.GuildJoinedResponse(settings=guilds_pb2.GuildSettings(guild_id=request.guild_id, locale="de")) + + async def GuildLeft( + self, + request: guilds_pb2.GuildLeftRequest, + context: Context[guilds_pb2.GuildLeftRequest, guilds_pb2.GuildLeftResponse], + ) -> guilds_pb2.GuildLeftResponse: + await self._check("left", context) + self.log.append(f"left {request.guild_id}") + return guilds_pb2.GuildLeftResponse() + + async def SyncGuilds( + self, + request: guilds_pb2.SyncGuildsRequest, + context: Context[guilds_pb2.SyncGuildsRequest, guilds_pb2.SyncGuildsResponse], + ) -> guilds_pb2.SyncGuildsResponse: + await self._check("sync", context) + self.log.append(f"sync {','.join(str(guild.guild_id) for guild in request.guilds)}") + self.synced.append(request) + return guilds_pb2.SyncGuildsResponse(joined=1, left=2) + + +class FakeGuild: + def __init__(self, guild_id: int, members: int = 1) -> None: + self.id = guild_id + self.approximate_member_count = members + + +class FakeRest: + def __init__(self, guilds: list[FakeGuild]) -> None: + self.guilds = guilds + self.listing = asyncio.Event() + self.proceed = asyncio.Event() + self.proceed.set() + + def fetch_my_guilds(self) -> AsyncIterator[FakeGuild]: + return self._guilds() + + async def _guilds(self) -> AsyncIterator[FakeGuild]: + self.listing.set() + await self.proceed.wait() + for guild in self.guilds: + yield guild + + +def rest_client_lists_guilds(rest: hikari.api.RESTClient) -> GuildLister: + return rest + + +@pytest.fixture +async def hub() -> AsyncGenerator[tuple[Hub, FakeGuilds]]: + # The fake answers only the calls guild reporting makes. + fake = FakeGuilds() # pyright: ignore[reportAbstractUsage] + server = grpc.aio.server() + guilds_pb2_grpc.add_GuildServiceServicer_to_server(fake, server) + port = server.add_insecure_port("127.0.0.1:0") + await server.start() + channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}") + try: + yield ( + Hub( + channel=channel, + version="test", + guilds=GuildServiceStub(channel), + privacy=PrivacyServiceStub(channel), + stats=StatsServiceStub(channel), + ), + fake, + ) + finally: + await channel.close() + await server.stop(0) + + +async def test_reports_a_join_and_returns_the_language(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + + locale = await reporter.joined(on_shard(0), preferred_locale="fr", member_count=12) + + assert locale == "de" + request = fake.joined[0] + assert (request.guild_id, request.preferred_locale, request.member_count) == (on_shard(0), "fr", 12) + + +async def test_reports_zero_members_when_the_count_is_unknown(hub: tuple[Hub, FakeGuilds]) -> None: + await GuildReporter(hub[0]).joined(on_shard(0), preferred_locale="en-US", member_count=None) + + assert hub[1].joined[0].member_count == 0 + + +async def test_reports_a_leave(hub: tuple[Hub, FakeGuilds]) -> None: + await GuildReporter(hub[0]).left(on_shard(2)) + + assert hub[1].log == [f"left {on_shard(2)}"] + + +@pytest.mark.parametrize("call", ["joined", "left", "sync"]) +async def test_raises_hub_error_when_the_hub_fails(hub: tuple[Hub, FakeGuilds], call: str) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + fake.failing.add(call) + + with pytest.raises(HubError, match="UNAVAILABLE"): + if call == "joined": + await reporter.joined(on_shard(0), preferred_locale="en-US", member_count=1) + elif call == "left": + await reporter.left(on_shard(0)) + else: + await reporter.sync(FakeRest([]), [0], 1) + + +async def test_syncs_the_guilds_on_the_given_shards(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + rest = FakeRest([FakeGuild(on_shard(shard, nth), 10 * shard + nth) for shard in range(4) for nth in (1, 2)]) + + result = await reporter.sync(rest, [3, 1], 4) + + request = fake.synced[0] + assert list(request.shards.shard_ids) == [1, 3] + assert request.shards.shard_count == 4 + assert {(guild.guild_id, guild.member_count) for guild in request.guilds} == { + (on_shard(1, 1), 11), + (on_shard(1, 2), 12), + (on_shard(3, 1), 31), + (on_shard(3, 2), 32), + } + assert result == SyncResult(joined=1, left=2) + + +async def test_sends_no_language_with_a_sync(hub: tuple[Hub, FakeGuilds]) -> None: + await GuildReporter(hub[0]).sync(FakeRest([FakeGuild(on_shard(0))]), [0], 1) + + assert hub[1].synced[0].guilds[0].preferred_locale == "" + + +async def run_with_paused_listing(reporter: GuildReporter, rest: FakeRest, during: AsyncIterator[None]) -> None: + rest.proceed.clear() + sync = asyncio.create_task(reporter.sync(rest, [0], 1)) + async with asyncio.timeout(5): + await rest.listing.wait() + async for _ in during: + pass + rest.proceed.set() + await sync + + +async def test_reports_a_join_again_after_a_sync_that_missed_it(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + old, new = on_shard(0, 1), on_shard(0, 2) + + async def join() -> AsyncIterator[None]: + await reporter.joined(new, preferred_locale="en-US", member_count=3) + yield + + await run_with_paused_listing(reporter, FakeRest([FakeGuild(old)]), join()) + + assert fake.log == [f"joined {new}", f"sync {old}", f"joined {new}"] + + +async def test_reports_a_leave_again_after_a_sync_that_still_listed_the_guild(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + guild = on_shard(0) + + async def leave() -> AsyncIterator[None]: + await reporter.left(guild) + yield + + await run_with_paused_listing(reporter, FakeRest([FakeGuild(guild)]), leave()) + + assert fake.log == [f"left {guild}", f"sync {guild}", f"left {guild}"] + + +async def test_reports_only_the_latest_change_of_a_guild_again(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + guild = on_shard(0) + + async def join_and_leave() -> AsyncIterator[None]: + await reporter.joined(guild, preferred_locale="en-US", member_count=3) + await reporter.left(guild) + yield + + await run_with_paused_listing(reporter, FakeRest([]), join_and_leave()) + + assert fake.log == [f"joined {guild}", f"left {guild}", "sync ", f"left {guild}"] + + +async def test_reports_changes_before_a_sync_only_once(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + guild = on_shard(0) + + await reporter.joined(guild, preferred_locale="en-US", member_count=3) + await reporter.sync(FakeRest([FakeGuild(guild)]), [0], 1) + + assert fake.log == [f"joined {guild}", f"sync {guild}"] + + +async def test_logs_a_repeated_report_that_fails_and_keeps_the_sync_result( + hub: tuple[Hub, FakeGuilds], caplog: pytest.LogCaptureFixture +) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + guild = on_shard(0) + result: list[SyncResult] = [] + + async def join_then_break_the_hub() -> AsyncIterator[None]: + await reporter.joined(guild, preferred_locale="en-US", member_count=3) + fake.failing.add("joined") + yield + + rest = FakeRest([]) + rest.proceed.clear() + sync = asyncio.create_task(reporter.sync(rest, [0], 1)) + with caplog.at_level(logging.WARNING, logger="librebots.kit"): + async with asyncio.timeout(5): + await rest.listing.wait() + async for _ in join_then_break_the_hub(): + pass + rest.proceed.set() + result.append(await sync) + + assert result == [SyncResult(joined=1, left=2)] + assert str(guild) in caplog.text + + +async def test_runs_one_sync_at_a_time(hub: tuple[Hub, FakeGuilds]) -> None: + reporter = GuildReporter(hub[0]) + first, second = FakeRest([]), FakeRest([]) + first.proceed.clear() + + async with asyncio.timeout(5): + running = asyncio.create_task(reporter.sync(first, [0], 1)) + await first.listing.wait() + waiting = asyncio.create_task(reporter.sync(second, [0], 1)) + for _ in range(10): + await asyncio.sleep(0) + started_early = second.listing.is_set() + first.proceed.set() + await asyncio.gather(running, waiting) + + assert not started_early + assert second.listing.is_set() diff --git a/tests/test_hub.py b/tests/test_hub.py index 2797e99..7c4e09c 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -1,6 +1,8 @@ +from __future__ import annotations + import logging import socket -from collections.abc import AsyncGenerator, Mapping +from collections.abc import AsyncGenerator, Awaitable, Mapping from importlib.metadata import version from pathlib import Path @@ -25,7 +27,7 @@ def __init__(self) -> None: async def GetInfo( self, request: info_pb2.GetInfoRequest, - context: grpc.aio.ServicerContext[info_pb2.GetInfoRequest, info_pb2.GetInfoResponse], + context: grpc.aio.ServicerContext[info_pb2.GetInfoRequest, Awaitable[info_pb2.GetInfoResponse]], ) -> info_pb2.GetInfoResponse: self.seen = dict(context.invocation_metadata() or ()) if self.seen.get("authorization") != f"Bearer {TOKEN}": diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 52242e6..efe7499 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import logging from pathlib import Path diff --git a/tests/test_import.py b/tests/test_import.py index 77921d0..ffd3a6e 100644 --- a/tests/test_import.py +++ b/tests/test_import.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import importlib diff --git a/uv.lock b/uv.lock index fd85d3f..12ce01b 100644 --- a/uv.lock +++ b/uv.lock @@ -468,16 +468,16 @@ wheels = [ [[package]] name = "librebots-hub" -version = "0.1.0" +version = "0.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "googleapis-common-protos" }, { name = "grpcio" }, { name = "protobuf" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c3/9c/282654051d483b6e050f0171863c1b05319cab2b7d087a977110455cd122/librebots_hub-0.1.0.tar.gz", hash = "sha256:fd3416ff7a12b1f2db2af9c2e712ca271cd9d709b392524de9af5f67d025efb7", size = 33674, upload-time = "2026-11-25T20:44:58.049Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/54/76d4797c36730d1c0cae79b1935e42c439fdadf3399f2ab01fc82402ec12/librebots_hub-0.1.1.tar.gz", hash = "sha256:d10d672b1023a9b28e22c240b8f7c9d481d3c01e02df583d37114248fc207c85", size = 33009, upload-time = "2026-11-26T23:02:40.512Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/56/8f/4ad41b90638dccf7fdf1bbbdf59e5ccebf2c03126505180ed01794bad832/librebots_hub-0.1.0-py3-none-any.whl", hash = "sha256:86c192b08c5f075a6275aa967e6e85a6963b3129368581c9ebe91e2f9743ca24", size = 30210, upload-time = "2026-11-25T20:44:56.93Z" }, + { url = "https://files.pythonhosted.org/packages/d3/19/dd34467558c434110c9255007d5bc4613555c9c5267054d3447c85b944d6/librebots_hub-0.1.1-py3-none-any.whl", hash = "sha256:4f54791c53d2223e319256db34c3f99337919fd380f8d361f83550b578b01677", size = 28867, upload-time = "2026-11-26T23:02:39.592Z" }, ] [[package]] @@ -508,7 +508,7 @@ requires-dist = [ { name = "hikari", specifier = ">=2.6.0" }, { name = "hikari-lightbulb", specifier = ">=3.2.7" }, { name = "hikari-risa", specifier = ">=1.3.0" }, - { name = "librebots-hub", specifier = ">=0.1.0" }, + { name = "librebots-hub", specifier = ">=0.1.1" }, { name = "msgspec", specifier = ">=0.22.0" }, ] From 83a92e843cf8638440b68b5375b885a1ef50f831 Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 09:16:15 +0100 Subject: [PATCH 2/4] Bound the hub calls and keep unsent guild changes for the next sync --- src/librebots/kit/guilds.py | 56 +++++++++++------------ tests/test_guilds.py | 91 ++++++++++++++++++++++++++++++++++--- 2 files changed, 113 insertions(+), 34 deletions(-) diff --git a/src/librebots/kit/guilds.py b/src/librebots/kit/guilds.py index 829dc70..5ef2b33 100644 --- a/src/librebots/kit/guilds.py +++ b/src/librebots/kit/guilds.py @@ -45,14 +45,16 @@ class GuildReporter: """Reports to the hub which guilds the shards of this process are in. Call `joined` and `left` for the gateway's join and leave events, and `sync` once the shards have started, after - a shard opens a new session and once a day. A join or leave reported while a sync runs is sent again after it, so - the older guild list the sync read cannot undo it. + a shard opens a new session and once a day. A join or leave reported while a sync runs is sent again after the + next sync that succeeds, so the older guild list a sync read cannot undo it. Every call to the hub gives up after + `timeout` seconds. """ - def __init__(self, hub: Hub) -> None: + def __init__(self, hub: Hub, *, timeout: float = 30) -> None: self._hub = hub + self._timeout = timeout self._sync_lock = asyncio.Lock() - self._during_sync: dict[int, Callable[[], Awaitable[object]]] = {} + self._pending: dict[int, Callable[[], Awaitable[object]]] = {} async def joined(self, guild_id: int, *, preferred_locale: str, member_count: int | None) -> str: """Report that the bot joined a guild and return the guild's language. Raises `HubError` if the hub fails.""" @@ -73,44 +75,42 @@ async def sync(self, rest: GuildLister, shard_ids: Collection[int], shard_count: """ shards = frozenset(shard_ids) async with self._sync_lock: - try: - guilds = [ - SyncedGuild(guild_id=guild.id, member_count=guild.approximate_member_count) - async for guild in rest.fetch_my_guilds() - if (guild.id >> 22) % shard_count in shards - ] - request = SyncGuildsRequest( - shards=ShardSet(shard_ids=sorted(shards), shard_count=shard_count), guilds=guilds - ) - response = await _call("SyncGuilds", self._hub.guilds.SyncGuilds(request)) - except BaseException: - self._during_sync.clear() - raise + guilds = [ + SyncedGuild(guild_id=guild.id, member_count=guild.approximate_member_count) + async for guild in rest.fetch_my_guilds() + if (guild.id >> 22) % shard_count in shards + ] + request = SyncGuildsRequest( + shards=ShardSet(shard_ids=sorted(shards), shard_count=shard_count), guilds=guilds + ) + response = await _call("SyncGuilds", self._hub.guilds.SyncGuilds(request, timeout=self._timeout)) await self._report_again() return SyncResult(joined=response.joined, left=response.left) def _remember(self, guild_id: int, report: Callable[[], Awaitable[object]]) -> None: - if self._sync_lock.locked(): - self._during_sync[guild_id] = report + if self._sync_lock.locked() or guild_id in self._pending: + self._pending[guild_id] = report async def _report_again(self) -> None: - while self._during_sync: - changes, self._during_sync = self._during_sync, {} - for guild_id, report in changes.items(): - try: - await report() - except HubError as exc: - _LOGGER.warning("Could not report guild %s again after a sync: %s", guild_id, exc) + while self._pending: + guild_id, report = next(iter(self._pending.items())) + try: + await report() + except HubError as exc: + _LOGGER.warning("Could not report guild %s again after a sync: %s", guild_id, exc) + if self._pending.get(guild_id) is report: + del self._pending[guild_id] async def _report_join(self, guild_id: int, preferred_locale: str, member_count: int | None) -> str: request = GuildJoinedRequest( guild_id=guild_id, preferred_locale=preferred_locale, member_count=member_count or 0 ) - response = await _call("GuildJoined", self._hub.guilds.GuildJoined(request)) + response = await _call("GuildJoined", self._hub.guilds.GuildJoined(request, timeout=self._timeout)) return response.settings.locale async def _report_leave(self, guild_id: int) -> None: - await _call("GuildLeft", self._hub.guilds.GuildLeft(GuildLeftRequest(guild_id=guild_id))) + request = GuildLeftRequest(guild_id=guild_id) + await _call("GuildLeft", self._hub.guilds.GuildLeft(request, timeout=self._timeout)) async def _call[T](method: str, call: Awaitable[T]) -> T: diff --git a/tests/test_guilds.py b/tests/test_guilds.py index 59f73ce..1e5e1a8 100644 --- a/tests/test_guilds.py +++ b/tests/test_guilds.py @@ -28,10 +28,16 @@ def __init__(self) -> None: self.joined: list[guilds_pb2.GuildJoinedRequest] = [] self.synced: list[guilds_pb2.SyncGuildsRequest] = [] self.failing: set[str] = set() + self.stalled: set[str] = set() + self.stall_started = asyncio.Event() + self._never = asyncio.Event() async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: if name in self.failing: await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") + if name in self.stalled: + self.stall_started.set() + await self._never.wait() async def GuildJoined( self, @@ -264,19 +270,92 @@ async def join_then_break_the_hub() -> AsyncIterator[None]: async def test_runs_one_sync_at_a_time(hub: tuple[Hub, FakeGuilds]) -> None: - reporter = GuildReporter(hub[0]) - first, second = FakeRest([]), FakeRest([]) + reporter, fake = GuildReporter(hub[0]), hub[1] + first, second = FakeRest([FakeGuild(on_shard(0, 1))]), FakeRest([FakeGuild(on_shard(0, 2))]) first.proceed.clear() + attempted = asyncio.Event() + + async def second_sync() -> SyncResult: + attempted.set() + return await reporter.sync(second, [0], 1) async with asyncio.timeout(5): running = asyncio.create_task(reporter.sync(first, [0], 1)) await first.listing.wait() - waiting = asyncio.create_task(reporter.sync(second, [0], 1)) - for _ in range(10): - await asyncio.sleep(0) + waiting = asyncio.create_task(second_sync()) + await attempted.wait() started_early = second.listing.is_set() first.proceed.set() await asyncio.gather(running, waiting) assert not started_early - assert second.listing.is_set() + assert fake.log == [f"sync {on_shard(0, 1)}", f"sync {on_shard(0, 2)}"] + + +async def test_gives_up_on_a_hub_that_does_not_answer(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0], timeout=0.2), hub[1] + fake.stalled.add("sync") + + with pytest.raises(HubError, match="DEADLINE_EXCEEDED"): + await reporter.sync(FakeRest([]), [0], 1) + + fake.stalled.clear() + assert await reporter.sync(FakeRest([]), [0], 1) == SyncResult(joined=1, left=2) + + +async def test_keeps_the_changes_of_a_failed_sync_for_the_next_one(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + guild = on_shard(0) + + async def join_then_break_the_sync() -> AsyncIterator[None]: + await reporter.joined(guild, preferred_locale="en-US", member_count=3) + fake.failing.add("sync") + yield + + with pytest.raises(HubError): + await run_with_paused_listing(reporter, FakeRest([]), join_then_break_the_sync()) + fake.failing.clear() + await reporter.sync(FakeRest([]), [0], 1) + + assert fake.log == [f"joined {guild}", "sync ", f"joined {guild}"] + + +async def test_keeps_only_the_latest_change_after_a_failed_sync(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + guild = on_shard(0) + + async def join_then_break_the_sync() -> AsyncIterator[None]: + await reporter.joined(guild, preferred_locale="en-US", member_count=3) + fake.failing.add("sync") + yield + + with pytest.raises(HubError): + await run_with_paused_listing(reporter, FakeRest([]), join_then_break_the_sync()) + fake.failing.clear() + await reporter.left(guild) + await reporter.sync(FakeRest([]), [0], 1) + + assert fake.log == [f"joined {guild}", f"left {guild}", "sync ", f"left {guild}"] + + +async def test_keeps_the_changes_a_cancelled_sync_did_not_send_again(hub: tuple[Hub, FakeGuilds]) -> None: + reporter, fake = GuildReporter(hub[0]), hub[1] + first, second = on_shard(0, 1), on_shard(0, 2) + rest = FakeRest([FakeGuild(first), FakeGuild(second)]) + rest.proceed.clear() + + async with asyncio.timeout(5): + sync = asyncio.create_task(reporter.sync(rest, [0], 1)) + await rest.listing.wait() + await reporter.left(first) + await reporter.left(second) + fake.stalled.add("left") + rest.proceed.set() + await fake.stall_started.wait() + sync.cancel() + with pytest.raises(asyncio.CancelledError): + await sync + fake.stalled.clear() + await reporter.sync(FakeRest([]), [0], 1) + + assert fake.log[-3:] == ["sync ", f"left {first}", f"left {second}"] From eef4c851f7890e6e198f0a5ecf51b4ddb8acb1fc Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 09:21:17 +0100 Subject: [PATCH 3/4] Take hikari's types instead of own protocols --- src/librebots/kit/__init__.py | 7 +-- src/librebots/kit/guilds.py | 24 ++------ src/librebots/kit/hub.py | 22 +++----- tests/test_guilds.py | 102 +++++++++++++++++----------------- tests/test_hub.py | 18 +++--- 5 files changed, 72 insertions(+), 101 deletions(-) diff --git a/src/librebots/kit/__init__.py b/src/librebots/kit/__init__.py index fbcafa3..65159dd 100644 --- a/src/librebots/kit/__init__.py +++ b/src/librebots/kit/__init__.py @@ -1,8 +1,8 @@ from __future__ import annotations from librebots.kit.config import Config, ConfigError -from librebots.kit.guilds import GuildLister, GuildReporter, ListedGuild, SyncResult -from librebots.kit.hub import Hub, HubError, ShardedApp, connect_hub +from librebots.kit.guilds import GuildReporter, SyncResult +from librebots.kit.hub import Hub, HubError, connect_hub from librebots.kit.i18n import Catalog, CatalogError __all__ = [ @@ -10,12 +10,9 @@ "CatalogError", "Config", "ConfigError", - "GuildLister", "GuildReporter", "Hub", "HubError", - "ListedGuild", - "ShardedApp", "SyncResult", "connect_hub", ] diff --git a/src/librebots/kit/guilds.py b/src/librebots/kit/guilds.py index 5ef2b33..78ac8b5 100644 --- a/src/librebots/kit/guilds.py +++ b/src/librebots/kit/guilds.py @@ -3,37 +3,21 @@ import asyncio import functools import logging -from collections.abc import AsyncIterable, Awaitable, Callable, Collection -from typing import Protocol +from collections.abc import Awaitable, Callable, Collection import grpc.aio +import hikari import msgspec from librebots.hub.v1.guilds_pb2 import GuildJoinedRequest, GuildLeftRequest, SyncedGuild, SyncGuildsRequest from librebots.hub.v1.shards_pb2 import ShardSet from librebots.kit.hub import Hub, HubError -__all__ = ["GuildLister", "GuildReporter", "ListedGuild", "SyncResult"] +__all__ = ["GuildReporter", "SyncResult"] _LOGGER = logging.getLogger(__name__) -class ListedGuild(Protocol): - """A guild as Discord's guild list returns it, such as hikari's `OwnGuild`.""" - - @property - def id(self) -> int: ... - - @property - def approximate_member_count(self) -> int: ... - - -class GuildLister(Protocol): - """Anything that lists the bot's guilds with their member counts, such as hikari's `RESTClient`.""" - - def fetch_my_guilds(self) -> AsyncIterable[ListedGuild]: ... - - class SyncResult(msgspec.Struct, frozen=True, kw_only=True): """How many guilds a sync registered and how many it marked as left.""" @@ -68,7 +52,7 @@ async def left(self, guild_id: int) -> None: self._remember(guild_id, report) await report() - async def sync(self, rest: GuildLister, shard_ids: Collection[int], shard_count: int) -> SyncResult: + async def sync(self, rest: hikari.api.RESTClient, shard_ids: Collection[int], shard_count: int) -> SyncResult: """Send every guild on these shards, and the hub marks the bot's other guilds on them as left. Syncs run one at a time. Raises `HubError` if the hub fails. diff --git a/src/librebots/kit/hub.py b/src/librebots/kit/hub.py index c191e0e..59c6162 100644 --- a/src/librebots/kit/hub.py +++ b/src/librebots/kit/hub.py @@ -3,13 +3,13 @@ import asyncio import logging import re -from collections.abc import Callable, Mapping, Sequence +from collections.abc import Callable, Sequence from importlib.metadata import version as installed_version from pathlib import Path -from typing import Protocol import grpc import grpc.aio +import hikari import msgspec from librebots.hub import connect from librebots.hub.v1.guilds_pb2_grpc import GuildServiceStub @@ -20,7 +20,7 @@ from librebots.kit.config import Config -__all__ = ["Hub", "HubError", "ShardedApp", "connect_hub"] +__all__ = ["Hub", "HubError", "connect_hub"] _LOGGER = logging.getLogger(__name__) _VERSION = re.compile(r"(\d+)\.(\d+)\.\d+") @@ -30,16 +30,6 @@ class HubError(Exception): """The hub could not be reached, rejected the bot or is too old for it.""" -class ShardedApp(Protocol): - """Anything with hikari's `shards` and `shard_count`, such as a `hikari.GatewayBot`.""" - - @property - def shards(self) -> Mapping[int, object]: ... - - @property - def shard_count(self) -> int: ... - - class Hub(msgspec.Struct, frozen=True, kw_only=True): """A connection to the hub with the stubs of the services every bot uses. @@ -57,7 +47,7 @@ async def close(self) -> None: await self.channel.close() -async def connect_hub(config: Config, *, shards: ShardedApp | None = None, timeout: float = 60) -> Hub: +async def connect_hub(config: Config, *, shards: hikari.ShardAware | None = None, timeout: float = 60) -> Hub: """Connect to the hub and return once it has answered. Every call names the shards of this process: those `shards` runs at that moment, or else `SHARD_IDS` and @@ -96,7 +86,9 @@ async def _read_ca_file(path: str | None) -> bytes | None: raise HubError(f"Cannot read HUB_CA_FILE: {exc}") from exc -def _shard_label(config: Config, app: ShardedApp | None) -> Callable[[], tuple[Sequence[int], int] | None] | None: +def _shard_label( + config: Config, app: hikari.ShardAware | None +) -> Callable[[], tuple[Sequence[int], int] | None] | None: if app is not None: def label() -> tuple[Sequence[int], int] | None: diff --git a/tests/test_guilds.py b/tests/test_guilds.py index 1e5e1a8..352f81a 100644 --- a/tests/test_guilds.py +++ b/tests/test_guilds.py @@ -3,6 +3,7 @@ import asyncio import logging from collections.abc import AsyncGenerator, AsyncIterator, Awaitable +from unittest.mock import create_autospec import grpc import grpc.aio @@ -13,7 +14,7 @@ from librebots.hub.v1.privacy_pb2_grpc import PrivacyServiceStub from librebots.hub.v1.stats_pb2_grpc import StatsServiceStub -from librebots.kit import GuildLister, GuildReporter, Hub, HubError, SyncResult +from librebots.kit import GuildReporter, Hub, HubError, SyncResult type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] @@ -69,33 +70,30 @@ async def SyncGuilds( return guilds_pb2.SyncGuildsResponse(joined=1, left=2) -class FakeGuild: - def __init__(self, guild_id: int, members: int = 1) -> None: - self.id = guild_id - self.approximate_member_count = members +def own_guild(guild_id: int, members: int = 1) -> hikari.OwnGuild: + guild = create_autospec(hikari.OwnGuild, instance=True) + guild.id = hikari.Snowflake(guild_id) + guild.approximate_member_count = members + return guild -class FakeRest: - def __init__(self, guilds: list[FakeGuild]) -> None: +class Listing: + def __init__(self, guilds: list[hikari.OwnGuild]) -> None: self.guilds = guilds - self.listing = asyncio.Event() + self.started = asyncio.Event() self.proceed = asyncio.Event() self.proceed.set() + rest = create_autospec(hikari.api.RESTClient, instance=True) + rest.fetch_my_guilds.side_effect = self._guilds + self.rest: hikari.api.RESTClient = rest - def fetch_my_guilds(self) -> AsyncIterator[FakeGuild]: - return self._guilds() - - async def _guilds(self) -> AsyncIterator[FakeGuild]: - self.listing.set() + async def _guilds(self) -> AsyncIterator[hikari.OwnGuild]: + self.started.set() await self.proceed.wait() for guild in self.guilds: yield guild -def rest_client_lists_guilds(rest: hikari.api.RESTClient) -> GuildLister: - return rest - - @pytest.fixture async def hub() -> AsyncGenerator[tuple[Hub, FakeGuilds]]: # The fake answers only the calls guild reporting makes. @@ -154,14 +152,14 @@ async def test_raises_hub_error_when_the_hub_fails(hub: tuple[Hub, FakeGuilds], elif call == "left": await reporter.left(on_shard(0)) else: - await reporter.sync(FakeRest([]), [0], 1) + await reporter.sync(Listing([]).rest, [0], 1) async def test_syncs_the_guilds_on_the_given_shards(hub: tuple[Hub, FakeGuilds]) -> None: reporter, fake = GuildReporter(hub[0]), hub[1] - rest = FakeRest([FakeGuild(on_shard(shard, nth), 10 * shard + nth) for shard in range(4) for nth in (1, 2)]) + listing = Listing([own_guild(on_shard(shard, nth), 10 * shard + nth) for shard in range(4) for nth in (1, 2)]) - result = await reporter.sync(rest, [3, 1], 4) + result = await reporter.sync(listing.rest, [3, 1], 4) request = fake.synced[0] assert list(request.shards.shard_ids) == [1, 3] @@ -176,19 +174,19 @@ async def test_syncs_the_guilds_on_the_given_shards(hub: tuple[Hub, FakeGuilds]) async def test_sends_no_language_with_a_sync(hub: tuple[Hub, FakeGuilds]) -> None: - await GuildReporter(hub[0]).sync(FakeRest([FakeGuild(on_shard(0))]), [0], 1) + await GuildReporter(hub[0]).sync(Listing([own_guild(on_shard(0))]).rest, [0], 1) assert hub[1].synced[0].guilds[0].preferred_locale == "" -async def run_with_paused_listing(reporter: GuildReporter, rest: FakeRest, during: AsyncIterator[None]) -> None: - rest.proceed.clear() - sync = asyncio.create_task(reporter.sync(rest, [0], 1)) +async def run_with_paused_listing(reporter: GuildReporter, listing: Listing, during: AsyncIterator[None]) -> None: + listing.proceed.clear() + sync = asyncio.create_task(reporter.sync(listing.rest, [0], 1)) async with asyncio.timeout(5): - await rest.listing.wait() + await listing.started.wait() async for _ in during: pass - rest.proceed.set() + listing.proceed.set() await sync @@ -200,7 +198,7 @@ async def join() -> AsyncIterator[None]: await reporter.joined(new, preferred_locale="en-US", member_count=3) yield - await run_with_paused_listing(reporter, FakeRest([FakeGuild(old)]), join()) + await run_with_paused_listing(reporter, Listing([own_guild(old)]), join()) assert fake.log == [f"joined {new}", f"sync {old}", f"joined {new}"] @@ -213,7 +211,7 @@ async def leave() -> AsyncIterator[None]: await reporter.left(guild) yield - await run_with_paused_listing(reporter, FakeRest([FakeGuild(guild)]), leave()) + await run_with_paused_listing(reporter, Listing([own_guild(guild)]), leave()) assert fake.log == [f"left {guild}", f"sync {guild}", f"left {guild}"] @@ -227,7 +225,7 @@ async def join_and_leave() -> AsyncIterator[None]: await reporter.left(guild) yield - await run_with_paused_listing(reporter, FakeRest([]), join_and_leave()) + await run_with_paused_listing(reporter, Listing([]), join_and_leave()) assert fake.log == [f"joined {guild}", f"left {guild}", "sync ", f"left {guild}"] @@ -237,7 +235,7 @@ async def test_reports_changes_before_a_sync_only_once(hub: tuple[Hub, FakeGuild guild = on_shard(0) await reporter.joined(guild, preferred_locale="en-US", member_count=3) - await reporter.sync(FakeRest([FakeGuild(guild)]), [0], 1) + await reporter.sync(Listing([own_guild(guild)]).rest, [0], 1) assert fake.log == [f"joined {guild}", f"sync {guild}"] @@ -254,15 +252,15 @@ async def join_then_break_the_hub() -> AsyncIterator[None]: fake.failing.add("joined") yield - rest = FakeRest([]) - rest.proceed.clear() - sync = asyncio.create_task(reporter.sync(rest, [0], 1)) + listing = Listing([]) + listing.proceed.clear() + sync = asyncio.create_task(reporter.sync(listing.rest, [0], 1)) with caplog.at_level(logging.WARNING, logger="librebots.kit"): async with asyncio.timeout(5): - await rest.listing.wait() + await listing.started.wait() async for _ in join_then_break_the_hub(): pass - rest.proceed.set() + listing.proceed.set() result.append(await sync) assert result == [SyncResult(joined=1, left=2)] @@ -271,20 +269,20 @@ async def join_then_break_the_hub() -> AsyncIterator[None]: async def test_runs_one_sync_at_a_time(hub: tuple[Hub, FakeGuilds]) -> None: reporter, fake = GuildReporter(hub[0]), hub[1] - first, second = FakeRest([FakeGuild(on_shard(0, 1))]), FakeRest([FakeGuild(on_shard(0, 2))]) + first, second = Listing([own_guild(on_shard(0, 1))]), Listing([own_guild(on_shard(0, 2))]) first.proceed.clear() attempted = asyncio.Event() async def second_sync() -> SyncResult: attempted.set() - return await reporter.sync(second, [0], 1) + return await reporter.sync(second.rest, [0], 1) async with asyncio.timeout(5): - running = asyncio.create_task(reporter.sync(first, [0], 1)) - await first.listing.wait() + running = asyncio.create_task(reporter.sync(first.rest, [0], 1)) + await first.started.wait() waiting = asyncio.create_task(second_sync()) await attempted.wait() - started_early = second.listing.is_set() + started_early = second.started.is_set() first.proceed.set() await asyncio.gather(running, waiting) @@ -297,10 +295,10 @@ async def test_gives_up_on_a_hub_that_does_not_answer(hub: tuple[Hub, FakeGuilds fake.stalled.add("sync") with pytest.raises(HubError, match="DEADLINE_EXCEEDED"): - await reporter.sync(FakeRest([]), [0], 1) + await reporter.sync(Listing([]).rest, [0], 1) fake.stalled.clear() - assert await reporter.sync(FakeRest([]), [0], 1) == SyncResult(joined=1, left=2) + assert await reporter.sync(Listing([]).rest, [0], 1) == SyncResult(joined=1, left=2) async def test_keeps_the_changes_of_a_failed_sync_for_the_next_one(hub: tuple[Hub, FakeGuilds]) -> None: @@ -313,9 +311,9 @@ async def join_then_break_the_sync() -> AsyncIterator[None]: yield with pytest.raises(HubError): - await run_with_paused_listing(reporter, FakeRest([]), join_then_break_the_sync()) + await run_with_paused_listing(reporter, Listing([]), join_then_break_the_sync()) fake.failing.clear() - await reporter.sync(FakeRest([]), [0], 1) + await reporter.sync(Listing([]).rest, [0], 1) assert fake.log == [f"joined {guild}", "sync ", f"joined {guild}"] @@ -330,10 +328,10 @@ async def join_then_break_the_sync() -> AsyncIterator[None]: yield with pytest.raises(HubError): - await run_with_paused_listing(reporter, FakeRest([]), join_then_break_the_sync()) + await run_with_paused_listing(reporter, Listing([]), join_then_break_the_sync()) fake.failing.clear() await reporter.left(guild) - await reporter.sync(FakeRest([]), [0], 1) + await reporter.sync(Listing([]).rest, [0], 1) assert fake.log == [f"joined {guild}", f"left {guild}", "sync ", f"left {guild}"] @@ -341,21 +339,21 @@ async def join_then_break_the_sync() -> AsyncIterator[None]: async def test_keeps_the_changes_a_cancelled_sync_did_not_send_again(hub: tuple[Hub, FakeGuilds]) -> None: reporter, fake = GuildReporter(hub[0]), hub[1] first, second = on_shard(0, 1), on_shard(0, 2) - rest = FakeRest([FakeGuild(first), FakeGuild(second)]) - rest.proceed.clear() + listing = Listing([own_guild(first), own_guild(second)]) + listing.proceed.clear() async with asyncio.timeout(5): - sync = asyncio.create_task(reporter.sync(rest, [0], 1)) - await rest.listing.wait() + sync = asyncio.create_task(reporter.sync(listing.rest, [0], 1)) + await listing.started.wait() await reporter.left(first) await reporter.left(second) fake.stalled.add("left") - rest.proceed.set() + listing.proceed.set() await fake.stall_started.wait() sync.cancel() with pytest.raises(asyncio.CancelledError): await sync fake.stalled.clear() - await reporter.sync(FakeRest([]), [0], 1) + await reporter.sync(Listing([]).rest, [0], 1) assert fake.log[-3:] == ["sync ", f"left {first}", f"left {second}"] diff --git a/tests/test_hub.py b/tests/test_hub.py index 7c4e09c..e880d27 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -2,9 +2,10 @@ import logging import socket -from collections.abc import AsyncGenerator, Awaitable, Mapping +from collections.abc import AsyncGenerator, Awaitable from importlib.metadata import version from pathlib import Path +from unittest.mock import create_autospec import grpc import grpc.aio @@ -35,10 +36,11 @@ async def GetInfo( return info_pb2.GetInfoResponse(version=self.version) -class FakeApp: - def __init__(self, shards: Mapping[int, object], shard_count: int) -> None: - self.shards = shards - self.shard_count = shard_count +def sharded_app(shard_ids: list[int], shard_count: int) -> hikari.ShardAware: + app = create_autospec(hikari.GatewayBot, instance=True) + app.shards = {shard_id: create_autospec(hikari.api.GatewayShard, instance=True) for shard_id in shard_ids} + app.shard_count = shard_count + return app @pytest.fixture @@ -96,7 +98,7 @@ async def test_close_shuts_the_channel_down(fake_hub: tuple[str, FakeInfo]) -> N async def test_sends_the_shard_label_of_the_app(fake_hub: tuple[str, FakeInfo]) -> None: address, info = fake_hub - hub = await connect_hub(config(address), shards=FakeApp({2: object(), 0: object()}, 4)) + hub = await connect_hub(config(address), shards=sharded_app([2, 0], 4)) await hub.close() assert info.seen["libre-shards"] == "0,2/4" @@ -114,9 +116,7 @@ async def test_sends_the_configured_shards_without_an_app(fake_hub: tuple[str, F async def test_prefers_the_shards_of_the_app_to_the_configured_ones(fake_hub: tuple[str, FakeInfo]) -> None: address, info = fake_hub - hub = await connect_hub( - config(address, SHARD_IDS="2", SHARD_COUNT="4"), shards=FakeApp({0: object(), 1: object()}, 2) - ) + hub = await connect_hub(config(address, SHARD_IDS="2", SHARD_COUNT="4"), shards=sharded_app([0, 1], 2)) await hub.close() assert info.seen["libre-shards"] == "0,1/2" From 8deb25e054422fdbad1f09edf4c58a77442c6873 Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 09:28:08 +0100 Subject: [PATCH 4/4] Keep a guild change whose repeat failed for the next sync --- src/librebots/kit/guilds.py | 9 +++++++-- tests/test_guilds.py | 34 +++++++++++++++++----------------- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/src/librebots/kit/guilds.py b/src/librebots/kit/guilds.py index 78ac8b5..7d2496c 100644 --- a/src/librebots/kit/guilds.py +++ b/src/librebots/kit/guilds.py @@ -76,12 +76,17 @@ def _remember(self, guild_id: int, report: Callable[[], Awaitable[object]]) -> N self._pending[guild_id] = report async def _report_again(self) -> None: - while self._pending: - guild_id, report = next(iter(self._pending.items())) + failed: set[int] = set() + while waiting := [guild_id for guild_id in self._pending if guild_id not in failed]: + guild_id = waiting[0] + report = self._pending[guild_id] try: await report() except HubError as exc: _LOGGER.warning("Could not report guild %s again after a sync: %s", guild_id, exc) + if self._pending.get(guild_id) is report: + failed.add(guild_id) + continue if self._pending.get(guild_id) is report: del self._pending[guild_id] diff --git a/tests/test_guilds.py b/tests/test_guilds.py index 352f81a..5bcaf97 100644 --- a/tests/test_guilds.py +++ b/tests/test_guilds.py @@ -28,12 +28,14 @@ def __init__(self) -> None: self.log: list[str] = [] self.joined: list[guilds_pb2.GuildJoinedRequest] = [] self.synced: list[guilds_pb2.SyncGuildsRequest] = [] + self.attempts: list[str] = [] self.failing: set[str] = set() self.stalled: set[str] = set() self.stall_started = asyncio.Event() self._never = asyncio.Event() async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: + self.attempts.append(name) if name in self.failing: await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") if name in self.stalled: @@ -240,31 +242,29 @@ async def test_reports_changes_before_a_sync_only_once(hub: tuple[Hub, FakeGuild assert fake.log == [f"joined {guild}", f"sync {guild}"] -async def test_logs_a_repeated_report_that_fails_and_keeps_the_sync_result( +async def test_keeps_a_repeated_report_that_fails_for_the_next_sync( hub: tuple[Hub, FakeGuilds], caplog: pytest.LogCaptureFixture ) -> None: reporter, fake = GuildReporter(hub[0]), hub[1] - guild = on_shard(0) - result: list[SyncResult] = [] + joined, left = on_shard(0, 1), on_shard(0, 2) - async def join_then_break_the_hub() -> AsyncIterator[None]: - await reporter.joined(guild, preferred_locale="en-US", member_count=3) + async def change_then_break_joins() -> AsyncIterator[None]: + await reporter.joined(joined, preferred_locale="en-US", member_count=3) + await reporter.left(left) fake.failing.add("joined") yield - listing = Listing([]) - listing.proceed.clear() - sync = asyncio.create_task(reporter.sync(listing.rest, [0], 1)) with caplog.at_level(logging.WARNING, logger="librebots.kit"): - async with asyncio.timeout(5): - await listing.started.wait() - async for _ in join_then_break_the_hub(): - pass - listing.proceed.set() - result.append(await sync) - - assert result == [SyncResult(joined=1, left=2)] - assert str(guild) in caplog.text + await run_with_paused_listing(reporter, Listing([]), change_then_break_joins()) + + assert fake.log == [f"joined {joined}", f"left {left}", "sync ", f"left {left}"] + assert fake.attempts.count("joined") == 2 + assert str(joined) in caplog.text + + fake.failing.clear() + assert await reporter.sync(Listing([]).rest, [0], 1) == SyncResult(joined=1, left=2) + + assert fake.log[-2:] == ["sync ", f"joined {joined}"] async def test_runs_one_sync_at_a_time(hub: tuple[Hub, FakeGuilds]) -> None: