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: 2 additions & 0 deletions src/librebots/kit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
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.privacy import Privacy

__all__ = [
"Catalog",
Expand All @@ -13,6 +14,7 @@
"GuildReporter",
"Hub",
"HubError",
"Privacy",
"SyncResult",
"connect_hub",
]
14 changes: 14 additions & 0 deletions src/librebots/kit/_rpc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from __future__ import annotations

from collections.abc import Awaitable

import grpc.aio

from librebots.kit.hub import HubError


async def call[T](method: str, request: Awaitable[T]) -> T:
try:
return await request
except grpc.aio.AioRpcError as exc:
raise HubError(f"{method} failed with {exc.code().name}: {exc.details()}") from exc
15 changes: 4 additions & 11 deletions src/librebots/kit/guilds.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
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._rpc import call
from librebots.kit.hub import Hub, HubError

__all__ = ["GuildReporter", "SyncResult"]
Expand Down Expand Up @@ -67,7 +67,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("SyncGuilds", self._hub.guilds.SyncGuilds(request, timeout=self._timeout))
await self._report_again()
return SyncResult(joined=response.joined, left=response.left)

Expand All @@ -94,16 +94,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("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
await call("GuildLeft", self._hub.guilds.GuildLeft(request, timeout=self._timeout))
127 changes: 127 additions & 0 deletions src/librebots/kit/privacy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
from __future__ import annotations

import asyncio
import logging
from collections.abc import Awaitable, Callable, Iterable

from librebots.hub.v1.privacy_pb2 import (
CategoryCount,
CountGuildDataRequest,
CountUserDataRequest,
DeleteGuildDataRequest,
DeleteUserDataRequest,
ExportUserDataRequest,
ListPendingUserDeletionsRequest,
RequestUserDeletionRequest,
)

from librebots.kit._rpc import call
from librebots.kit.hub import Hub

__all__ = ["Privacy"]

_LOGGER = logging.getLogger(__name__)


class Privacy:
"""Counts, exports and deletes what the bot stores in the hub about a person or a guild.

Deleting a person's data runs in the background and survives a restart: the hub records the request first, then
`on_user_deletion` removes what the bot keeps on Discord for that person, then the hub deletes the rest. A deletion
that fails stays pending, and `resume_deletions` starts it again. `on_user_deletion` can therefore run several
times for one person, also after an earlier run removed some or all of it, and must succeed when nothing is left
to remove. Every call to the hub gives up after `timeout` seconds.
"""

def __init__(
self,
hub: Hub,
*,
on_user_deletion: Callable[[int], Awaitable[None]] | None = None,
Comment thread
rayakame marked this conversation as resolved.
Resolved
timeout: float = 30,
) -> None:
self._hub = hub
self._on_user_deletion = on_user_deletion
self._timeout = timeout
self._deletions: dict[int, asyncio.Task[None]] = {}

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))
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))
return response.json

async def delete_user(self, user_id: int) -> None:
"""Record that a person's data is to be deleted and start deleting it in the background.

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))
self._start(user_id)

async def resume_deletions(self) -> int:
"""Start every pending deletion that is not running yet and return how many it started.

Raises `HubError` if the hub fails.
"""
request = ListPendingUserDeletionsRequest()
response = await call(
"ListPendingUserDeletions", self._hub.privacy.ListPendingUserDeletions(request, timeout=self._timeout)
)
return sum(self._start(deletion.user_id) for deletion in response.deletions)

async def wait_for_deletions(self) -> None:
"""Wait until every running deletion has finished or failed."""
while self._deletions:
await asyncio.wait(list(self._deletions.values()))

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))
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))
return _by_category(response.deleted)

async def close(self) -> None:
"""Stop the running deletions; they stay pending in the hub."""
tasks = list(self._deletions.values())
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)

def _start(self, user_id: int) -> bool:
if user_id in self._deletions:
return False
task = asyncio.create_task(self._delete(user_id), name=f"delete the data of user {user_id}")
self._deletions[user_id] = task
task.add_done_callback(lambda done: self._forget(user_id, done))
return True

def _forget(self, user_id: int, task: asyncio.Task[None]) -> None:
if self._deletions.get(user_id) is task:
del self._deletions[user_id]

async def _delete(self, user_id: int) -> None:
try:
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))
except Exception:
_LOGGER.exception("Deleting the data of user %s failed; it stays pending and is tried again later", user_id)


def _by_category(categories: Iterable[CategoryCount]) -> dict[str, int]:
return {category.category: category.count for category in categories}
31 changes: 31 additions & 0 deletions tests/hub_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from __future__ import annotations

from collections.abc import AsyncGenerator, Callable
from contextlib import asynccontextmanager

import grpc.aio
from librebots.hub.v1.guilds_pb2_grpc import GuildServiceStub
from librebots.hub.v1.privacy_pb2_grpc import PrivacyServiceStub
from librebots.hub.v1.stats_pb2_grpc import StatsServiceStub

from librebots.kit import Hub


@asynccontextmanager
async def serving(register: Callable[[grpc.aio.Server], None]) -> AsyncGenerator[Hub]:
server = grpc.aio.server()
register(server)
port = server.add_insecure_port("127.0.0.1:0")
await server.start()
channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
try:
yield Hub(
channel=channel,
version="test",
guilds=GuildServiceStub(channel),
privacy=PrivacyServiceStub(channel),
stats=StatsServiceStub(channel),
)
finally:
await channel.close()
await server.stop(0)
25 changes: 3 additions & 22 deletions tests/test_guilds.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@
import grpc.aio
import hikari
import pytest
from hub_server import serving
from librebots.hub.v1 import guilds_pb2, guilds_pb2_grpc
from librebots.hub.v1.guilds_pb2_grpc import GuildServiceStub
from librebots.hub.v1.privacy_pb2_grpc import PrivacyServiceStub
from librebots.hub.v1.stats_pb2_grpc import StatsServiceStub

from librebots.kit import GuildReporter, Hub, HubError, SyncResult

Expand Down Expand Up @@ -100,25 +98,8 @@ async def _guilds(self) -> AsyncIterator[hikari.OwnGuild]:
async def hub() -> AsyncGenerator[tuple[Hub, FakeGuilds]]:
# The fake answers only the calls guild reporting makes.
fake = FakeGuilds() # pyright: ignore[reportAbstractUsage]
server = grpc.aio.server()
guilds_pb2_grpc.add_GuildServiceServicer_to_server(fake, server)
port = server.add_insecure_port("127.0.0.1:0")
await server.start()
channel = grpc.aio.insecure_channel(f"127.0.0.1:{port}")
try:
yield (
Hub(
channel=channel,
version="test",
guilds=GuildServiceStub(channel),
privacy=PrivacyServiceStub(channel),
stats=StatsServiceStub(channel),
),
fake,
)
finally:
await channel.close()
await server.stop(0)
async with serving(lambda server: guilds_pb2_grpc.add_GuildServiceServicer_to_server(fake, server)) as hub:
yield hub, fake


async def test_reports_a_join_and_returns_the_language(hub: tuple[Hub, FakeGuilds]) -> None:
Expand Down
Loading