Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
user_topics: Update 'set visibility policy' codepath for bulk db operations.
Prakhar Pratyush60762a750bc6
diff --git a/zerver/actions/user_topics.py b/zerver/actions/user_topics.pyindex a7aa45712a5..e454e52194b 100644--- a/zerver/actions/user_topics.py+++ b/zerver/actions/user_topics.py@@ -1,19 +1,19 @@import datetime-from typing import Any, Dict, Optional+from typing import Any, Dict, List, Optionalfrom django.utils.timezone import now as timezone_nowfrom zerver.lib.timestamp import datetime_to_timestampfrom zerver.lib.user_topics import (+ bulk_set_user_topic_visibility_policy_in_database,get_topic_mutes,- set_user_topic_visibility_policy_in_database,)from zerver.models import Stream, UserProfilefrom zerver.tornado.django_api import send_event-def do_set_user_topic_visibility_policy(- user_profile: UserProfile,+def bulk_do_set_user_topic_visibility_policy(+ user_profiles: List[UserProfile],stream: Stream,topic: str,*,@@ -24,8 +24,8 @@ def do_set_user_topic_visibility_policy(if last_updated is None:last_updated = timezone_now()- database_changed = set_user_topic_visibility_policy_in_database(- user_profile,+ user_profiles_with_changed_user_topic_rows = bulk_set_user_topic_visibility_policy_in_database(+ user_profiles,stream.id,topic,visibility_policy=visibility_policy,@@ -33,25 +33,50 @@ def do_set_user_topic_visibility_policy(last_updated=last_updated,)- # Requests to set the visibility_policy to its current value+ # Users with requests to set the visibility_policy to its current value# or to delete a UserTopic row that doesn't exist shouldn't# send an unnecessary event.- if not database_changed:+ if len(user_profiles_with_changed_user_topic_rows) == 0:return- # This first muted_topics event is deprecated and will be removed- # once clients are migrated to handle the user_topic event type- # instead.- if not skip_muted_topics_event:- muted_topics_event = dict(type="muted_topics", muted_topics=get_topic_mutes(user_profile))- send_event(user_profile.realm, muted_topics_event, [user_profile.id])-- user_topic_event: Dict[str, Any] = {- "type": "user_topic",- "stream_id": stream.id,- "topic_name": topic,- "last_updated": datetime_to_timestamp(last_updated),- "visibility_policy": visibility_policy,- }-- send_event(user_profile.realm, user_topic_event, [user_profile.id])+ for user_profile in user_profiles_with_changed_user_topic_rows:+ # This first muted_topics event is deprecated and will be removed+ # once clients are migrated to handle the user_topic event type+ # instead.+ if not skip_muted_topics_event:+ muted_topics_event = dict(+ type="muted_topics", muted_topics=get_topic_mutes(user_profile)+ )+ send_event(user_profile.realm, muted_topics_event, [user_profile.id])++ user_topic_event: Dict[str, Any] = {+ "type": "user_topic",+ "stream_id": stream.id,+ "topic_name": topic,+ "last_updated": datetime_to_timestamp(last_updated),+ "visibility_policy": visibility_policy,+ }++ send_event(user_profile.realm, user_topic_event, [user_profile.id])+++def do_set_user_topic_visibility_policy(+ user_profile: UserProfile,+ stream: Stream,+ topic: str,+ *,+ visibility_policy: int,+ last_updated: Optional[datetime.datetime] = None,+ skip_muted_topics_event: bool = False,+) -> None:+ # For conciseness, this function should be used when a single+ # user_profile is involved. In the case of multiple user profiles,+ # call 'bulk_do_set_user_topic_visibility_policy' directly.+ bulk_do_set_user_topic_visibility_policy(+ [user_profile],+ stream,+ topic,+ visibility_policy=visibility_policy,+ last_updated=last_updated,+ skip_muted_topics_event=skip_muted_topics_event,+ )diff --git a/zerver/lib/user_topics.py b/zerver/lib/user_topics.pyindex 9570e95d1f3..1f6eba70af8 100644--- a/zerver/lib/user_topics.py+++ b/zerver/lib/user_topics.py@@ -98,8 +98,8 @@ def set_topic_visibility_policy(recipient_id = stream.recipient_idassert recipient_id is not None- set_user_topic_visibility_policy_in_database(- user_profile=user_profile,+ bulk_set_user_topic_visibility_policy_in_database(+ user_profiles=[user_profile],stream_id=stream.id,recipient_id=recipient_id,topic_name=topic_name,@@ -109,63 +109,72 @@ def set_topic_visibility_policy(@transaction.atomic(savepoint=False)-def set_user_topic_visibility_policy_in_database(- user_profile: UserProfile,+def bulk_set_user_topic_visibility_policy_in_database(+ user_profiles: List[UserProfile],stream_id: int,topic_name: str,*,visibility_policy: int,recipient_id: Optional[int] = None,last_updated: Optional[datetime.datetime] = None,-) -> bool:- # returns True if it modifies the database and False otherwise.+) -> List[UserProfile]:+ # returns the list of user_profiles whose user_topic row+ # is either deleted, updated, or created.+ rows = UserTopic.objects.filter(+ user_profile__in=user_profiles,+ stream_id=stream_id,+ topic_name__iexact=topic_name,+ ).select_related("user_profile", "user_profile__realm")++ user_profiles_with_visibility_policy = [row.user_profile for row in rows]+ user_profiles_without_visibility_policy = list(+ set(user_profiles) - set(user_profiles_with_visibility_policy)+ )+if visibility_policy == UserTopic.VisibilityPolicy.INHERIT:- (num_deleted, ignored) = UserTopic.objects.filter(- user_profile=user_profile,- stream_id=stream_id,- topic_name__iexact=topic_name,- ).delete()- if num_deleted == 0:- # If the user doesn't already have a visibility_policy for this topic+ for user_profile in user_profiles_without_visibility_policy:+ # The user doesn't already have a visibility_policy for this topic.logging.info("User %s tried to remove visibility_policy, which actually doesn't exist",user_profile.id,)- return False- return True+ rows.delete()+ return user_profiles_with_visibility_policyassert last_updated is not Noneassert recipient_id is not None- (row, created) = UserTopic.objects.get_or_create(- user_profile=user_profile,- stream_id=stream_id,- topic_name__iexact=topic_name,- recipient_id=recipient_id,- defaults={- "topic_name": topic_name,- "last_updated": last_updated,- "visibility_policy": visibility_policy,- },- )- if created:- return True-- duplicate_request: bool = row.visibility_policy == visibility_policy+ user_profiles_seeking_visibility_policy_update: List[UserProfile] = []+ for row in rows:+ duplicate_request: bool = row.visibility_policy == visibility_policy+ if duplicate_request:+ logging.info(+ "User %s tried to set visibility_policy to its current value of %s",+ row.user_profile_id,+ visibility_policy,+ )+ continue+ # The request is to just 'update' the visibility policy of a topic+ user_profiles_seeking_visibility_policy_update.append(row.user_profile)- if duplicate_request:- logging.info(- "User %s tried to set visibility_policy to its current value of %s",- user_profile.id,- visibility_policy,+ if user_profiles_seeking_visibility_policy_update:+ rows.filter(user_profile__in=user_profiles_seeking_visibility_policy_update).update(+ visibility_policy=visibility_policy, last_updated=last_updated)- return False- # The request is to just 'update' the visibility policy of a topic- row.visibility_policy = visibility_policy- row.last_updated = last_updated- row.save(update_fields=["visibility_policy", "last_updated"])- return True+ if user_profiles_without_visibility_policy:+ UserTopic.objects.bulk_create(+ UserTopic(+ user_profile=user_profile,+ stream_id=stream_id,+ recipient_id=recipient_id,+ topic_name=topic_name,+ last_updated=last_updated,+ visibility_policy=visibility_policy,+ )+ for user_profile in user_profiles_without_visibility_policy+ )+ return user_profiles_seeking_visibility_policy_update + user_profiles_without_visibility_policydef topic_has_visibility_policy(diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.pyindex 21720fd4785..7594f43de16 100644--- a/zerver/tests/test_import_export.py+++ b/zerver/tests/test_import_export.py@@ -1765,7 +1765,10 @@ class SingleUserExportTest(ExportFile):self.assertEqual(rec["status_text"], "on vacation")do_set_user_topic_visibility_policy(- cordelia, scotland, "bagpipe music", visibility_policy=UserTopic.VisibilityPolicy.MUTED+ cordelia,+ scotland,+ "bagpipe music",+ visibility_policy=UserTopic.VisibilityPolicy.MUTED,)do_set_user_topic_visibility_policy(othello, scotland, "nessie", visibility_policy=UserTopic.VisibilityPolicy.MUTEDdiff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.pyindex 61c6a1774c2..272c2ebf21b 100644--- a/zerver/tests/test_message_edit.py+++ b/zerver/tests/test_message_edit.py@@ -1357,9 +1357,9 @@ class EditMessageTest(EditMessageTestCase):users_to_be_notified = list(map(notify, [hamlet.id, cordelia.id, aaron.id]))change_all_topic_name = "Topic 1 edited"- # This code path adds 19 (10 + 4/user with muted topics + 1) to+ # This code path adds 21 (10 + 5/user with muted topics + 1) to# the number of database queries for moving a topic.- with self.assert_database_query_count(19):+ with self.assert_database_query_count(21):check_update_message(user_profile=hamlet,message_id=message_id,@@ -1453,7 +1453,7 @@ class EditMessageTest(EditMessageTestCase):set_topic_visibility_policy(desdemona, muted_topics, UserTopic.VisibilityPolicy.MUTED)set_topic_visibility_policy(cordelia, muted_topics, UserTopic.VisibilityPolicy.MUTED)- with self.assert_database_query_count(30):+ with self.assert_database_query_count(32):check_update_message(user_profile=desdemona,message_id=message_id,@@ -1484,7 +1484,7 @@ class EditMessageTest(EditMessageTestCase):set_topic_visibility_policy(desdemona, muted_topics, UserTopic.VisibilityPolicy.MUTED)set_topic_visibility_policy(cordelia, muted_topics, UserTopic.VisibilityPolicy.MUTED)- with self.assert_database_query_count(31):+ with self.assert_database_query_count(33):check_update_message(user_profile=desdemona,message_id=message_id,@@ -1517,7 +1517,7 @@ class EditMessageTest(EditMessageTestCase):set_topic_visibility_policy(desdemona, muted_topics, UserTopic.VisibilityPolicy.MUTED)set_topic_visibility_policy(cordelia, muted_topics, UserTopic.VisibilityPolicy.MUTED)- with self.assert_database_query_count(30):+ with self.assert_database_query_count(32):check_update_message(user_profile=desdemona,message_id=message_id,@@ -1630,7 +1630,7 @@ class EditMessageTest(EditMessageTestCase):users_to_be_notified_via_muted_topics_event.append(user_topic.user_profile_id)change_all_topic_name = "Topic 1 edited"- with self.assert_database_query_count(19):+ with self.assert_database_query_count(21):check_update_message(user_profile=hamlet,message_id=message_id,