librebots-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,374 @@
1
+ """Adds `/privacy`: who runs the bot, what it stores about the caller, and export and deletion of that data.
2
+
3
+ Deleting asks for the person's username, or for the server's name from the server owner, typed into a modal. Needs
4
+ `Privacy`, `Config`, `BotInfo`, a risa client and a `Catalog` with kit's texts and the bot's `privacy-category-<name>`
5
+ texts in lightbulb's dependency injection.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from collections.abc import Mapping
12
+
13
+ import hikari
14
+ import lightbulb
15
+ import msgspec
16
+ import risa
17
+ from risa import ui
18
+
19
+ from librebots.kit.bot import BotInfo
20
+ from librebots.kit.config import Config
21
+ from librebots.kit.hub import HubError
22
+ from librebots.kit.i18n import Catalog
23
+ from librebots.kit.privacy import Privacy
24
+
25
+ __all__ = ["loader"]
26
+
27
+ _LOGGER = logging.getLogger(__name__)
28
+ _RED = 0xE24B4A
29
+ _DELETE_USER_MODAL = "kit-privacy-delete-user"
30
+ _DELETE_SERVER_MODAL = "kit-privacy-delete-server"
31
+ _TYPED_NAME = "typed-name"
32
+
33
+ loader = lightbulb.Loader()
34
+
35
+
36
+ @risa.register(name="kit-privacy")
37
+ class _PrivacyOverview(risa.View):
38
+ locale: risa.Prop[str] = "en-US"
39
+ stored: risa.Prop[dict[str, int]] = msgspec.field(default_factory=dict[str, int])
40
+ server_owner: risa.Prop[bool] = False
41
+ catalog: risa.Prop[Catalog | None] = None
42
+ config: risa.Prop[Config | None] = None
43
+ bot: risa.Prop[BotInfo | None] = None
44
+
45
+ def render(self) -> ui.Layout:
46
+ if self.catalog is None or self.config is None or self.bot is None:
47
+ raise RuntimeError("the overview renders only with its texts, config and bot info set")
48
+ catalog, locale = self.catalog, self.locale
49
+ if self.stored:
50
+ stored = f"{catalog.text(locale, 'kit-privacy-overview.stored')}\n{_listed(catalog, locale, self.stored)}"
51
+ else:
52
+ stored = catalog.text(locale, "kit-privacy-overview.nothing")
53
+ buttons: list[ui.Button | ui.LinkButton] = [
54
+ ui.Button(
55
+ self.export_my_data,
56
+ label=catalog.text(locale, "kit-privacy-export.button"),
57
+ style=hikari.ButtonStyle.SECONDARY,
58
+ disabled=not self.stored,
59
+ ),
60
+ ui.Button(
61
+ self.ask_to_delete_my_data,
62
+ label=catalog.text(locale, "kit-privacy-delete.button"),
63
+ style=hikari.ButtonStyle.DANGER,
64
+ disabled=not self.stored,
65
+ ),
66
+ ui.LinkButton(self.config.privacy_policy_url, label=catalog.text(locale, "kit-privacy-overview.policy")),
67
+ ]
68
+ if self.server_owner:
69
+ buttons.append(
70
+ ui.Button(
71
+ self.ask_to_delete_server_data,
72
+ label=catalog.text(locale, "kit-privacy-server.button"),
73
+ style=hikari.ButtonStyle.DANGER,
74
+ )
75
+ )
76
+ operator = catalog.text(
77
+ locale,
78
+ "kit-privacy-overview",
79
+ operator=self.config.operator_name,
80
+ contact=self.config.operator_contact,
81
+ bot=self.bot.name,
82
+ )
83
+ return ui.Container(
84
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-overview.title')}"),
85
+ ui.TextDisplay(operator),
86
+ ui.TextDisplay(stored),
87
+ ui.Row(*buttons),
88
+ accent_color=self.bot.accent_color,
89
+ )
90
+
91
+ @risa.handler
92
+ async def export_my_data(
93
+ self,
94
+ ctx: risa.ComponentContext,
95
+ privacy: Privacy = risa.INJECTED,
96
+ catalog: Catalog = risa.INJECTED,
97
+ bot: BotInfo = risa.INJECTED,
98
+ ) -> None:
99
+ locale = ctx.interaction.locale
100
+ exported = await privacy.export_user(ctx.user.id)
101
+ layout = ui.Container(
102
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-export.title')}"),
103
+ ui.TextDisplay(catalog.text(locale, "kit-privacy-export", bot=bot.name)),
104
+ ui.File(hikari.Bytes(exported.encode(), f"{bot.hub_name}-data.json")),
105
+ accent_color=bot.accent_color,
106
+ )
107
+ await ctx.respond(**ui.render(layout), ephemeral=True)
108
+
109
+ @risa.handler
110
+ async def ask_to_delete_my_data(
111
+ self,
112
+ ctx: risa.ComponentContext,
113
+ privacy: Privacy = risa.INJECTED,
114
+ catalog: Catalog = risa.INJECTED,
115
+ bot: BotInfo = risa.INJECTED,
116
+ ) -> None:
117
+ locale = ctx.interaction.locale
118
+ stored = await privacy.count_user(ctx.user.id)
119
+ what = catalog.text(locale, "kit-privacy-delete", bot=bot.name)
120
+ layout = ui.Container(
121
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-delete.title')}"),
122
+ ui.TextDisplay(f"{what}\n{_listed(catalog, locale, stored)}"),
123
+ ui.TextDisplay(catalog.text(locale, "kit-privacy-delete.warning")),
124
+ ui.Row(
125
+ ui.Button(
126
+ self.open_delete_my_data_modal,
127
+ label=catalog.text(locale, "kit-privacy-delete.confirm"),
128
+ style=hikari.ButtonStyle.DANGER,
129
+ ),
130
+ ui.Button(
131
+ self.back_to_overview,
132
+ label=catalog.text(locale, "kit-privacy-cancel"),
133
+ style=hikari.ButtonStyle.SECONDARY,
134
+ ),
135
+ ),
136
+ accent_color=_RED,
137
+ )
138
+ await ctx.edit(layout)
139
+
140
+ @risa.handler
141
+ async def open_delete_my_data_modal(self, ctx: risa.ComponentContext, catalog: Catalog = risa.INJECTED) -> None:
142
+ locale = ctx.interaction.locale
143
+ field = hikari.impl.ModalActionRowBuilder().add_text_input(
144
+ _TYPED_NAME,
145
+ catalog.text(locale, "kit-privacy-delete.input"),
146
+ placeholder=ctx.user.username,
147
+ max_length=100,
148
+ )
149
+ title = catalog.text(locale, "kit-privacy-delete.modal")
150
+ await ctx.interaction.create_modal_response(title, _DELETE_USER_MODAL, components=[field])
151
+
152
+ @risa.handler
153
+ async def ask_to_delete_server_data(
154
+ self,
155
+ ctx: risa.ComponentContext,
156
+ privacy: Privacy = risa.INJECTED,
157
+ catalog: Catalog = risa.INJECTED,
158
+ bot: BotInfo = risa.INJECTED,
159
+ ) -> None:
160
+ locale = ctx.interaction.locale
161
+ guild = await _guild_if_owner(ctx.interaction)
162
+ if guild is None:
163
+ refusal = _nothing_deleted(catalog, locale, "kit-privacy-server.owner-only")
164
+ await ctx.respond(**ui.render(refusal), ephemeral=True)
165
+ return
166
+ stored = await privacy.count_guild(guild.id)
167
+ what = catalog.text(locale, "kit-privacy-server", bot=bot.name)
168
+ layout = ui.Container(
169
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-server.title')}"),
170
+ ui.TextDisplay(f"{what}\n{_listed(catalog, locale, stored)}"),
171
+ ui.TextDisplay(catalog.text(locale, "kit-privacy-server.warning")),
172
+ ui.Row(
173
+ ui.Button(
174
+ self.open_delete_server_data_modal,
175
+ label=catalog.text(locale, "kit-privacy-server.confirm"),
176
+ style=hikari.ButtonStyle.DANGER,
177
+ ),
178
+ ui.Button(
179
+ self.back_to_overview,
180
+ label=catalog.text(locale, "kit-privacy-cancel"),
181
+ style=hikari.ButtonStyle.SECONDARY,
182
+ ),
183
+ ),
184
+ accent_color=_RED,
185
+ )
186
+ await ctx.edit(layout)
187
+
188
+ @risa.handler
189
+ async def open_delete_server_data_modal(self, ctx: risa.ComponentContext, catalog: Catalog = risa.INJECTED) -> None:
190
+ locale = ctx.interaction.locale
191
+ guild = await _guild_if_owner(ctx.interaction)
192
+ if guild is None:
193
+ refusal = _nothing_deleted(catalog, locale, "kit-privacy-server.owner-only")
194
+ await ctx.respond(**ui.render(refusal), ephemeral=True)
195
+ return
196
+ field = hikari.impl.ModalActionRowBuilder().add_text_input(
197
+ _TYPED_NAME,
198
+ catalog.text(locale, "kit-privacy-server.input"),
199
+ placeholder=guild.name,
200
+ max_length=100,
201
+ )
202
+ title = catalog.text(locale, "kit-privacy-server.modal")
203
+ await ctx.interaction.create_modal_response(title, _DELETE_SERVER_MODAL, components=[field])
204
+
205
+ @risa.handler
206
+ async def back_to_overview(
207
+ self,
208
+ ctx: risa.ComponentContext,
209
+ privacy: Privacy = risa.INJECTED,
210
+ catalog: Catalog = risa.INJECTED,
211
+ config: Config = risa.INJECTED,
212
+ bot: BotInfo = risa.INJECTED,
213
+ ) -> None:
214
+ overview = _PrivacyOverview(
215
+ locale=str(ctx.interaction.locale),
216
+ stored=await privacy.count_user(ctx.interaction.user.id),
217
+ server_owner=await _guild_if_owner(ctx.interaction) is not None,
218
+ catalog=catalog,
219
+ config=config,
220
+ bot=bot,
221
+ )
222
+ await ctx.edit(overview.render())
223
+
224
+
225
+ @loader.command
226
+ class _PrivacyCommand(
227
+ lightbulb.SlashCommand,
228
+ name="kit-cmd-privacy.name",
229
+ description="kit-cmd-privacy.description",
230
+ localize=True,
231
+ contexts=[hikari.ApplicationContextType.GUILD, hikari.ApplicationContextType.BOT_DM],
232
+ ):
233
+ @lightbulb.invoke
234
+ async def show_privacy(
235
+ self,
236
+ ctx: lightbulb.Context,
237
+ views: risa.Client = lightbulb.di.INJECTED,
238
+ privacy: Privacy = lightbulb.di.INJECTED,
239
+ catalog: Catalog = lightbulb.di.INJECTED,
240
+ config: Config = lightbulb.di.INJECTED,
241
+ bot: BotInfo = lightbulb.di.INJECTED,
242
+ ) -> None:
243
+ overview = _PrivacyOverview(
244
+ locale=str(ctx.interaction.locale),
245
+ stored=await privacy.count_user(ctx.interaction.user.id),
246
+ server_owner=await _guild_if_owner(ctx.interaction) is not None,
247
+ catalog=catalog,
248
+ config=config,
249
+ bot=bot,
250
+ )
251
+ await ctx.respond(**await views.build(overview), ephemeral=True)
252
+
253
+
254
+ @loader.listener(hikari.ModalInteractionCreateEvent)
255
+ async def _delete_after_the_typed_name(
256
+ event: hikari.ModalInteractionCreateEvent,
257
+ privacy: Privacy = lightbulb.di.INJECTED,
258
+ catalog: Catalog = lightbulb.di.INJECTED,
259
+ bot: BotInfo = lightbulb.di.INJECTED,
260
+ ) -> None:
261
+ interaction = event.interaction
262
+ if interaction.custom_id not in {_DELETE_USER_MODAL, _DELETE_SERVER_MODAL}:
263
+ return
264
+ locale = interaction.locale
265
+ typed = next(
266
+ (field.value for row in interaction.components for field in row.components if field.custom_id == _TYPED_NAME),
267
+ "",
268
+ )
269
+ typed = typed.strip().casefold()
270
+
271
+ guild: hikari.Guild | None = None
272
+ refusal: str | None = None
273
+ if interaction.custom_id == _DELETE_USER_MODAL:
274
+ if typed != interaction.user.username.casefold():
275
+ refusal = "kit-privacy-delete.mismatch"
276
+ elif (guild := await _guild_if_owner(interaction)) is None:
277
+ refusal = "kit-privacy-server.owner-only"
278
+ elif typed != guild.name.casefold():
279
+ refusal = "kit-privacy-server.mismatch"
280
+ if refusal is not None:
281
+ await interaction.create_initial_response(
282
+ hikari.ResponseType.MESSAGE_CREATE,
283
+ **ui.render(_nothing_deleted(catalog, locale, refusal)),
284
+ flags=hikari.MessageFlag.EPHEMERAL,
285
+ )
286
+ return
287
+
288
+ # Discord drops an answer that comes after three seconds, and the hub may take longer.
289
+ await interaction.create_initial_response(hikari.ResponseType.DEFERRED_MESSAGE_UPDATE)
290
+ try:
291
+ if guild is None:
292
+ await privacy.delete_user(interaction.user.id)
293
+ finished = ui.Container(
294
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-deleting.title')}"),
295
+ ui.TextDisplay(catalog.text(locale, "kit-privacy-deleting")),
296
+ accent_color=bot.accent_color,
297
+ )
298
+ else:
299
+ deleted = await privacy.delete_guild(guild.id)
300
+ if deleted:
301
+ what = f"{catalog.text(locale, 'kit-privacy-server-deleted', bot=bot.name)}\n"
302
+ what += _listed(catalog, locale, deleted)
303
+ else:
304
+ what = catalog.text(locale, "kit-privacy-server-deleted.nothing", bot=bot.name)
305
+ finished = ui.Container(
306
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-server-deleted.title')}"),
307
+ ui.TextDisplay(what),
308
+ accent_color=bot.accent_color,
309
+ )
310
+ except HubError as exc:
311
+ # A call that ran out of time may still have been carried out, so the answer must not say nothing happened.
312
+ _LOGGER.warning("Could not confirm a deletion after a typed confirmation: %s", exc)
313
+ finished = ui.Container(
314
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-unconfirmed.title')}"),
315
+ ui.TextDisplay(catalog.text(locale, "kit-privacy-unconfirmed")),
316
+ accent_color=_RED,
317
+ )
318
+ await interaction.edit_initial_response(**ui.render(finished))
319
+
320
+
321
+ # Resolving risa's client while the extension loads would freeze the registry before the bot is done with it.
322
+ @loader.listener(hikari.StartedEvent)
323
+ async def _route_clicks_and_resume_deletions(
324
+ _: hikari.StartedEvent,
325
+ client: lightbulb.Client = lightbulb.di.INJECTED,
326
+ views: risa.Client = lightbulb.di.INJECTED,
327
+ privacy: Privacy = lightbulb.di.INJECTED,
328
+ ) -> None:
329
+ views.add_view(_PrivacyOverview)
330
+ # One task per client: a lightbulb task keeps its state after a cancel, so a shared one breaks the next client.
331
+ # With lightbulb's default of one failure, a single error would stop the daily retry until the next restart.
332
+ client.task(lightbulb.crontrigger("30 4 * * *"), max_failures=-1)(_resume_pending_deletions)
333
+ await _resume_pending_deletions(privacy)
334
+
335
+
336
+ async def _resume_pending_deletions(privacy: Privacy = lightbulb.di.INJECTED) -> None:
337
+ try:
338
+ started = await privacy.resume_deletions()
339
+ except HubError as exc:
340
+ _LOGGER.warning("Could not resume the pending deletions: %s", exc)
341
+ return
342
+ if started:
343
+ _LOGGER.info("Resumed %d pending deletions", started)
344
+
345
+
346
+ async def _guild_if_owner(
347
+ interaction: hikari.CommandInteraction | hikari.ComponentInteraction | hikari.ModalInteraction,
348
+ ) -> hikari.Guild | None:
349
+ if interaction.guild_id is None:
350
+ return None
351
+ guild = interaction.get_guild() or await interaction.fetch_guild()
352
+ if guild is None or guild.owner_id != interaction.user.id:
353
+ return None
354
+ return guild
355
+
356
+
357
+ def _listed(catalog: Catalog, locale: hikari.Locale | str, stored: Mapping[str, int]) -> str:
358
+ lines: list[str] = []
359
+ for category, count in stored.items():
360
+ key = f"privacy-category-{category}"
361
+ try:
362
+ lines.append(f"- {catalog.text(locale, key, count=count)}")
363
+ except KeyError:
364
+ _LOGGER.warning("The bot's texts have no %s, so /privacy names the category as it is", key)
365
+ lines.append(f"- {category}: {count}")
366
+ return "\n".join(lines)
367
+
368
+
369
+ def _nothing_deleted(catalog: Catalog, locale: hikari.Locale | str, reason: str) -> ui.Container:
370
+ return ui.Container(
371
+ ui.TextDisplay(f"### {catalog.text(locale, 'kit-privacy-not-deleted.title')}"),
372
+ ui.TextDisplay(catalog.text(locale, reason)),
373
+ accent_color=_RED,
374
+ )
@@ -0,0 +1,101 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import functools
5
+ import logging
6
+ from collections.abc import Awaitable, Callable, Collection
7
+
8
+ import hikari
9
+ import msgspec
10
+ from librebots.hub.v1.guilds_pb2 import GuildJoinedRequest, GuildLeftRequest, SyncedGuild, SyncGuildsRequest
11
+ from librebots.hub.v1.shards_pb2 import ShardSet
12
+
13
+ from librebots.kit.hub import Hub, HubError, call_hub
14
+
15
+ __all__ = ["GuildReporter", "SyncResult"]
16
+
17
+ _LOGGER = logging.getLogger(__name__)
18
+
19
+
20
+ class SyncResult(msgspec.Struct, frozen=True, kw_only=True):
21
+ """How many guilds a sync registered and how many it marked as left."""
22
+
23
+ joined: int
24
+ left: int
25
+
26
+
27
+ class GuildReporter:
28
+ """Reports to the hub which guilds the shards of this process are in.
29
+
30
+ Call `joined` and `left` for the gateway's join and leave events, and `sync` once the shards have started, after
31
+ a shard opens a new session and once a day. A join or leave reported while a sync runs is sent again after the
32
+ next sync that succeeds, so the older guild list a sync read cannot undo it. Every call to the hub gives up after
33
+ `timeout` seconds.
34
+ """
35
+
36
+ def __init__(self, hub: Hub, *, timeout: float = 30) -> None:
37
+ self._hub = hub
38
+ self._timeout = timeout
39
+ self._sync_lock = asyncio.Lock()
40
+ self._pending: dict[int, Callable[[], Awaitable[object]]] = {}
41
+
42
+ async def joined(self, guild_id: int, *, preferred_locale: str, member_count: int | None) -> str:
43
+ """Report that the bot joined a guild and return the guild's language. Raises `HubError` if the hub fails."""
44
+ report = functools.partial(self._report_join, guild_id, preferred_locale, member_count)
45
+ self._remember(guild_id, report)
46
+ return await report()
47
+
48
+ async def left(self, guild_id: int) -> None:
49
+ """Report that the bot left or was removed from a guild. Raises `HubError` if the hub fails."""
50
+ report = functools.partial(self._report_leave, guild_id)
51
+ self._remember(guild_id, report)
52
+ await report()
53
+
54
+ async def sync(self, rest: hikari.api.RESTClient, shard_ids: Collection[int], shard_count: int) -> SyncResult:
55
+ """Send every guild on these shards, and the hub marks the bot's other guilds on them as left.
56
+
57
+ Syncs run one at a time. Raises `HubError` if the hub fails.
58
+ """
59
+ shards = frozenset(shard_ids)
60
+ async with self._sync_lock:
61
+ guilds = [
62
+ SyncedGuild(guild_id=guild.id, member_count=guild.approximate_member_count)
63
+ async for guild in rest.fetch_my_guilds()
64
+ if (guild.id >> 22) % shard_count in shards
65
+ ]
66
+ request = SyncGuildsRequest(
67
+ shards=ShardSet(shard_ids=sorted(shards), shard_count=shard_count), guilds=guilds
68
+ )
69
+ response = await call_hub("SyncGuilds", self._hub.guilds.SyncGuilds(request, timeout=self._timeout))
70
+ await self._report_again()
71
+ return SyncResult(joined=response.joined, left=response.left)
72
+
73
+ def _remember(self, guild_id: int, report: Callable[[], Awaitable[object]]) -> None:
74
+ if self._sync_lock.locked() or guild_id in self._pending:
75
+ self._pending[guild_id] = report
76
+
77
+ async def _report_again(self) -> None:
78
+ failed: set[int] = set()
79
+ while waiting := [guild_id for guild_id in self._pending if guild_id not in failed]:
80
+ guild_id = waiting[0]
81
+ report = self._pending[guild_id]
82
+ try:
83
+ await report()
84
+ except HubError as exc:
85
+ _LOGGER.warning("Could not report guild %s again after a sync: %s", guild_id, exc)
86
+ if self._pending.get(guild_id) is report:
87
+ failed.add(guild_id)
88
+ continue
89
+ if self._pending.get(guild_id) is report:
90
+ del self._pending[guild_id]
91
+
92
+ async def _report_join(self, guild_id: int, preferred_locale: str, member_count: int | None) -> str:
93
+ request = GuildJoinedRequest(
94
+ guild_id=guild_id, preferred_locale=preferred_locale, member_count=member_count or 0
95
+ )
96
+ response = await call_hub("GuildJoined", self._hub.guilds.GuildJoined(request, timeout=self._timeout))
97
+ return response.settings.locale
98
+
99
+ async def _report_leave(self, guild_id: int) -> None:
100
+ request = GuildLeftRequest(guild_id=guild_id)
101
+ await call_hub("GuildLeft", self._hub.guilds.GuildLeft(request, timeout=self._timeout))
librebots/kit/hub.py ADDED
@@ -0,0 +1,176 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ import re
6
+ from collections.abc import Awaitable, Callable, Sequence
7
+ from importlib.metadata import version as installed_version
8
+ from pathlib import Path
9
+
10
+ import grpc
11
+ import grpc.aio
12
+ import hikari
13
+ import msgspec
14
+ from librebots.hub import connect, reason_of
15
+ from librebots.hub.v1.guilds_pb2_grpc import GuildServiceStub
16
+ from librebots.hub.v1.info_pb2 import GetInfoRequest
17
+ from librebots.hub.v1.info_pb2_grpc import InfoServiceStub
18
+ from librebots.hub.v1.privacy_pb2_grpc import PrivacyServiceStub
19
+ from librebots.hub.v1.stats_pb2_grpc import StatsServiceStub
20
+
21
+ from librebots.kit.config import Config
22
+
23
+ __all__ = ["Hub", "HubError", "HubRequestError", "HubUnavailableError", "call_hub", "connect_hub"]
24
+
25
+ _LOGGER = logging.getLogger(__name__)
26
+ _VERSION = re.compile(r"(\d+)\.(\d+)\.\d+")
27
+ _UNAVAILABLE = frozenset({grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED})
28
+
29
+
30
+ class HubError(Exception):
31
+ """Something went wrong with the hub. The message says what, for the log."""
32
+
33
+
34
+ class HubUnavailableError(HubError):
35
+ """The hub could not be reached or did not answer in time. Trying again later can work."""
36
+
37
+
38
+ class HubRequestError(HubError):
39
+ """The hub answered a call with an error.
40
+
41
+ `reason` is the name of the hub's reason code, such as `"REASON_GUILD_NOT_REGISTERED"`, or `None` if it sent none.
42
+ """
43
+
44
+ def __init__(self, message: str, *, code: grpc.StatusCode, reason: str | None) -> None:
45
+ super().__init__(message)
46
+ self.code: grpc.StatusCode = code
47
+ self.reason: str | None = reason
48
+
49
+
50
+ class Hub(msgspec.Struct, frozen=True, kw_only=True):
51
+ """A connection to the hub with the stubs of the services every bot uses.
52
+
53
+ A bot's own services take `channel`, for example `StarboardServiceStub(hub.channel)`.
54
+ """
55
+
56
+ channel: grpc.aio.Channel
57
+ version: str
58
+ guilds: GuildServiceStub
59
+ privacy: PrivacyServiceStub
60
+ stats: StatsServiceStub
61
+
62
+ async def close(self) -> None:
63
+ """Close the connection and cancel the calls still running on it."""
64
+ await self.channel.close()
65
+
66
+
67
+ async def connect_hub(config: Config, *, shards: hikari.ShardAware | None = None, timeout: float = 60) -> Hub:
68
+ """Connect to the hub and return once it has answered.
69
+
70
+ Every call names the shards of this process: those `shards` runs at that moment, or else `SHARD_IDS` and
71
+ `SHARD_COUNT` from the configuration. Waits up to `timeout` seconds for the hub to come up. Raises `HubError` if
72
+ it does not, if it rejects `HUB_TOKEN`, or if it is older than the installed `librebots-hub` client.
73
+ """
74
+ channel = connect(
75
+ config.hub_address,
76
+ config.hub_token,
77
+ tls=config.hub_tls,
78
+ root_certificates=await _read_ca_file(config.hub_ca_file),
79
+ shards=_shard_label(config, shards),
80
+ )
81
+ try:
82
+ hub_version = await _hub_version(channel, config.hub_address, timeout)
83
+ _check_version(hub_version, await asyncio.to_thread(installed_version, "librebots-hub"))
84
+ except BaseException:
85
+ await channel.close()
86
+ raise
87
+ _LOGGER.info("Connected to the hub at %s, version %s", config.hub_address, hub_version)
88
+ return Hub(
89
+ channel=channel,
90
+ version=hub_version,
91
+ guilds=GuildServiceStub(channel),
92
+ privacy=PrivacyServiceStub(channel),
93
+ stats=StatsServiceStub(channel),
94
+ )
95
+
96
+
97
+ async def _read_ca_file(path: str | None) -> bytes | None:
98
+ if path is None:
99
+ return None
100
+ try:
101
+ return await asyncio.to_thread(Path(path).read_bytes)
102
+ except OSError as exc:
103
+ raise HubError(f"Cannot read HUB_CA_FILE: {exc}") from exc
104
+
105
+
106
+ def _shard_label(
107
+ config: Config, app: hikari.ShardAware | None
108
+ ) -> Callable[[], tuple[Sequence[int], int] | None] | None:
109
+ if app is not None:
110
+
111
+ def label() -> tuple[Sequence[int], int] | None:
112
+ if not app.shards:
113
+ return None
114
+ return tuple(app.shards), app.shard_count
115
+
116
+ return label
117
+ if config.shard_ids is not None and config.shard_count is not None:
118
+ configured = (config.shard_ids, config.shard_count)
119
+ return lambda: configured
120
+ return None
121
+
122
+
123
+ async def _hub_version(channel: grpc.aio.Channel, address: str, timeout: float) -> str:
124
+ try:
125
+ response = await InfoServiceStub(channel).GetInfo(GetInfoRequest(), timeout=timeout, wait_for_ready=True)
126
+ except grpc.aio.AioRpcError as exc:
127
+ match exc.code():
128
+ case grpc.StatusCode.DEADLINE_EXCEEDED:
129
+ message = (
130
+ f"The hub at {address} did not answer within {timeout:g} seconds; check HUB_ADDRESS and HUB_TLS"
131
+ )
132
+ case grpc.StatusCode.UNAUTHENTICATED:
133
+ message = f"The hub at {address} rejected HUB_TOKEN"
134
+ case code:
135
+ message = f"The hub at {address} failed with {code.name}: {exc.details()}"
136
+ raise _error(message, exc) from exc
137
+ return response.version
138
+
139
+
140
+ def _check_version(hub_version: str, client_version: str) -> None:
141
+ if hub_version == "dev":
142
+ _LOGGER.warning("The hub reports no version, so kit cannot check that it offers what this bot calls")
143
+ return
144
+ hub = _major_minor(hub_version)
145
+ if hub is None:
146
+ raise HubError(f"The hub reported an unknown version: {hub_version!r}")
147
+ client = _major_minor(client_version)
148
+ if client is not None and hub < client:
149
+ raise HubError(
150
+ f"The hub runs {hub_version}, but this bot needs {client[0]}.{client[1]} or newer; update the hub first"
151
+ )
152
+
153
+
154
+ def _major_minor(text: str) -> tuple[int, int] | None:
155
+ match = _VERSION.match(text)
156
+ if match is None:
157
+ return None
158
+ return int(match[1]), int(match[2])
159
+
160
+
161
+ async def call_hub[T](method: str, request: Awaitable[T]) -> T:
162
+ """Await a call to the hub and raise the matching `HubError` if it fails.
163
+
164
+ For calls to a bot's own service: `await call_hub("ReportStars", stub.ReportStars(request, timeout=10))`.
165
+ """
166
+ try:
167
+ return await request
168
+ except grpc.aio.AioRpcError as exc:
169
+ raise _error(f"{method} failed with {exc.code().name}: {exc.details()}", exc) from exc
170
+
171
+
172
+ def _error(message: str, exc: grpc.aio.AioRpcError) -> HubError:
173
+ code = exc.code()
174
+ if code in _UNAVAILABLE:
175
+ return HubUnavailableError(message)
176
+ return HubRequestError(message, code=code, reason=reason_of(exc))