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: Filter out users who have joined recently in SQL.

Alex Vandiver524d4913b3d7
diff --git a/zerver/lib/digest.py b/zerver/lib/digest.py
index d7ddb424912..aeda16743be 100644
--- a/zerver/lib/digest.py
+++ b/zerver/lib/digest.py
@@ -248,13 +248,47 @@ def enough_traffic(hot_conversations: str, new_streams: int) -> bool:
return bool(hot_conversations or new_streams)
-def get_user_stream_map(user_ids: List[int]) -> Dict[int, Set[int]]:
- rows = Subscription.objects.filter(
- user_profile_id__in=user_ids,
- recipient__type=Recipient.STREAM,
- active=True,
- is_muted=False,
- ).values("user_profile_id", "recipient__type_id")
+def get_user_stream_map(user_ids: List[int], cutoff_date: datetime.datetime) -> Dict[int, Set[int]]:
+ """Skipping streams where the user's subscription status has changed
+ when constructing digests is critical to ensure correctness for
+ streams without shared history, guest users, and long-term idle
+ users, because it means that every user has the same view of the
+ history of a given stream whose message history is being included
+ (and thus we can share a lot of work).
+
+ The downside is that newly created streams are never included in
+ the first digest email after their creation. Should we wish to
+ change that, we will need to be very careful to avoid creating
+ bugs for any of those classes of users.
+ """
+ events = [
+ RealmAuditLog.SUBSCRIPTION_CREATED,
+ RealmAuditLog.SUBSCRIPTION_ACTIVATED,
+ RealmAuditLog.SUBSCRIPTION_DEACTIVATED,
+ ]
+ # This uses the zerver_realmauditlog_user_subscriptions_idx
+ # partial index on RealmAuditLog which is specifically for those
+ # three event types.
+ rows = (
+ Subscription.objects.filter(
+ user_profile_id__in=user_ids,
+ recipient__type=Recipient.STREAM,
+ active=True,
+ is_muted=False,
+ )
+ .alias(
+ was_modified=Exists(
+ RealmAuditLog.objects.filter(
+ modified_stream_id=OuterRef("recipient__type_id"),
+ modified_user_id=OuterRef("user_profile_id"),
+ event_time__gt=cutoff_date,
+ event_type__in=events,
+ )
+ )
+ )
+ .filter(was_modified=False)
+ .values("user_profile_id", "recipient__type_id")
+ )
# maps user_id -> {stream_id, stream_id, ...}
dct: Dict[int, Set[int]] = defaultdict(set)
@@ -288,16 +322,12 @@ def bulk_get_digest_context(
result: Dict[int, Dict[str, Any]] = {}
user_ids = [user.id for user in users]
-
- user_stream_map = get_user_stream_map(user_ids)
-
- recently_modified_streams = get_modified_streams(user_ids, cutoff_date)
+ user_stream_map = get_user_stream_map(user_ids, cutoff_date)
all_stream_ids = set()
for user in users:
stream_ids = user_stream_map[user.id]
- stream_ids -= recently_modified_streams.get(user.id, set())
all_stream_ids |= stream_ids
# Get all the recent topics for all the users. This does the heavy
@@ -398,45 +428,3 @@ def bulk_write_realm_audit_logs(users: List[UserProfile]) -> None:
]
RealmAuditLog.objects.bulk_create(log_rows)
-
-
-def get_modified_streams(
- user_ids: List[int], cutoff_date: datetime.datetime
-) -> Dict[int, Set[int]]:
- """Skipping streams where the user's subscription status has changed
- when constructing digests is critical to ensure correctness for
- streams without shared history, guest users, and long-term idle
- users, because it means that every user has the same view of the
- history of a given stream whose message history is being included
- (and thus we can share a lot of work).
-
- The downside is that newly created streams are never included in
- the first digest email after their creation. Should we wish to
- change that, we will need to be very careful to avoid creating
- bugs for any of those classes of users.
- """
- events = [
- RealmAuditLog.SUBSCRIPTION_CREATED,
- RealmAuditLog.SUBSCRIPTION_ACTIVATED,
- RealmAuditLog.SUBSCRIPTION_DEACTIVATED,
- ]
-
- # Get rows where the users' subscriptions have changed.
- rows = (
- RealmAuditLog.objects.filter(
- modified_user_id__in=user_ids,
- event_time__gt=cutoff_date,
- event_type__in=events,
- )
- .values("modified_user_id", "modified_stream_id")
- .distinct()
- )
-
- result: Dict[int, Set[int]] = defaultdict(set)
-
- for row in rows:
- user_id = row["modified_user_id"]
- stream_id = row["modified_stream_id"]
- result[user_id].add(stream_id)
-
- return result
diff --git a/zerver/tests/test_digest.py b/zerver/tests/test_digest.py
index f8049549ee1..0ddf0e51ecd 100644
--- a/zerver/tests/test_digest.py
+++ b/zerver/tests/test_digest.py
@@ -1,6 +1,6 @@
import datetime
import time
-from typing import List
+from typing import List, Set
from unittest import mock
from django.test import override_settings
@@ -18,8 +18,8 @@ from zerver.lib.digest import (
enqueue_emails,
gather_new_streams,
get_hot_topics,
- get_modified_streams,
get_recent_streams,
+ get_user_stream_map,
)
from zerver.lib.message import get_last_message_id
from zerver.lib.streams import create_stream_if_needed
@@ -65,7 +65,7 @@ class TestDigestEmailMessages(ZulipTestCase):
# This code is run when we call `confirmation.models.create_confirmation_link`.
# To trigger this, we call the one_click_unsubscribe_link function below.
one_click_unsubscribe_link(othello, "digest")
- with self.assert_database_query_count(9):
+ with self.assert_database_query_count(8):
bulk_handle_digest_email([othello.id], cutoff)
self.assertEqual(mock_send_future_email.call_count, 1)
@@ -141,7 +141,7 @@ class TestDigestEmailMessages(ZulipTestCase):
# This code is run when we call `confirmation.models.create_confirmation_link`.
# To trigger this, we call the one_click_unsubscribe_link function below.
one_click_unsubscribe_link(polonius, "digest")
- with self.assert_database_query_count(9):
+ with self.assert_database_query_count(8):
bulk_handle_digest_email([polonius.id], cutoff)
self.assertEqual(mock_send_future_email.call_count, 1)
@@ -202,7 +202,7 @@ class TestDigestEmailMessages(ZulipTestCase):
with mock.patch("zerver.lib.digest.send_future_email") as mock_send_future_email:
digest_user_ids = [user.id for user in digest_users]
- with self.assert_database_query_count(12):
+ with self.assert_database_query_count(11):
with self.assert_memcached_count(0):
bulk_handle_digest_email(digest_user_ids, cutoff)
@@ -242,8 +242,13 @@ class TestDigestEmailMessages(ZulipTestCase):
self.subscribe(cordelia, stream)
realm = othello.realm
- denmark = get_stream("Denmark", realm)
verona = get_stream("Verona", realm)
+ scotland = get_stream("Scotland", realm)
+ denmark = get_stream("Denmark", realm)
+
+ def user_streams(user: UserProfile) -> Set[Stream]:
+ data = get_user_stream_map([user.id], one_hour_ago)
+ return {Stream.objects.get(id=stream_id) for stream_id in data[user.id]}
two_hours_ago = timezone_now() - datetime.timedelta(hours=2)
one_hour_ago = timezone_now() - datetime.timedelta(hours=1)
@@ -251,35 +256,41 @@ class TestDigestEmailMessages(ZulipTestCase):
# Delete all RealmAuditLogs to start with a clean slate.
RealmAuditLog.objects.all().delete()
+ # Othello's map is Verona, Scotland, and Denmark
+ self.assertEqual(user_streams(othello), {verona, scotland, denmark})
+
# Unsubscribe and subscribe Othello from a stream
self.unsubscribe(othello, "Denmark")
self.subscribe(othello, "Denmark")
- recent_streams = get_modified_streams([othello.id], one_hour_ago)
- self.assertEqual(recent_streams[othello.id], {denmark.id})
+ # This drops denmark from the list of streams
+ self.assertEqual(user_streams(othello), {verona, scotland})
# Backdate all our logs (so that Denmark will no longer
# appear like a recently modified stream for Othello).
RealmAuditLog.objects.all().update(event_time=two_hours_ago)
# Now Denmark no longer appears recent to Othello.
- recent_streams = get_modified_streams([othello.id], one_hour_ago)
- self.assertEqual(recent_streams[othello.id], set())
+ self.assertEqual(user_streams(othello), {denmark, verona, scotland})
# Unsubscribe and subscribe from a stream
self.unsubscribe(othello, "Verona")
self.subscribe(othello, "Verona")
# Now, Verona, but not Denmark, appears recent.
- recent_streams = get_modified_streams([othello.id], one_hour_ago)
- self.assertEqual(recent_streams[othello.id], {verona.id})
+ self.assertEqual(user_streams(othello), {denmark, scotland})
# make sure we don't mix up Othello and Cordelia
+ streams = get_user_stream_map([othello.id, cordelia.id], one_hour_ago)
+ self.assertEqual(streams[othello.id], {scotland.id, denmark.id})
+ self.assertEqual(streams[cordelia.id], {verona.id, scotland.id, denmark.id})
+
self.unsubscribe(cordelia, "Denmark")
self.subscribe(cordelia, "Denmark")
- recent_streams = get_modified_streams([othello.id, cordelia.id], one_hour_ago)
- self.assertEqual(recent_streams[cordelia.id], {denmark.id})
+ streams = get_user_stream_map([othello.id, cordelia.id], one_hour_ago)
+ self.assertEqual(streams[othello.id], {scotland.id, denmark.id})
+ self.assertEqual(streams[cordelia.id], {verona.id, scotland.id})
def active_human_users(self, realm: Realm) -> List[UserProfile]:
users = list(