Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]
Expand Down
8 changes: 6 additions & 2 deletions src/librebots/kit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,23 @@

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",
"ConfigError",
"GuildReporter",
"Hub",
"HubError",
"HubRequestError",
"HubUnavailableError",
"Privacy",
"SyncResult",
"call_hub",
"connect_hub",
]
14 changes: 0 additions & 14 deletions src/librebots/kit/_rpc.py

This file was deleted.

100 changes: 100 additions & 0 deletions src/librebots/kit/ext/errors.py
Original file line number Diff line number Diff line change
@@ -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)
Comment thread
rayakame marked this conversation as resolved.
Resolved
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)
9 changes: 4 additions & 5 deletions src/librebots/kit/guilds.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down Expand Up @@ -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)

Expand All @@ -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))
45 changes: 40 additions & 5 deletions src/librebots/kit/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
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

import grpc
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
Expand All @@ -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):
Expand Down Expand Up @@ -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


Expand All @@ -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))
5 changes: 4 additions & 1 deletion src/librebots/kit/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand Down
6 changes: 6 additions & 0 deletions src/librebots/kit/locales/de/kit.ftl
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions src/librebots/kit/locales/en-US/kit.ftl
Original file line number Diff line number Diff line change
@@ -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
17 changes: 8 additions & 9 deletions src/librebots/kit/privacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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)

Expand Down
Loading