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..65159dd 100644 --- a/src/librebots/kit/__init__.py +++ b/src/librebots/kit/__init__.py @@ -1,5 +1,18 @@ +from __future__ import annotations + from librebots.kit.config import Config, ConfigError -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__ = ["Catalog", "CatalogError", "Config", "ConfigError", "Hub", "HubError", "ShardedApp", "connect_hub"] +__all__ = [ + "Catalog", + "CatalogError", + "Config", + "ConfigError", + "GuildReporter", + "Hub", + "HubError", + "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..7d2496c --- /dev/null +++ b/src/librebots/kit/guilds.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +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__ = ["GuildReporter", "SyncResult"] + +_LOGGER = logging.getLogger(__name__) + + +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 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, *, timeout: float = 30) -> None: + self._hub = hub + self._timeout = timeout + self._sync_lock = asyncio.Lock() + 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.""" + 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: 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. + """ + shards = frozenset(shard_ids) + async with self._sync_lock: + 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() or guild_id in self._pending: + self._pending[guild_id] = report + + async def _report_again(self) -> None: + 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] + + 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, timeout=self._timeout)) + return response.settings.locale + + async def _report_leave(self, guild_id: int) -> None: + 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: + 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..59c6162 100644 --- a/src/librebots/kit/hub.py +++ b/src/librebots/kit/hub.py @@ -1,13 +1,15 @@ +from __future__ import annotations + 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 @@ -18,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+") @@ -28,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. @@ -55,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 @@ -94,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/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..5bcaf97 --- /dev/null +++ b/tests/test_guilds.py @@ -0,0 +1,359 @@ +from __future__ import annotations + +import asyncio +import logging +from collections.abc import AsyncGenerator, AsyncIterator, Awaitable +from unittest.mock import create_autospec + +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 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.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: + self.stall_started.set() + await self._never.wait() + + 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) + + +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 Listing: + def __init__(self, guilds: list[hikari.OwnGuild]) -> None: + self.guilds = guilds + 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 + + async def _guilds(self) -> AsyncIterator[hikari.OwnGuild]: + self.started.set() + await self.proceed.wait() + for guild in self.guilds: + yield guild + + +@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(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] + 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(listing.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(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, 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 listing.started.wait() + async for _ in during: + pass + listing.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, Listing([own_guild(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, Listing([own_guild(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, Listing([]), 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(Listing([own_guild(guild)]).rest, [0], 1) + + assert fake.log == [f"joined {guild}", f"sync {guild}"] + + +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] + joined, left = on_shard(0, 1), on_shard(0, 2) + + 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 + + with caplog.at_level(logging.WARNING, logger="librebots.kit"): + 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: + reporter, fake = GuildReporter(hub[0]), hub[1] + 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.rest, [0], 1) + + async with asyncio.timeout(5): + 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.started.is_set() + first.proceed.set() + await asyncio.gather(running, waiting) + + assert not started_early + 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(Listing([]).rest, [0], 1) + + fake.stalled.clear() + 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: + 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, Listing([]), join_then_break_the_sync()) + fake.failing.clear() + await reporter.sync(Listing([]).rest, [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, Listing([]), join_then_break_the_sync()) + fake.failing.clear() + await reporter.left(guild) + await reporter.sync(Listing([]).rest, [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) + listing = Listing([own_guild(first), own_guild(second)]) + listing.proceed.clear() + + async with asyncio.timeout(5): + 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") + listing.proceed.set() + await fake.stall_started.wait() + sync.cancel() + with pytest.raises(asyncio.CancelledError): + await sync + fake.stalled.clear() + 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 2797e99..e880d27 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -1,8 +1,11 @@ +from __future__ import annotations + import logging import socket -from collections.abc import AsyncGenerator, 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 @@ -25,7 +28,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}": @@ -33,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 @@ -94,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" @@ -112,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" 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" }, ]