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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Libre Bots kit

The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations, UI
helpers, guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code,
The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations,
guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code,
and nothing in it runs unless the bot names it.

```sh
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ requires-python = ">=3.12"
dependencies = [
"fluent-runtime>=0.4.0",
"hikari>=2.6.0",
"hikari-lightbulb>=3.2.7",
"hikari-lightbulb[crontrigger]>=3.2.7",
"hikari-risa>=1.3.0",
"librebots-hub>=0.1.1",
"msgspec>=0.22.0",
Expand Down
1 change: 1 addition & 0 deletions src/librebots/kit/ext/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from __future__ import annotations
76 changes: 76 additions & 0 deletions src/librebots/kit/ext/guilds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Reports joins and leaves to the hub, and syncs a shard's guilds when it opens a session and daily at 04:00 UTC.

Needs a `GuildReporter` in lightbulb's dependency injection.
"""

from __future__ import annotations

import logging
from collections.abc import Collection

import hikari
import lightbulb

from librebots.kit.guilds import GuildReporter
from librebots.kit.hub import HubError

__all__ = ["loader", "sync_own_shards"]

_LOGGER = logging.getLogger(__name__)

loader = lightbulb.Loader()


@loader.listener(hikari.GuildJoinEvent)
async def _report_join(event: hikari.GuildJoinEvent, reporter: GuildReporter = lightbulb.di.INJECTED) -> None:
guild = event.guild
try:
await reporter.joined(guild.id, preferred_locale=str(guild.preferred_locale), member_count=guild.member_count)
except HubError as exc:
_LOGGER.warning("Could not report joining guild %s, the next sync will: %s", guild.id, exc)


@loader.listener(hikari.GuildLeaveEvent)
async def _report_leave(event: hikari.GuildLeaveEvent, reporter: GuildReporter = lightbulb.di.INJECTED) -> None:
try:
await reporter.left(event.guild_id)
except HubError as exc:
_LOGGER.warning("Could not report leaving guild %s, the next sync will: %s", event.guild_id, exc)


@loader.listener(hikari.ShardReadyEvent)
async def _sync_shard(
event: hikari.ShardReadyEvent,
reporter: GuildReporter = lightbulb.di.INJECTED,
rest: hikari.api.RESTClient = lightbulb.di.INJECTED,
) -> None:
await _sync(reporter, rest, [event.shard.id], event.shard.shard_count)


@lightbulb.di.with_di
async def sync_own_shards(
bot: hikari.GatewayBot = lightbulb.di.INJECTED,
reporter: GuildReporter = lightbulb.di.INJECTED,
rest: hikari.api.RESTClient = lightbulb.di.INJECTED,
) -> None:
"""Sync the guilds of every shard this process runs, as the extension does daily at 04:00 UTC.

Takes its arguments from lightbulb's dependency injection, so call it from a command, listener or task.
"""
await _sync(reporter, rest, bot.shards.keys(), bot.shard_count)


# With lightbulb's default of one failure, a single error would stop the daily sync until the next restart.
loader.task(lightbulb.crontrigger("0 4 * * *"), max_failures=-1)(sync_own_shards)


async def _sync(
reporter: GuildReporter, rest: hikari.api.RESTClient, shard_ids: Collection[int], shard_count: int
) -> None:
shards = sorted(shard_ids)
try:
result = await reporter.sync(rest, shards, shard_count)
except HubError as exc:
_LOGGER.warning("Could not sync the guilds of shards %s: %s", shards, exc)
return
_LOGGER.info("Synced the guilds of shards %s: %d joined, %d left", shards, result.joined, result.left)
89 changes: 89 additions & 0 deletions tests/guild_fakes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
from __future__ import annotations

import asyncio
from collections.abc import AsyncIterator, Awaitable
from unittest.mock import create_autospec

import grpc
import grpc.aio
import hikari
from librebots.hub.v1 import guilds_pb2, guilds_pb2_grpc

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
172 changes: 172 additions & 0 deletions tests/test_ext_guilds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
from __future__ import annotations

import logging
from collections.abc import AsyncGenerator, Awaitable, Callable
from unittest.mock import create_autospec

import hikari
import lightbulb
import pytest
from guild_fakes import FakeGuilds, Listing, on_shard, own_guild
from hub_server import serving
from librebots.hub.v1 import guilds_pb2_grpc
from librebots.hub.v1.shards_pb2 import ShardSet

from librebots.kit import GuildReporter
from librebots.kit.ext import guilds

EXTENSION = "librebots.kit.ext.guilds"

type Listener[E: hikari.Event] = Callable[[E], Awaitable[None]]


@pytest.fixture
async def running() -> AsyncGenerator[tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds]]:
# The fake answers only the calls guild reporting makes.
fake = FakeGuilds() # pyright: ignore[reportAbstractUsage]
async with serving(lambda server: guilds_pb2_grpc.add_GuildServiceServicer_to_server(fake, server)) as hub:
bot = hikari.GatewayBot("MTIzNDU2Nzg5MDEyMzQ1Njc4.x.y", banner=None)
client = lightbulb.client_from_app(bot)
client.di.registry_for(lightbulb.di.Contexts.DEFAULT).register_value(GuildReporter, GuildReporter(hub))
await client.load_extensions(EXTENSION)
yield bot, client, fake
await client.unload_extensions(EXTENSION)


def listener[E: hikari.Event](bot: hikari.GatewayBot, event_type: type[E]) -> Listener[E]:
(callback,) = bot.event_manager.get_listeners(event_type)
return callback


def provide[T](client: lightbulb.Client, typ: type[T], value: T) -> None:
client.di.registry_for(lightbulb.di.Contexts.DEFAULT).register_value(typ, value)


def join_event(guild_id: int, locale: hikari.Locale, members: int | None) -> hikari.GuildJoinEvent:
guild = create_autospec(hikari.GatewayGuild, instance=True)
guild.id = hikari.Snowflake(guild_id)
guild.preferred_locale = locale
guild.member_count = members
event = create_autospec(hikari.GuildJoinEvent, instance=True)
event.guild = guild
return event


def leave_event(guild_id: int) -> hikari.GuildLeaveEvent:
event = create_autospec(hikari.GuildLeaveEvent, instance=True)
event.guild_id = hikari.Snowflake(guild_id)
return event


def ready_event(shard_id: int, shard_count: int) -> hikari.ShardReadyEvent:
shard = create_autospec(hikari.api.GatewayShard, instance=True)
shard.id = shard_id
shard.shard_count = shard_count
event = create_autospec(hikari.ShardReadyEvent, instance=True)
event.shard = shard
return event


def sharded_bot(shard_ids: list[int], shard_count: int) -> hikari.GatewayBot:
bot = create_autospec(hikari.GatewayBot, instance=True)
bot.shards = {shard_id: create_autospec(hikari.api.GatewayShard, instance=True) for shard_id in shard_ids}
bot.shard_count = shard_count
return bot


def guilds_on_every_shard() -> Listing:
return Listing([own_guild(on_shard(shard), members=shard + 1) for shard in range(4)])


@pytest.mark.parametrize("event_type", [hikari.GuildJoinEvent, hikari.GuildLeaveEvent, hikari.ShardReadyEvent])
async def test_listens_once_loaded(
running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], event_type: type[hikari.Event]
) -> None:
assert listener(running[0], event_type)


async def test_reports_a_join_with_the_language_and_member_count(
running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds],
) -> None:
bot, _, fake = running

await listener(bot, hikari.GuildJoinEvent)(join_event(on_shard(1), hikari.Locale.DE, 42))

request = fake.joined[0]
assert (request.guild_id, request.preferred_locale, request.member_count) == (on_shard(1), "de", 42)


async def test_reports_a_leave(running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds]) -> None:
bot, _, fake = running

await listener(bot, hikari.GuildLeaveEvent)(leave_event(on_shard(3)))

assert fake.log == [f"left {on_shard(3)}"]


@pytest.mark.parametrize(
("call", "event_type", "event"),
[
("joined", hikari.GuildJoinEvent, join_event(on_shard(0), hikari.Locale.EN_US, 1)),
("left", hikari.GuildLeaveEvent, leave_event(on_shard(0))),
],
)
async def test_logs_a_report_the_hub_fails(
running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds],
caplog: pytest.LogCaptureFixture,
call: str,
event_type: type[hikari.Event],
event: hikari.Event,
) -> None:
bot, _, fake = running
fake.failing.add(call)

with caplog.at_level(logging.WARNING, logger=guilds.__name__):
await listener(bot, event_type)(event)

assert str(on_shard(0)) in caplog.text
assert "UNAVAILABLE" in caplog.text


async def test_syncs_the_shard_of_a_new_session(
running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], caplog: pytest.LogCaptureFixture
) -> None:
bot, client, fake = running
provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest)

with caplog.at_level(logging.INFO, logger=guilds.__name__):
await listener(bot, hikari.ShardReadyEvent)(ready_event(2, 4))

request = fake.synced[0]
assert request.shards == ShardSet(shard_ids=[2], shard_count=4)
assert [guild.guild_id for guild in request.guilds] == [on_shard(2)]
assert "1 joined, 2 left" in caplog.text


async def test_logs_a_sync_the_hub_fails(
running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds], caplog: pytest.LogCaptureFixture
) -> None:
bot, client, fake = running
provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest)
fake.failing.add("sync")

with caplog.at_level(logging.WARNING, logger=guilds.__name__):
await listener(bot, hikari.ShardReadyEvent)(ready_event(2, 4))

assert "shards [2]" in caplog.text
assert "UNAVAILABLE" in caplog.text


async def test_syncs_every_own_shard_once_a_day(
running: tuple[hikari.GatewayBot, lightbulb.Client, FakeGuilds],
) -> None:
_, client, fake = running
provide(client, hikari.GatewayBot, sharded_bot([0, 2], 4))
provide(client, hikari.api.RESTClient, guilds_on_every_shard().rest)

async with client.di.enter_context(lightbulb.di.Contexts.DEFAULT):
await guilds.sync_own_shards()

request = fake.synced[0]
assert request.shards == ShardSet(shard_ids=[0, 2], shard_count=4)
assert [guild.guild_id for guild in request.guilds] == [on_shard(0), on_shard(2)]
Loading