Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

digest: Fix digest email context generation timing out.

Prakhar Pratyush037efd79c5ae
diff --git a/zerver/lib/digest.py b/zerver/lib/digest.py
index 80dc2edda2f..498b14887e6 100644
--- a/zerver/lib/digest.py
+++ b/zerver/lib/digest.py
@@ -293,9 +293,36 @@ def gather_new_streams(
return len(new_streams), {"html": channels_html, "plain": channels_plain}
-def get_new_messages_count(user: UserProfile, threshold: datetime) -> int:
+def get_min_recent_message_id(realm_id: int, threshold: datetime) -> int | None:
+ # ID of the realm's earliest message at or after the threshold,
+ # or None if there are none.
+ return (
+ # Uses index: zerver_message_realm_date_sent
+ Message.objects.filter(realm_id=realm_id, date_sent__gte=threshold)
+ .order_by("date_sent")
+ .values_list("id", flat=True)
+ .first()
+ )
+
+
+def get_new_messages_count(user: UserProfile, min_recent_message_id: int | None) -> int:
+ if min_recent_message_id is None:
+ # No message was sent since the threshold.
+ return 0
+
+ # We filter on `message_id` for performance, so the planner drives
+ # from the unique (user_profile_id, message_id) index on `UserMessage`.
+ #
+ # Since we want "messages the user received since threshold",
+ # the intuition is to filter on `user_profile` and `message__date_sent`.
+ # When filtering without `message_id`, the planner drives from Message's
+ # `date_sent` index, which is not scoped to a user: it reads every message
+ # sent since threshold and joins against all UserMessage rows for the user
+ # to determine whether they received each message - which is too slow.
count = UserMessage.objects.filter(
- user_profile=user, message__date_sent__gte=threshold, message__sender__is_bot=False
+ user_profile=user,
+ message_id__gte=min_recent_message_id,
+ message__sender__is_bot=False,
).count()
return count
@@ -404,6 +431,12 @@ def bulk_get_digest_context(
stream_id_map = get_slim_stream_id_map(stream_ids)
user_muted_topics_map = get_user_muted_topics_map(user_ids)
+ # ID of the realm's earliest message at or after the `cutoff`.
+ # Shared across all users, and computed lazily since it is only
+ # needed for users who have message content hidden in emails.
+ min_recent_message_id: int | None = None
+ have_min_recent_message_id = False
+
for user in users:
context = common_context(user)
@@ -428,7 +461,10 @@ def bulk_get_digest_context(
if not message_content_allowed_in_missedmessage_emails(user):
# Count new messages when message content is hidden in email notifications.
- context["new_messages_count"] = get_new_messages_count(user, cutoff_date)
+ if not have_min_recent_message_id:
+ min_recent_message_id = get_min_recent_message_id(realm.id, cutoff_date)
+ have_min_recent_message_id = True
+ context["new_messages_count"] = get_new_messages_count(user, min_recent_message_id)
context["hot_conversations"] = []
context["show_message_content"] = False
else:
diff --git a/zerver/tests/test_digest.py b/zerver/tests/test_digest.py
index 3c07a00d5e2..486c301ce5b 100644
--- a/zerver/tests/test_digest.py
+++ b/zerver/tests/test_digest.py
@@ -20,6 +20,7 @@ from zerver.lib.digest import (
enqueue_emails,
gather_new_streams,
get_hot_topics,
+ get_min_recent_message_id,
get_new_messages_count,
get_recent_topics,
get_recently_created_streams,
@@ -617,12 +618,19 @@ class TestDigestEmailMessages(ZulipTestCase):
self.subscribe(othello, "Verona")
cutoff = timezone_now() - timedelta(days=5)
+ # No message sent since the cutoff.
+ min_recent_message_id = get_min_recent_message_id(othello.realm_id, cutoff)
+ self.assertIsNone(min_recent_message_id)
+ self.assertEqual(get_new_messages_count(othello, min_recent_message_id), 0)
+
senders = ["hamlet", "cordelia", "default_bot"]
# Exclude messages sent by bots from digests, as only human messages should be considered.
new_messages_count = len(self.simulate_stream_conversation("Verona", senders)) - 1
+ min_recent_message_id = get_min_recent_message_id(othello.realm_id, cutoff)
+ self.assertIsNotNone(min_recent_message_id)
self.assertEqual(
- get_new_messages_count(othello, cutoff),
+ get_new_messages_count(othello, min_recent_message_id),
new_messages_count,
)
@@ -660,7 +668,7 @@ class TestDigestEmailMessages(ZulipTestCase):
one_click_unsubscribe_link(othello, "digest")
# Clear the LRU cache on the stream topics
get_recent_topics.cache_clear()
- with self.assert_database_query_count(9):
+ with self.assert_database_query_count(10):
bulk_handle_digest_email([othello.id], cutoff)
self.assertEqual(mock_send_future_email.call_count, 1)
@@ -673,7 +681,7 @@ class TestDigestEmailMessages(ZulipTestCase):
stream.date_created = timezone_now() - timedelta(days=3)
stream.save()
- with self.assert_database_query_count(9):
+ with self.assert_database_query_count(10):
bulk_handle_digest_email([othello.id], cutoff)
self.assertEqual(mock_send_future_email.call_count, 2)