From a63d76a8649dab549e7e40f5d21abdeadd7809bf Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 09:56:40 +0100 Subject: [PATCH 1/2] Count, export and delete a person's or a guild's data --- src/librebots/kit/__init__.py | 2 + src/librebots/kit/_rpc.py | 14 ++ src/librebots/kit/guilds.py | 15 +- src/librebots/kit/privacy.py | 126 +++++++++++++ tests/hub_server.py | 31 +++ tests/test_guilds.py | 25 +-- tests/test_privacy.py | 344 ++++++++++++++++++++++++++++++++++ 7 files changed, 524 insertions(+), 33 deletions(-) create mode 100644 src/librebots/kit/_rpc.py create mode 100644 src/librebots/kit/privacy.py create mode 100644 tests/hub_server.py create mode 100644 tests/test_privacy.py diff --git a/src/librebots/kit/__init__.py b/src/librebots/kit/__init__.py index 65159dd..3c42c53 100644 --- a/src/librebots/kit/__init__.py +++ b/src/librebots/kit/__init__.py @@ -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", @@ -13,6 +14,7 @@ "GuildReporter", "Hub", "HubError", + "Privacy", "SyncResult", "connect_hub", ] diff --git a/src/librebots/kit/_rpc.py b/src/librebots/kit/_rpc.py new file mode 100644 index 0000000..eb86043 --- /dev/null +++ b/src/librebots/kit/_rpc.py @@ -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 diff --git a/src/librebots/kit/guilds.py b/src/librebots/kit/guilds.py index 7d2496c..7e02ebb 100644 --- a/src/librebots/kit/guilds.py +++ b/src/librebots/kit/guilds.py @@ -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"] @@ -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) @@ -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)) diff --git a/src/librebots/kit/privacy.py b/src/librebots/kit/privacy.py new file mode 100644 index 0000000..0d4dd4b --- /dev/null +++ b/src/librebots/kit/privacy.py @@ -0,0 +1,126 @@ +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. Every call to the hub gives up after `timeout` + seconds. + """ + + def __init__( + self, + hub: Hub, + *, + on_user_deletion: Callable[[int], Awaitable[None]] | None = None, + 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} diff --git a/tests/hub_server.py b/tests/hub_server.py new file mode 100644 index 0000000..7a12f25 --- /dev/null +++ b/tests/hub_server.py @@ -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) diff --git a/tests/test_guilds.py b/tests/test_guilds.py index 5bcaf97..4548b41 100644 --- a/tests/test_guilds.py +++ b/tests/test_guilds.py @@ -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 @@ -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: diff --git a/tests/test_privacy.py b/tests/test_privacy.py new file mode 100644 index 0000000..01ef6d4 --- /dev/null +++ b/tests/test_privacy.py @@ -0,0 +1,344 @@ +from __future__ import annotations + +import asyncio +import logging +from collections.abc import AsyncGenerator, Awaitable + +import grpc +import grpc.aio +import pytest +from hub_server import serving +from librebots.hub.v1 import privacy_pb2, privacy_pb2_grpc + +from librebots.kit import Hub, HubError, Privacy + +type Context[Request, Response] = grpc.aio.ServicerContext[Request, Awaitable[Response]] + +USER = 123456789012345678 +OTHER = 223456789012345678 +GUILD = 987654321098765432 + + +def counts(**values: int) -> list[privacy_pb2.CategoryCount]: + return [privacy_pb2.CategoryCount(category=name.replace("_", "-"), count=count) for name, count in values.items()] + + +class FakePrivacy(privacy_pb2_grpc.PrivacyServiceServicer): + def __init__(self) -> None: + self.log: list[str] = [] + self.pending: list[int] = [] + self.failing: set[str] = set() + self.stalled: set[str] = set() + self._never = asyncio.Event() + + async def _check[Request, Response](self, name: str, context: Context[Request, Response]) -> None: + if name in self.failing: + await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") + if name in self.stalled: + await self._never.wait() + + async def CountUserData( + self, + request: privacy_pb2.CountUserDataRequest, + context: Context[privacy_pb2.CountUserDataRequest, privacy_pb2.CountUserDataResponse], + ) -> privacy_pb2.CountUserDataResponse: + await self._check("count user", context) + self.log.append(f"count user {request.user_id}") + return privacy_pb2.CountUserDataResponse(categories=counts(starboard_entries=12, starboard_stars=87)) + + async def ExportUserData( + self, + request: privacy_pb2.ExportUserDataRequest, + context: Context[privacy_pb2.ExportUserDataRequest, privacy_pb2.ExportUserDataResponse], + ) -> privacy_pb2.ExportUserDataResponse: + await self._check("export user", context) + return privacy_pb2.ExportUserDataResponse( + json=f'{{"bot":"starboard","user_id":"{request.user_id}","data":{{}}}}' + ) + + async def DeleteUserData( + self, + request: privacy_pb2.DeleteUserDataRequest, + context: Context[privacy_pb2.DeleteUserDataRequest, privacy_pb2.DeleteUserDataResponse], + ) -> privacy_pb2.DeleteUserDataResponse: + await self._check("delete user", context) + self.log.append(f"delete user {request.user_id}") + if request.user_id in self.pending: + self.pending.remove(request.user_id) + return privacy_pb2.DeleteUserDataResponse(deleted=counts(starboard_entries=12)) + + async def RequestUserDeletion( + self, + request: privacy_pb2.RequestUserDeletionRequest, + context: Context[privacy_pb2.RequestUserDeletionRequest, privacy_pb2.RequestUserDeletionResponse], + ) -> privacy_pb2.RequestUserDeletionResponse: + await self._check("request deletion", context) + self.log.append(f"request deletion {request.user_id}") + if request.user_id not in self.pending: + self.pending.append(request.user_id) + return privacy_pb2.RequestUserDeletionResponse() + + async def ListPendingUserDeletions( + self, + request: privacy_pb2.ListPendingUserDeletionsRequest, + context: Context[privacy_pb2.ListPendingUserDeletionsRequest, privacy_pb2.ListPendingUserDeletionsResponse], + ) -> privacy_pb2.ListPendingUserDeletionsResponse: + await self._check("list pending", context) + deletions = [privacy_pb2.PendingUserDeletion(user_id=user_id) for user_id in self.pending] + return privacy_pb2.ListPendingUserDeletionsResponse(deletions=deletions) + + async def CountGuildData( + self, + request: privacy_pb2.CountGuildDataRequest, + context: Context[privacy_pb2.CountGuildDataRequest, privacy_pb2.CountGuildDataResponse], + ) -> privacy_pb2.CountGuildDataResponse: + await self._check("count guild", context) + self.log.append(f"count guild {request.guild_id}") + return privacy_pb2.CountGuildDataResponse(categories=counts(starboard_settings=1, starboard_entries=342)) + + async def DeleteGuildData( + self, + request: privacy_pb2.DeleteGuildDataRequest, + context: Context[privacy_pb2.DeleteGuildDataRequest, privacy_pb2.DeleteGuildDataResponse], + ) -> privacy_pb2.DeleteGuildDataResponse: + await self._check("delete guild", context) + self.log.append(f"delete guild {request.guild_id}") + return privacy_pb2.DeleteGuildDataResponse(deleted=counts(starboard_settings=1, starboard_entries=342)) + + +class Removal: + def __init__(self, log: list[str]) -> None: + self.log = log + self.started = asyncio.Event() + self.proceed = asyncio.Event() + self.proceed.set() + self.failures = 0 + self.cancelled = False + + async def __call__(self, user_id: int) -> None: + self.started.set() + try: + await self.proceed.wait() + except asyncio.CancelledError: + self.cancelled = True + raise + if self.failures: + self.failures -= 1 + raise RuntimeError("Discord refused to delete a post") + self.log.append(f"remove from discord {user_id}") + + +@pytest.fixture +async def hub() -> AsyncGenerator[tuple[Hub, FakePrivacy]]: + fake = FakePrivacy() + async with serving(lambda server: privacy_pb2_grpc.add_PrivacyServiceServicer_to_server(fake, server)) as hub: + yield hub, fake + + +async def test_counts_what_is_stored_about_a_user(hub: tuple[Hub, FakePrivacy]) -> None: + privacy, fake = Privacy(hub[0]), hub[1] + + assert await privacy.count_user(USER) == {"starboard-entries": 12, "starboard-stars": 87} + assert fake.log == [f"count user {USER}"] + + +async def test_exports_the_json_of_the_hub_unchanged(hub: tuple[Hub, FakePrivacy]) -> None: + exported = await Privacy(hub[0]).export_user(USER) + + assert exported == f'{{"bot":"starboard","user_id":"{USER}","data":{{}}}}' + + +async def test_counts_and_deletes_what_is_stored_about_a_guild(hub: tuple[Hub, FakePrivacy]) -> None: + privacy, fake = Privacy(hub[0]), hub[1] + + assert await privacy.count_guild(GUILD) == {"starboard-settings": 1, "starboard-entries": 342} + assert await privacy.delete_guild(GUILD) == {"starboard-settings": 1, "starboard-entries": 342} + assert fake.log == [f"count guild {GUILD}", f"delete guild {GUILD}"] + + +@pytest.mark.parametrize("call", ["count user", "export user", "count guild", "delete guild", "request deletion"]) +async def test_raises_hub_error_when_the_hub_fails(hub: tuple[Hub, FakePrivacy], call: str) -> None: + privacy, fake = Privacy(hub[0]), hub[1] + fake.failing.add(call) + + with pytest.raises(HubError, match="UNAVAILABLE"): + match call: + case "count user": + await privacy.count_user(USER) + case "export user": + await privacy.export_user(USER) + case "count guild": + await privacy.count_guild(GUILD) + case "delete guild": + await privacy.delete_guild(GUILD) + case _: + await privacy.delete_user(USER) + + +async def test_gives_up_on_a_hub_that_does_not_answer(hub: tuple[Hub, FakePrivacy]) -> None: + privacy, fake = Privacy(hub[0], timeout=0.2), hub[1] + fake.stalled.add("count user") + + with pytest.raises(HubError, match="DEADLINE_EXCEEDED"): + await privacy.count_user(USER) + + +async def test_deletes_a_user_after_removing_what_the_bot_keeps_on_discord(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + privacy = Privacy(hub[0], on_user_deletion=Removal(fake.log)) + + await privacy.delete_user(USER) + async with asyncio.timeout(5): + await privacy.wait_for_deletions() + + assert fake.log == [f"request deletion {USER}", f"remove from discord {USER}", f"delete user {USER}"] + assert fake.pending == [] + + +async def test_deletes_a_user_directly_without_a_removal_step(hub: tuple[Hub, FakePrivacy]) -> None: + privacy, fake = Privacy(hub[0]), hub[1] + + await privacy.delete_user(USER) + async with asyncio.timeout(5): + await privacy.wait_for_deletions() + + assert fake.log == [f"request deletion {USER}", f"delete user {USER}"] + + +async def test_returns_once_the_deletion_is_recorded(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + removal = Removal(fake.log) + removal.proceed.clear() + privacy = Privacy(hub[0], on_user_deletion=removal) + + await privacy.delete_user(USER) + + assert fake.pending == [USER] + async with asyncio.timeout(5): + await removal.started.wait() + removal.proceed.set() + await privacy.wait_for_deletions() + assert fake.pending == [] + + +async def test_starts_no_work_when_the_request_cannot_be_recorded(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + removal = Removal(fake.log) + privacy = Privacy(hub[0], on_user_deletion=removal) + fake.failing.add("request deletion") + + with pytest.raises(HubError): + await privacy.delete_user(USER) + await privacy.wait_for_deletions() + + assert not removal.started.is_set() + assert fake.log == [] + + +async def test_runs_one_deletion_per_user_at_a_time(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + removal = Removal(fake.log) + removal.proceed.clear() + privacy = Privacy(hub[0], on_user_deletion=removal) + + async with asyncio.timeout(5): + await privacy.delete_user(USER) + await removal.started.wait() + await privacy.delete_user(USER) + removal.proceed.set() + await privacy.wait_for_deletions() + + assert fake.log.count(f"remove from discord {USER}") == 1 + assert fake.log.count(f"delete user {USER}") == 1 + + +async def test_keeps_a_failed_deletion_pending_and_logs_it( + hub: tuple[Hub, FakePrivacy], caplog: pytest.LogCaptureFixture +) -> None: + fake = hub[1] + removal = Removal(fake.log) + removal.failures = 1 + privacy = Privacy(hub[0], on_user_deletion=removal) + + with caplog.at_level(logging.WARNING, logger="librebots.kit"): + await privacy.delete_user(USER) + async with asyncio.timeout(5): + await privacy.wait_for_deletions() + + assert fake.pending == [USER] + assert f"delete user {USER}" not in fake.log + assert str(USER) in caplog.text + + +async def test_keeps_the_deletion_pending_when_the_hub_fails_to_delete(hub: tuple[Hub, FakePrivacy]) -> None: + privacy, fake = Privacy(hub[0]), hub[1] + fake.failing.add("delete user") + + await privacy.delete_user(USER) + async with asyncio.timeout(5): + await privacy.wait_for_deletions() + + assert fake.pending == [USER] + + +async def test_resumes_the_pending_deletions(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + fake.pending = [USER, OTHER] + privacy = Privacy(hub[0], on_user_deletion=Removal(fake.log)) + + started = await privacy.resume_deletions() + async with asyncio.timeout(5): + await privacy.wait_for_deletions() + + assert started == 2 + assert fake.pending == [] + assert {f"delete user {USER}", f"delete user {OTHER}"} <= set(fake.log) + + +async def test_resumes_a_deletion_that_failed_before(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + removal = Removal(fake.log) + removal.failures = 1 + privacy = Privacy(hub[0], on_user_deletion=removal) + + await privacy.delete_user(USER) + async with asyncio.timeout(5): + await privacy.wait_for_deletions() + await privacy.resume_deletions() + await privacy.wait_for_deletions() + + assert fake.pending == [] + assert fake.log[-1] == f"delete user {USER}" + + +async def test_does_not_resume_a_deletion_that_is_running(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + removal = Removal(fake.log) + removal.proceed.clear() + privacy = Privacy(hub[0], on_user_deletion=removal) + + async with asyncio.timeout(5): + await privacy.delete_user(USER) + await removal.started.wait() + started = await privacy.resume_deletions() + removal.proceed.set() + await privacy.wait_for_deletions() + + assert started == 0 + assert fake.log.count(f"delete user {USER}") == 1 + + +async def test_close_stops_running_deletions_and_leaves_them_pending(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + removal = Removal(fake.log) + removal.proceed.clear() + privacy = Privacy(hub[0], on_user_deletion=removal) + + async with asyncio.timeout(5): + await privacy.delete_user(USER) + await removal.started.wait() + await privacy.close() + + assert removal.cancelled + assert fake.pending == [USER] + assert f"delete user {USER}" not in fake.log From b60ad878a760272a445a900c33323632be81abc0 Mon Sep 17 00:00:00 2001 From: Christopher Date: Fri, 27 Nov 2026 10:51:45 +0100 Subject: [PATCH 2/2] Say that the removal step must tolerate running again --- src/librebots/kit/privacy.py | 5 +++-- tests/test_privacy.py | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/librebots/kit/privacy.py b/src/librebots/kit/privacy.py index 0d4dd4b..1b10a16 100644 --- a/src/librebots/kit/privacy.py +++ b/src/librebots/kit/privacy.py @@ -28,8 +28,9 @@ class Privacy: 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. Every call to the hub gives up after `timeout` - seconds. + 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__( diff --git a/tests/test_privacy.py b/tests/test_privacy.py index 01ef6d4..06fdd23 100644 --- a/tests/test_privacy.py +++ b/tests/test_privacy.py @@ -342,3 +342,23 @@ async def test_close_stops_running_deletions_and_leaves_them_pending(hub: tuple[ assert removal.cancelled assert fake.pending == [USER] assert f"delete user {USER}" not in fake.log + + +async def test_runs_the_removal_again_when_the_hub_failed_after_it(hub: tuple[Hub, FakePrivacy]) -> None: + fake = hub[1] + privacy = Privacy(hub[0], on_user_deletion=Removal(fake.log)) + fake.failing.add("delete user") + + async with asyncio.timeout(5): + await privacy.delete_user(USER) + await privacy.wait_for_deletions() + fake.failing.clear() + await privacy.resume_deletions() + await privacy.wait_for_deletions() + + assert fake.log == [ + f"request deletion {USER}", + f"remove from discord {USER}", + f"remove from discord {USER}", + f"delete user {USER}", + ]