diff --git a/pyproject.toml b/pyproject.toml index fba3f8a..24afff9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ dependencies = [ "fluent-runtime>=0.4.0", "hikari>=2.6.0", "hikari-lightbulb[crontrigger]>=3.2.7", - "hikari-risa>=1.3.0", + "hikari-risa>=1.4.0", "librebots-hub>=0.1.1", "msgspec>=0.22.0", ] diff --git a/src/librebots/kit/__init__.py b/src/librebots/kit/__init__.py index 3c42c53..b226a3b 100644 --- a/src/librebots/kit/__init__.py +++ b/src/librebots/kit/__init__.py @@ -2,11 +2,12 @@ from librebots.kit.config import Config, ConfigError from librebots.kit.guilds import GuildReporter, SyncResult -from librebots.kit.hub import Hub, HubError, connect_hub -from librebots.kit.i18n import Catalog, CatalogError +from librebots.kit.hub import Hub, HubError, HubRequestError, HubUnavailableError, call_hub, connect_hub +from librebots.kit.i18n import LOCALES, Catalog, CatalogError from librebots.kit.privacy import Privacy __all__ = [ + "LOCALES", "Catalog", "CatalogError", "Config", @@ -14,7 +15,10 @@ "GuildReporter", "Hub", "HubError", + "HubRequestError", + "HubUnavailableError", "Privacy", "SyncResult", + "call_hub", "connect_hub", ] diff --git a/src/librebots/kit/_rpc.py b/src/librebots/kit/_rpc.py deleted file mode 100644 index eb86043..0000000 --- a/src/librebots/kit/_rpc.py +++ /dev/null @@ -1,14 +0,0 @@ -from __future__ import annotations - -from collections.abc import Awaitable - -import grpc.aio - -from librebots.kit.hub import HubError - - -async def call[T](method: str, request: Awaitable[T]) -> T: - try: - return await request - 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/ext/errors.py b/src/librebots/kit/ext/errors.py new file mode 100644 index 0000000..40b96d2 --- /dev/null +++ b/src/librebots/kit/ext/errors.py @@ -0,0 +1,100 @@ +"""Answers a failed command or click that no handler of the bot took, and logs it. + +Needs a `Catalog` with kit's texts (`kit.LOCALES`) and a risa client in lightbulb's dependency injection. Its handlers +run last, so a bot's own error handlers at the default priority come first. + +The answer is visible to the caller only, except after a public defer: it then replaces the "thinking" message, and +Discord keeps that message's visibility. +""" + +from __future__ import annotations + +import logging +import re +import secrets +import traceback +from collections.abc import Sequence + +import hikari +import lightbulb +import risa +from risa import ui + +from librebots.kit.hub import HubUnavailableError +from librebots.kit.i18n import Catalog + +__all__ = ["loader"] + +_LOGGER = logging.getLogger(__name__) +_PRIORITY = -100 +_RED = 0xE24B4A +# hikari puts the request URL into its HTTP errors, and these URLs carry the interaction token. +_TOKEN_IN_URL = re.compile(r"(/(?:interactions|webhooks)/\d+/)[^/\s?#']+") + +loader = lightbulb.Loader() + + +@loader.error_handler(priority=_PRIORITY) +async def _answer_failed_command( + exc: lightbulb.exceptions.ExecutionPipelineFailedException, catalog: Catalog = lightbulb.di.INJECTED +) -> bool: + ctx = exc.context + layout = _build_error_reply( + catalog, ctx.interaction.locale, exc.causes, f"Command /{ctx.command_data.qualified_name}" + ) + try: + await ctx.respond(**ui.render(layout), ephemeral=True) + except hikari.HTTPError as error: + _LOGGER.warning("Could not tell the caller that a command failed: %s", _redact_tokens(str(error))) + return True + + +async def _answer_failed_click( + pipeline: risa.ExecutionPipeline, ctx: risa.ComponentContext, catalog: Catalog = risa.INJECTED +) -> bool: + layout = _build_error_reply( + catalog, ctx.interaction.locale, [failure.error for failure in pipeline.failures], "A click" + ) + try: + await ctx.respond(**ui.render(layout), ephemeral=True) + except hikari.HTTPError as error: + _LOGGER.warning("Could not tell the clicker that a click failed: %s", _redact_tokens(str(error))) + return True + + +# Resolving risa's client while the extension loads would freeze the registry before the bot is done with it. +@loader.listener(hikari.StartedEvent) +async def _register_click_fallback(_: hikari.StartedEvent, views: risa.Client = lightbulb.di.INJECTED) -> None: + views.error_handler(_answer_failed_click, priority=_PRIORITY) + + +def _build_error_reply( + catalog: Catalog, locale: hikari.Locale | str, errors: Sequence[Exception], failed: str +) -> ui.Container: + key, reference = _log_and_pick_text(errors, failed) + text = catalog.text(locale, key) if reference is None else catalog.text(locale, key, reference=reference) + return ui.Container( + ui.TextDisplay(f"### {catalog.text(locale, f'{key}.title')}"), + ui.TextDisplay(text), + accent_color=_RED, + ) + + +def _log_and_pick_text(errors: Sequence[Exception], failed: str) -> tuple[str, str | None]: + for error in errors: + if isinstance(error, HubUnavailableError): + _LOGGER.warning("%s failed because the hub is unavailable: %s", failed, _redact_tokens(str(error))) + return "kit-error-hub", None + for error in errors: + if isinstance(error, hikari.ForbiddenError): + _LOGGER.info("%s failed for a missing permission: %s", failed, _redact_tokens(str(error))) + return "kit-error-forbidden", None + reference = secrets.token_hex(3) + for error in errors: + described = _redact_tokens("".join(traceback.format_exception(error)).rstrip()) + _LOGGER.error("%s failed, reference %s\n%s", failed, reference, described) + return "kit-error-unknown", reference + + +def _redact_tokens(text: str) -> str: + return _TOKEN_IN_URL.sub(r"\1***", text) diff --git a/src/librebots/kit/guilds.py b/src/librebots/kit/guilds.py index 7e02ebb..38b5081 100644 --- a/src/librebots/kit/guilds.py +++ b/src/librebots/kit/guilds.py @@ -10,8 +10,7 @@ from librebots.hub.v1.guilds_pb2 import GuildJoinedRequest, GuildLeftRequest, SyncedGuild, SyncGuildsRequest from librebots.hub.v1.shards_pb2 import ShardSet -from librebots.kit._rpc import call -from librebots.kit.hub import Hub, HubError +from librebots.kit.hub import Hub, HubError, call_hub __all__ = ["GuildReporter", "SyncResult"] @@ -67,7 +66,7 @@ async def sync(self, rest: hikari.api.RESTClient, shard_ids: Collection[int], sh 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)) + response = await call_hub("SyncGuilds", self._hub.guilds.SyncGuilds(request, timeout=self._timeout)) await self._report_again() return SyncResult(joined=response.joined, left=response.left) @@ -94,9 +93,9 @@ async def _report_join(self, guild_id: int, preferred_locale: str, member_count: 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)) + response = await call_hub("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)) + await call_hub("GuildLeft", self._hub.guilds.GuildLeft(request, timeout=self._timeout)) diff --git a/src/librebots/kit/hub.py b/src/librebots/kit/hub.py index 59c6162..dfdcd3e 100644 --- a/src/librebots/kit/hub.py +++ b/src/librebots/kit/hub.py @@ -3,7 +3,7 @@ import asyncio import logging import re -from collections.abc import Callable, Sequence +from collections.abc import Awaitable, Callable, Sequence from importlib.metadata import version as installed_version from pathlib import Path @@ -11,7 +11,7 @@ import grpc.aio import hikari import msgspec -from librebots.hub import connect +from librebots.hub import connect, reason_of from librebots.hub.v1.guilds_pb2_grpc import GuildServiceStub from librebots.hub.v1.info_pb2 import GetInfoRequest from librebots.hub.v1.info_pb2_grpc import InfoServiceStub @@ -20,14 +20,31 @@ from librebots.kit.config import Config -__all__ = ["Hub", "HubError", "connect_hub"] +__all__ = ["Hub", "HubError", "HubRequestError", "HubUnavailableError", "call_hub", "connect_hub"] _LOGGER = logging.getLogger(__name__) _VERSION = re.compile(r"(\d+)\.(\d+)\.\d+") +_UNAVAILABLE = frozenset({grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED}) class HubError(Exception): - """The hub could not be reached, rejected the bot or is too old for it.""" + """Something went wrong with the hub. The message says what, for the log.""" + + +class HubUnavailableError(HubError): + """The hub could not be reached or did not answer in time. Trying again later can work.""" + + +class HubRequestError(HubError): + """The hub answered a call with an error. + + `reason` is the name of the hub's reason code, such as `"REASON_GUILD_NOT_REGISTERED"`, or `None` if it sent none. + """ + + def __init__(self, message: str, *, code: grpc.StatusCode, reason: str | None) -> None: + super().__init__(message) + self.code: grpc.StatusCode = code + self.reason: str | None = reason class Hub(msgspec.Struct, frozen=True, kw_only=True): @@ -116,7 +133,7 @@ async def _hub_version(channel: grpc.aio.Channel, address: str, timeout: float) message = f"The hub at {address} rejected HUB_TOKEN" case code: message = f"The hub at {address} failed with {code.name}: {exc.details()}" - raise HubError(message) from exc + raise _error(message, exc) from exc return response.version @@ -139,3 +156,21 @@ def _major_minor(text: str) -> tuple[int, int] | None: if match is None: return None return int(match[1]), int(match[2]) + + +async def call_hub[T](method: str, request: Awaitable[T]) -> T: + """Await a call to the hub and raise the matching `HubError` if it fails. + + For calls to a bot's own service: `await call_hub("ReportStars", stub.ReportStars(request, timeout=10))`. + """ + try: + return await request + except grpc.aio.AioRpcError as exc: + raise _error(f"{method} failed with {exc.code().name}: {exc.details()}", exc) from exc + + +def _error(message: str, exc: grpc.aio.AioRpcError) -> HubError: + code = exc.code() + if code in _UNAVAILABLE: + return HubUnavailableError(message) + return HubRequestError(message, code=code, reason=reason_of(exc)) diff --git a/src/librebots/kit/i18n.py b/src/librebots/kit/i18n.py index 8d14c40..9210b36 100644 --- a/src/librebots/kit/i18n.py +++ b/src/librebots/kit/i18n.py @@ -13,9 +13,12 @@ from fluent.syntax import FluentParser, ast from fluent.syntax.visitor import Visitor -__all__ = ["Catalog", "CatalogError"] +__all__ = ["LOCALES", "Catalog", "CatalogError"] _LOGGER = logging.getLogger(__name__) + +LOCALES = Path(__file__).parent / "locales" +"""kit's own texts. A bot loads them before its own: `Catalog.load(LOCALES, "locales")`.""" _ENGLISH = "en-US" diff --git a/src/librebots/kit/locales/de/kit.ftl b/src/librebots/kit/locales/de/kit.ftl new file mode 100644 index 0000000..9a6738b --- /dev/null +++ b/src/librebots/kit/locales/de/kit.ftl @@ -0,0 +1,6 @@ +kit-error-hub = Ich komme gerade nicht an meine Daten. Versuch es in einer Minute noch einmal. + .title = Gerade nicht erreichbar +kit-error-forbidden = Mir fehlt dafür eine Berechtigung. Bitte einen Server-Admin, meine Rolle zu prüfen. + .title = Berechtigung fehlt +kit-error-unknown = Versuch es später noch einmal. Wenn es wieder passiert, gib dem Betreiber des Bots diese Referenz: `{ $reference }` + .title = Etwas ist schiefgelaufen diff --git a/src/librebots/kit/locales/en-US/kit.ftl b/src/librebots/kit/locales/en-US/kit.ftl new file mode 100644 index 0000000..b03b47a --- /dev/null +++ b/src/librebots/kit/locales/en-US/kit.ftl @@ -0,0 +1,6 @@ +kit-error-hub = I can't reach my data at the moment. Try again in a minute. + .title = Not reachable right now +kit-error-forbidden = I'm missing a permission for this. Ask a server admin to check my role. + .title = Missing permission +kit-error-unknown = Try again later. If it keeps happening, give the bot's operator this reference: `{ $reference }` + .title = Something went wrong diff --git a/src/librebots/kit/privacy.py b/src/librebots/kit/privacy.py index 1b10a16..3e4c750 100644 --- a/src/librebots/kit/privacy.py +++ b/src/librebots/kit/privacy.py @@ -15,8 +15,7 @@ RequestUserDeletionRequest, ) -from librebots.kit._rpc import call -from librebots.kit.hub import Hub +from librebots.kit.hub import Hub, call_hub __all__ = ["Privacy"] @@ -48,13 +47,13 @@ def __init__( async def count_user(self, user_id: int) -> dict[str, int]: """Return what the bot stores about a person, counted by category. Raises `HubError` if the hub fails.""" request = CountUserDataRequest(user_id=user_id) - response = await call("CountUserData", self._hub.privacy.CountUserData(request, timeout=self._timeout)) + response = await call_hub("CountUserData", self._hub.privacy.CountUserData(request, timeout=self._timeout)) return _by_category(response.categories) async def export_user(self, user_id: int) -> str: """Return everything the bot stores about a person as a JSON document. Raises `HubError` if the hub fails.""" request = ExportUserDataRequest(user_id=user_id) - response = await call("ExportUserData", self._hub.privacy.ExportUserData(request, timeout=self._timeout)) + response = await call_hub("ExportUserData", self._hub.privacy.ExportUserData(request, timeout=self._timeout)) return response.json async def delete_user(self, user_id: int) -> None: @@ -63,7 +62,7 @@ async def delete_user(self, user_id: int) -> None: Returns once the hub has recorded the request. Raises `HubError` if it cannot. """ request = RequestUserDeletionRequest(user_id=user_id) - await call("RequestUserDeletion", self._hub.privacy.RequestUserDeletion(request, timeout=self._timeout)) + await call_hub("RequestUserDeletion", self._hub.privacy.RequestUserDeletion(request, timeout=self._timeout)) self._start(user_id) async def resume_deletions(self) -> int: @@ -72,7 +71,7 @@ async def resume_deletions(self) -> int: Raises `HubError` if the hub fails. """ request = ListPendingUserDeletionsRequest() - response = await call( + response = await call_hub( "ListPendingUserDeletions", self._hub.privacy.ListPendingUserDeletions(request, timeout=self._timeout) ) return sum(self._start(deletion.user_id) for deletion in response.deletions) @@ -85,13 +84,13 @@ async def wait_for_deletions(self) -> None: async def count_guild(self, guild_id: int) -> dict[str, int]: """Return what the bot stores about a guild, counted by category. Raises `HubError` if the hub fails.""" request = CountGuildDataRequest(guild_id=guild_id) - response = await call("CountGuildData", self._hub.privacy.CountGuildData(request, timeout=self._timeout)) + response = await call_hub("CountGuildData", self._hub.privacy.CountGuildData(request, timeout=self._timeout)) return _by_category(response.categories) async def delete_guild(self, guild_id: int) -> dict[str, int]: """Delete what the bot stores about a guild and return what was deleted. Raises `HubError` if the hub fails.""" request = DeleteGuildDataRequest(guild_id=guild_id) - response = await call("DeleteGuildData", self._hub.privacy.DeleteGuildData(request, timeout=self._timeout)) + response = await call_hub("DeleteGuildData", self._hub.privacy.DeleteGuildData(request, timeout=self._timeout)) return _by_category(response.deleted) async def close(self) -> None: @@ -118,7 +117,7 @@ async def _delete(self, user_id: int) -> None: if self._on_user_deletion is not None: await self._on_user_deletion(user_id) request = DeleteUserDataRequest(user_id=user_id) - await call("DeleteUserData", self._hub.privacy.DeleteUserData(request, timeout=self._timeout)) + await call_hub("DeleteUserData", self._hub.privacy.DeleteUserData(request, timeout=self._timeout)) except Exception: _LOGGER.exception("Deleting the data of user %s failed; it stays pending and is tried again later", user_id) diff --git a/tests/test_ext_errors.py b/tests/test_ext_errors.py new file mode 100644 index 0000000..10d34dc --- /dev/null +++ b/tests/test_ext_errors.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import logging +import re +from collections.abc import AsyncGenerator, Callable, Sequence +from unittest.mock import AsyncMock, create_autospec + +import grpc +import hikari +import lightbulb +import pytest +import risa +from risa import ui + +from librebots.kit import LOCALES, Catalog, HubRequestError, HubUnavailableError +from librebots.kit.ext import errors + +EXTENSION = "librebots.kit.ext.errors" +RED = hikari.Color(0xE24B4A) + + +TOKEN = "aW50ZXJhY3Rpb246c2VjcmV0" +TOKEN_URL = f"https://discord.com/api/v10/webhooks/123/{TOKEN}/messages/@original" + + +def forbidden() -> hikari.ForbiddenError: + return hikari.ForbiddenError(url="https://discord.com/api", headers={}, raw_body="") + + +FAILURES: dict[str, Callable[[], Exception]] = { + "hub-down": lambda: HubUnavailableError("GetStats failed with UNAVAILABLE: hub is down"), + "forbidden": forbidden, + "refused": lambda: HubRequestError( + "GuildJoined failed with NOT_FOUND", code=grpc.StatusCode.NOT_FOUND, reason=None + ), + "broken": lambda: RuntimeError("it broke"), + "webhook-gone": lambda: hikari.NotFoundError(url=TOKEN_URL, headers={}, raw_body="", message="Unknown Webhook"), +} + + +def failing_command(name: str) -> type[lightbulb.SlashCommand]: + class Failing(lightbulb.SlashCommand, name=name, description="Fails"): + @lightbulb.invoke + async def invoke(self, ctx: lightbulb.Context) -> None: + raise FAILURES[name]() + + return Failing + + +@risa.register(name="kit-test-failing") +class Failing(risa.View): + def render(self) -> ui.Layout: + return ui.Row(ui.Button(self.hub_down, label="Hub"), ui.Button(self.broken, label="Broken")) + + @risa.handler + async def hub_down(self, ctx: risa.ComponentContext) -> None: + raise FAILURES["hub-down"]() + + @risa.handler + async def broken(self, ctx: risa.ComponentContext) -> None: + raise FAILURES["broken"]() + + +class Command: + def __init__(self, name: str, locale: hikari.Locale = hikari.Locale.EN_US) -> None: + interaction = create_autospec(hikari.CommandInteraction, instance=True) + interaction.command_name = name + interaction.command_type = hikari.CommandType.SLASH + interaction.options = [] + interaction.registered_guild_id = None + interaction.locale = locale + self.interaction: hikari.CommandInteraction = interaction + self.response: AsyncMock = interaction.create_initial_response + + +class Bot: + def __init__(self) -> None: + app = create_autospec(hikari.GatewayBot, instance=True) + app.rest = self.rest = create_autospec(hikari.api.RESTClient, instance=True) + app.event_manager = self.events = hikari.impl.EventManagerImpl( + hikari.impl.EntityFactoryImpl(app), hikari.impl.EventFactoryImpl(app), hikari.Intents.NONE + ) + self.app: hikari.GatewayBot = app + self.client = lightbulb.client_from_app(self.app, sync_commands=False) + self.views = risa.client_from_lightbulb(self.client) + self.views.add_view(Failing) + self.client.di.registry_for(lightbulb.di.Contexts.DEFAULT).register_value(Catalog, Catalog.load(LOCALES)) + for name in FAILURES: + self.client.register(failing_command(name)) + + async def start(self) -> None: + await self.client.load_extensions(EXTENSION) + await self.client.start() + await self.events.dispatch(hikari.StartedEvent(app=self.app), return_tasks=True) + + async def run(self, command: Command) -> AsyncMock: + await self.client.handle_interaction_create(command.interaction) + return command.response + + async def click(self, button: int, locale: hikari.Locale = hikari.Locale.EN_US) -> AsyncMock: + rendered = await self.views.build(Failing()) + row, _ = rendered.components[0].build() + interaction = create_autospec(hikari.ComponentInteraction, instance=True) + interaction.custom_id = row["components"][button]["custom_id"] + interaction.locale = locale + shard = create_autospec(hikari.api.GatewayShard, instance=True) + event = hikari.ComponentInteractionCreateEvent(shard=shard, interaction=interaction) + await self.events.dispatch(event, return_tasks=True) + return self.rest.create_interaction_response + + +@pytest.fixture +async def bot() -> AsyncGenerator[Bot]: + bot = Bot() + await bot.start() + yield bot + await bot.client.stop() + await bot.client.unload_extensions(EXTENSION) + + +def reply(response: AsyncMock) -> tuple[hikari.Color, list[str]]: + call = response.await_args + assert call is not None + assert call.kwargs["flags"] == hikari.MessageFlag.EPHEMERAL + components: Sequence[hikari.api.ComponentBuilder] = call.kwargs["components"] + (container,) = components + payload, _ = container.build() + return payload["accent_color"], [child["content"] for child in payload["components"]] + + +def reference_in(text: str) -> str: + match = re.search(r"`([0-9a-f]{6})`", text) + assert match is not None, text + return match[1] + + +async def test_tells_the_caller_the_hub_is_unreachable(bot: Bot, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.WARNING, logger=errors.__name__): + response = await bot.run(Command("hub-down")) + + assert reply(response) == ( + RED, + ["### Not reachable right now", "I can't reach my data at the moment. Try again in a minute."], + ) + assert "hub is down" in caplog.text + + +async def test_tells_the_caller_a_permission_is_missing(bot: Bot) -> None: + _, texts = reply(await bot.run(Command("forbidden"))) + + assert texts[0] == "### Missing permission" + + +@pytest.mark.parametrize( + ("name", "logged"), + [ + ("broken", "RuntimeError: it broke"), + ("refused", "HubRequestError: GuildJoined failed with NOT_FOUND"), + ], +) +async def test_gives_a_reference_that_the_log_repeats( + bot: Bot, caplog: pytest.LogCaptureFixture, name: str, logged: str +) -> None: + with caplog.at_level(logging.ERROR, logger=errors.__name__): + response = await bot.run(Command(name)) + + _, texts = reply(response) + assert texts[0] == "### Something went wrong" + (record,) = caplog.records + assert reference_in(texts[1]) in record.getMessage() + assert "Traceback" in record.getMessage() + assert logged in record.getMessage() + + +async def test_logs_no_interaction_token(bot: Bot, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.ERROR, logger=errors.__name__): + await bot.run(Command("webhook-gone")) + + assert "Unknown Webhook" in caplog.text + assert "/webhooks/123/***/messages" in caplog.text + assert TOKEN not in caplog.text + + +async def test_answers_in_the_language_of_the_caller(bot: Bot) -> None: + _, texts = reply(await bot.run(Command("hub-down", hikari.Locale.DE))) + + assert texts[0] == "### Gerade nicht erreichbar" + + +async def test_leaves_errors_to_the_handlers_of_the_bot(bot: Bot) -> None: + handled: list[Exception] = [] + + async def handle(exc: lightbulb.exceptions.ExecutionPipelineFailedException) -> bool: + handled.extend(exc.causes) + return True + + bot.client.error_handler(handle) + response = await bot.run(Command("broken")) + + assert [repr(cause) for cause in handled] == [repr(FAILURES["broken"]())] + response.assert_not_awaited() + + +async def test_logs_an_answer_that_fails(bot: Bot, caplog: pytest.LogCaptureFixture) -> None: + command = Command("hub-down") + command.response.side_effect = hikari.NotFoundError( + url=TOKEN_URL, headers={}, raw_body="", message="Unknown interaction" + ) + + with caplog.at_level(logging.WARNING, logger=errors.__name__): + await bot.run(command) + + assert "Unknown interaction" in caplog.text + assert TOKEN not in caplog.text + + +async def test_tells_the_clicker_the_hub_is_unreachable(bot: Bot) -> None: + response = await bot.click(0, hikari.Locale.DE) + + assert reply(response) == ( + RED, + [ + "### Gerade nicht erreichbar", + "Ich komme gerade nicht an meine Daten. Versuch es in einer Minute noch einmal.", + ], + ) + + +async def test_gives_a_clicker_a_reference_that_the_log_repeats(bot: Bot, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.ERROR, logger=errors.__name__): + response = await bot.click(1) + + _, texts = reply(response) + (record,) = caplog.records + assert reference_in(texts[1]) in record.getMessage() + assert "RuntimeError: it broke" in record.getMessage() diff --git a/tests/test_hub.py b/tests/test_hub.py index e880d27..02d61eb 100644 --- a/tests/test_hub.py +++ b/tests/test_hub.py @@ -11,9 +11,11 @@ import grpc.aio import hikari import pytest +from google.rpc import error_details_pb2, status_pb2 # pyright: ignore[reportMissingTypeStubs] +from hub_server import serving from librebots.hub.v1 import info_pb2, info_pb2_grpc -from librebots.kit import Config, HubError, connect_hub +from librebots.kit import Config, HubError, HubRequestError, HubUnavailableError, call_hub, connect_hub TOKEN = "hub-token" CLIENT = version("librebots-hub") @@ -36,6 +38,33 @@ async def GetInfo( return info_pb2.GetInfoResponse(version=self.version) +class FailingInfo(info_pb2_grpc.InfoServiceServicer): + def __init__(self, code: grpc.StatusCode, reason: str | None = None) -> None: + self.code = code + self.reason = reason + + async def GetInfo( + self, + request: info_pb2.GetInfoRequest, + context: grpc.aio.ServicerContext[info_pb2.GetInfoRequest, Awaitable[info_pb2.GetInfoResponse]], + ) -> info_pb2.GetInfoResponse: + await context.abort(self.code, "it broke", trailing_metadata=self._details()) + raise AssertionError + + def _details(self) -> tuple[tuple[str, bytes], ...]: + if self.reason is None: + return () + status = status_pb2.Status(code=self.code.value[0], message="it broke") + status.details.add().Pack(error_details_pb2.ErrorInfo(reason=self.reason, domain="hub.libre-bots")) + return (("grpc-status-details-bin", status.SerializeToString()),) + + +async def get_info_failing_with(code: grpc.StatusCode, reason: str | None = None) -> None: + info = FailingInfo(code, reason) + async with serving(lambda server: info_pb2_grpc.add_InfoServiceServicer_to_server(info, server)) as hub: + await call_hub("GetInfo", info_pb2_grpc.InfoServiceStub(hub.channel).GetInfo(info_pb2.GetInfoRequest())) + + 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} @@ -134,23 +163,27 @@ async def test_sends_no_shard_label_before_the_shards_start(fake_hub: tuple[str, async def test_rejects_a_wrong_token(fake_hub: tuple[str, FakeInfo]) -> None: - with pytest.raises(HubError, match="HUB_TOKEN"): + with pytest.raises(HubRequestError, match="HUB_TOKEN") as caught: await connect_hub(config(fake_hub[0], HUB_TOKEN="wrong")) + assert caught.value.code == grpc.StatusCode.UNAUTHENTICATED + async def test_gives_up_when_the_hub_does_not_answer() -> None: address = unused_address() - with pytest.raises(HubError, match=f"{address}.*0.2 seconds"): + with pytest.raises(HubUnavailableError, match=f"{address}.*0.2 seconds"): await connect_hub(config(address), timeout=0.2) async def test_reports_an_unreadable_ca_file(tmp_path: Path) -> None: values = {"HUB_TLS": "true", "HUB_CA_FILE": str(tmp_path / "missing.pem")} - with pytest.raises(HubError, match="HUB_CA_FILE"): + with pytest.raises(HubError, match="HUB_CA_FILE") as caught: await connect_hub(config(unused_address(), **values), timeout=0.2) + assert caught.type is HubError + @pytest.mark.parametrize( "hub_version", @@ -180,9 +213,11 @@ async def test_rejects_a_hub_with_an_older_minor_version(fake_hub: tuple[str, Fa address, info = fake_hub info.version = f"{CLIENT_MAJOR}.{CLIENT_MINOR - 1}.99" if CLIENT_MINOR else f"{CLIENT_MAJOR - 1}.99.0" - with pytest.raises(HubError, match=info.version): + with pytest.raises(HubError, match=info.version) as caught: await connect_hub(config(address)) + assert caught.type is HubError + async def test_warns_about_a_hub_without_a_version( fake_hub: tuple[str, FakeInfo], caplog: pytest.LogCaptureFixture @@ -202,5 +237,40 @@ async def test_rejects_an_unknown_hub_version(fake_hub: tuple[str, FakeInfo]) -> address, info = fake_hub info.version = "banana" - with pytest.raises(HubError, match="banana"): + with pytest.raises(HubError, match="banana") as caught: await connect_hub(config(address)) + + assert caught.type is HubError + + +async def test_call_returns_the_response(fake_hub: tuple[str, FakeInfo]) -> None: + hub = await connect_hub(config(fake_hub[0])) + stub = info_pb2_grpc.InfoServiceStub(hub.channel) + try: + response = await call_hub("GetInfo", stub.GetInfo(info_pb2.GetInfoRequest())) + finally: + await hub.close() + + assert response.version == CLIENT + + +@pytest.mark.parametrize("code", [grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED]) +async def test_call_reports_a_hub_it_cannot_reach(code: grpc.StatusCode) -> None: + with pytest.raises(HubUnavailableError, match=f"GetInfo failed with {code.name}: it broke"): + await get_info_failing_with(code) + + +async def test_call_reports_the_code_and_reason_of_a_refused_call() -> None: + with pytest.raises(HubRequestError, match="GetInfo failed with NOT_FOUND") as caught: + await get_info_failing_with(grpc.StatusCode.NOT_FOUND, "REASON_GUILD_NOT_REGISTERED") + + assert caught.value.code == grpc.StatusCode.NOT_FOUND + assert caught.value.reason == "REASON_GUILD_NOT_REGISTERED" + + +async def test_call_reports_no_reason_when_the_hub_sends_none() -> None: + with pytest.raises(HubRequestError) as caught: + await get_info_failing_with(grpc.StatusCode.INTERNAL) + + assert caught.value.code == grpc.StatusCode.INTERNAL + assert caught.value.reason is None diff --git a/uv.lock b/uv.lock index 432035a..072b237 100644 --- a/uv.lock +++ b/uv.lock @@ -453,16 +453,16 @@ crontrigger = [ [[package]] name = "hikari-risa" -version = "1.3.0" +version = "1.4.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "hikari" }, { name = "linkd" }, { name = "msgspec" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/79/3d/62c74de422038d40f72a83869d3583bcb36f2b671fe89bbc8556b44c5a00/hikari_risa-1.3.0.tar.gz", hash = "sha256:815c5226fa9e6095bf2e62867565a958ff0f9cc839e563de0fd89018f73654d1", size = 94706, upload-time = "2026-11-19T13:06:37.371Z" } +sdist = { url = "https://files.pythonhosted.org/packages/0d/dc/32e915d73ca307aaf5665c02b54465ce1b10d46048e252f5ca68fe084600/hikari_risa-1.4.0.tar.gz", hash = "sha256:9cc0c4d8a09e0bb5878128bf5de5622b09a9a382bcc8febee0e586f222113485", size = 96135, upload-time = "2026-11-27T19:35:05.884Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/19/606eee371568f0d1a72ee131b55ec93f2847802a45405f09f5bf30265d43/hikari_risa-1.3.0-py3-none-any.whl", hash = "sha256:33553a4c9c6e48becaa5098ee2f6b1ea156d469d5c3fe9e4cd5856b56d1e4a70", size = 138357, upload-time = "2026-11-19T13:06:35.756Z" }, + { url = "https://files.pythonhosted.org/packages/09/6a/6a46c50d4b0865b1d4bb2650cd84e5c9daf296bfbc80338588ad0e927866/hikari_risa-1.4.0-py3-none-any.whl", hash = "sha256:3dd609baadaf0bc9b3f4b7857c0793c0a36b9faf51ef1d6e8d3f6aa60ac524ab", size = 139864, upload-time = "2026-11-27T19:35:04.604Z" }, ] [[package]] @@ -524,7 +524,7 @@ requires-dist = [ { name = "fluent-runtime", specifier = ">=0.4.0" }, { name = "hikari", specifier = ">=2.6.0" }, { name = "hikari-lightbulb", extras = ["crontrigger"], specifier = ">=3.2.7" }, - { name = "hikari-risa", specifier = ">=1.3.0" }, + { name = "hikari-risa", specifier = ">=1.4.0" }, { name = "librebots-hub", specifier = ">=0.1.1" }, { name = "msgspec", specifier = ">=0.22.0" }, ]