Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
retention: Send events about message deletion via retention policy.
Mateusz Manderab165d2cc28a2
diff --git a/zerver/actions/message_delete.py b/zerver/actions/message_delete.pyindex d3ac9d91879..34182e09932 100644--- a/zerver/actions/message_delete.py+++ b/zerver/actions/message_delete.py@@ -1,10 +1,8 @@-from collections import defaultdictfrom collections.abc import Iterablefrom typing import TypedDict-from zerver.actions.message_flags import do_clear_mobile_push_notifications_for_idsfrom zerver.lib import retention-from zerver.lib.retention import _process_grouped_messages_deletion, move_messages_to_archive+from zerver.lib.retention import move_messages_to_archivefrom zerver.models import Message, Realm, Stream, UserProfilefrom zerver.tornado.django_api import send_event_on_commit@@ -56,40 +54,13 @@ def do_delete_messages(When the Recipient.PERSONAL is no longer a case to consider, thisrestriction can be deleted."""- message_ids = []- private_messages_by_recipient: defaultdict[int, list[Message]] = defaultdict(list)- stream_messages_by_recipient_and_topic: defaultdict[tuple[int, str], list[Message]] = (- defaultdict(list)+ message_ids = [message.id for message in messages]+ move_messages_to_archive(+ message_ids,+ realm=realm,+ chunk_size=retention.STREAM_MESSAGE_BATCH_SIZE,+ acting_user=acting_user,)- stream_by_recipient_id = {}- for message in messages:- message_ids.append(message.id)- if message.is_channel_message:- recipient_id = message.recipient_id- # topics are case-insensitive.- topic_name = message.topic_name().lower()- stream_messages_by_recipient_and_topic[(recipient_id, topic_name)].append(message)- else:- recipient_id = message.recipient.id- private_messages_by_recipient[recipient_id].append(message)-- do_clear_mobile_push_notifications_for_ids(user_profile_ids=None, message_ids=message_ids)-- for recipient_id, grouped_messages in sorted(private_messages_by_recipient.items()):- _process_grouped_messages_deletion(- realm, grouped_messages, stream=None, topic=None, acting_user=acting_user- )-- for (- (recipient_id, topic_name),- grouped_messages,- ) in sorted(stream_messages_by_recipient_and_topic.items()):- if recipient_id not in stream_by_recipient_id:- stream_by_recipient_id[recipient_id] = Stream.objects.get(recipient_id=recipient_id)- stream = stream_by_recipient_id[recipient_id]- _process_grouped_messages_deletion(- realm, grouped_messages, stream=stream, topic=topic_name, acting_user=acting_user- )def do_delete_messages_by_sender(user: UserProfile) -> None:diff --git a/zerver/lib/retention.py b/zerver/lib/retention.pyindex 81fa7c36ad8..377c66839b7 100644--- a/zerver/lib/retention.py+++ b/zerver/lib/retention.py@@ -33,14 +33,19 @@ from datetime import timedeltafrom typing import Anyfrom django.conf import settings+from django.contrib.postgres.aggregates import ArrayAggfrom django.db import connection, transaction-from django.db.models import Model+from django.db.models import Case, CharField, Model, Value, When+from django.db.models.functions import Upperfrom django.utils.timezone import now as timezone_nowfrom psycopg2.sql import SQL, Composable, Identifier, Literal+from zerver.actions.message_flags import do_clear_mobile_push_notifications_for_idsfrom zerver.lib.logging_util import log_to_filefrom zerver.lib.message import event_recipient_ids_for_action_on_messagesfrom zerver.lib.request import RequestVariableConversionError+from zerver.lib.topic import DB_TOPIC_NAME+from zerver.lib.utils import assert_is_not_nonefrom zerver.models import (ArchivedAttachment,ArchivedReaction,@@ -128,6 +133,7 @@ def run_archiving(type: int,realm: Realm,chunk_size: int | None = MESSAGE_BATCH_SIZE,+ acting_user: UserProfile | None = None,**kwargs: Composable,) -> int:# This function is carefully designed to achieve our@@ -156,7 +162,7 @@ def run_archiving()if new_chunk:move_related_objects_to_archive(new_chunk)- delete_messages(new_chunk)+ delete_messages(new_chunk, realm, acting_user=acting_user)message_count += len(new_chunk)else:archive_transaction.delete() # Nothing was archived@@ -322,18 +328,17 @@ def move_attachment_messages_to_archive(msg_ids: list[int]) -> None:def _process_grouped_messages_deletion(realm: Realm,- grouped_messages: list[Message],+ message_ids: list[int],*,stream: Stream | None,topic: str | None,acting_user: UserProfile | None,) -> None:"""- Helper for do_delete_messages. Should not be called directly otherwise.+ Helper for delete_messages. Should not be called directly otherwise."""from zerver.actions.message_delete import DeleteMessagesEvent, check_update_first_message_id- message_ids = [message.id for message in grouped_messages]if not message_ids:return # nocoverage@@ -344,13 +349,11 @@ def _process_grouped_messages_deletion(if stream is None:assert topic is Nonemessage_type = "private"- archiving_chunk_size = MESSAGE_BATCH_SIZEelse:assert topic is not Nonemessage_type = "stream"event["stream_id"] = stream.idevent["topic"] = topic- archiving_chunk_size = STREAM_MESSAGE_BATCH_SIZEevent["message_type"] = message_type# We exclude long-term idle users, since they by definition have no active clients.@@ -364,21 +367,73 @@ def _process_grouped_messages_deletion(# Always send event to the user who deleted the message.users_to_notify.add(acting_user.id)- move_messages_to_archive(message_ids, realm=realm, chunk_size=archiving_chunk_size)+ # Uses index: zerver_message_pkey+ Message.objects.filter(id__in=message_ids).delete()+if stream is not None:check_update_first_message_id(realm, stream, message_ids, users_to_notify)send_event_on_commit(realm, event, users_to_notify)-def delete_messages(msg_ids: list[int]) -> None:+def delete_messages(+ msg_ids: list[int], realm: Realm, acting_user: UserProfile | None = None+) -> None:# Important note: This also deletes related objects with a foreign# key to Message (due to `on_delete=CASCADE` in our models# configuration), so we need to be sure we've taken care of# archiving the messages before doing this step.- #- # Uses index: zerver_message_pkey- Message.objects.filter(id__in=msg_ids).delete()++ # Besides deleting messages, this function needs to send out message deletion events.+ # This requires grouping the messages per (channel, topic) for channel messages+ # and per conversation for DMs.+ # Message archiving through retention policy can involve large numbers of messages,+ # so we care about performance here and thus prefer to offload this work to the database+ # instead of running loops in Python.+ query = (+ Message.objects.filter(id__in=msg_ids)+ .annotate(+ group_topic=Case(+ When(is_channel_message=True, then=Upper(DB_TOPIC_NAME)),+ default=Value(None),+ output_field=CharField(),+ )+ )+ .values("recipient_id", "group_topic")+ .annotate(message_ids=ArrayAgg("id", order_by="id"))+ )++ grouped_message_ids: dict[tuple[int, str | None], list[int]] = {}+ unique_recipient_ids: set[int] = {+ row["recipient_id"] for row in query if row["group_topic"] is not None+ }+ recipient_id_to_stream: dict[int, Stream] = {+ assert_is_not_none(stream.recipient_id): stream+ for stream in Stream.objects.filter(recipient_id__in=unique_recipient_ids)+ }+ for row in query:+ recipient_id = row["recipient_id"]+ topic = row["group_topic"]+ key = (recipient_id, topic)+ grouped_message_ids[key] = row["message_ids"]++ do_clear_mobile_push_notifications_for_ids(user_profile_ids=None, message_ids=msg_ids)++ for (recipient_id, topic), message_ids in grouped_message_ids.items():+ if topic is not None:+ topic_name = topic.lower()+ stream = recipient_id_to_stream[recipient_id]+ else:+ topic_name = None+ stream = None++ _process_grouped_messages_deletion(+ realm,+ message_ids,+ stream=stream,+ topic=topic_name,+ acting_user=acting_user,+ )def delete_expired_attachments(realm: Realm) -> None:@@ -510,7 +565,10 @@ def get_realms_and_streams_for_archiving() -> list[tuple[Realm, list[Stream]]]:def move_messages_to_archive(- message_ids: list[int], realm: Realm, chunk_size: int = MESSAGE_BATCH_SIZE+ message_ids: list[int],+ realm: Realm,+ chunk_size: int = MESSAGE_BATCH_SIZE,+ acting_user: UserProfile | None = None,) -> None:"""Callers using this to archive a large amount of messages should ideally make sure the message_ids are@@ -543,6 +601,7 @@ def move_messages_to_archive(message_ids=Literal(tuple(message_ids_chunk)),realm=realm,chunk_size=None,+ acting_user=acting_user,)# Clean up attachments:archived_attachments = ArchivedAttachment.objects.filter(diff --git a/zerver/tests/test_message_delete.py b/zerver/tests/test_message_delete.pyindex 3fa45324ebf..ae18f51ea06 100644--- a/zerver/tests/test_message_delete.py+++ b/zerver/tests/test_message_delete.py@@ -915,7 +915,7 @@ class DeleteMessageTest(ZulipTestCase):self.assertEqual(stream.first_message_id, message_ids[1])all_messages = Message.objects.filter(id__in=message_ids)- with self.assert_database_query_count(25):+ with self.assert_database_query_count(26):do_delete_messages(realm, all_messages, acting_user=None)stream = get_stream(stream_name, realm)self.assertEqual(stream.first_message_id, None)diff --git a/zerver/tests/test_retention.py b/zerver/tests/test_retention.pyindex 3bb3ae174d8..f5cbc1b8d75 100644--- a/zerver/tests/test_retention.py+++ b/zerver/tests/test_retention.py@@ -1127,7 +1127,7 @@ class TestDoDeleteMessages(ZulipTestCase):message_ids = [self.send_stream_message(cordelia, "Verona", str(i)) for i in range(10)]messages = Message.objects.filter(id__in=message_ids)- with self.assert_database_query_count(23):+ with self.assert_database_query_count(24):do_delete_messages(realm, messages, acting_user=None)self.assertFalse(Message.objects.filter(id__in=message_ids).exists())