Repository navigation
Report the guilds of each shard to the hub #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
11203a2
Report the guilds of each shard to the hub
rayakame 83a92e8
Bound the hub calls and keep unsent guild changes for the next sync
rayakame eef4c85
Take hikari's types instead of own protocols
rayakame 8deb25e
Keep a guild change whose repeat failed for the next sync
rayakame File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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: | ||
| 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] | ||
|
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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,5 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.