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
11 changes: 7 additions & 4 deletions .coderabbit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]

Expand Down Expand Up @@ -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"
17 changes: 15 additions & 2 deletions src/librebots/kit/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
2 changes: 2 additions & 0 deletions src/librebots/kit/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
from collections.abc import Mapping
from pathlib import Path
Expand Down
109 changes: 109 additions & 0 deletions src/librebots/kit/guilds.py
Original file line number Diff line number Diff line change
@@ -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:
Comment thread
rayakame marked this conversation as resolved.
Resolved
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]
Comment thread
rayakame marked this conversation as resolved.
Resolved

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
24 changes: 9 additions & 15 deletions src/librebots/kit/hub.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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+")
Expand All @@ -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.

Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions src/librebots/kit/i18n.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import logging
from collections.abc import Iterable, Mapping
from pathlib import Path
Expand Down
2 changes: 2 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
from pathlib import Path

Expand Down
Loading