Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
message fetching: Avoid duplicate cache layers.
Steve Howelld19c1f743893
diff --git a/zerver/lib/cache.py b/zerver/lib/cache.pyindex a35fc3a14fb..5e38cadb8de 100644--- a/zerver/lib/cache.py+++ b/zerver/lib/cache.py@@ -438,10 +438,8 @@ def display_recipient_cache_key(recipient_id: int) -> str:return f"display_recipient_dict:{recipient_id}"-def display_recipient_bulk_get_users_by_id_cache_key(user_id: int) -> str:- # Cache key function for a function for bulk fetching users, used internally- # by display_recipient code.- return "bulk_fetch_display_recipients:" + user_profile_by_id_cache_key(user_id)+def single_user_display_recipient_cache_key(user_id: int) -> str:+ return f"single_user_display_recipient:{user_id}"def user_profile_cache_key_id(email: str, realm_id: int) -> str:@@ -557,7 +555,7 @@ def delete_display_recipient_cache(user_profile: "UserProfile") -> None:"recipient_id", flat=True)keys = [display_recipient_cache_key(rid) for rid in recipient_ids]- keys.append(display_recipient_bulk_get_users_by_id_cache_key(user_profile.id))+ keys.append(single_user_display_recipient_cache_key(user_profile.id))cache_delete_many(keys)diff --git a/zerver/lib/display_recipient.py b/zerver/lib/display_recipient.pyindex 78146827106..4344e40a99a 100644--- a/zerver/lib/display_recipient.py+++ b/zerver/lib/display_recipient.py@@ -5,8 +5,8 @@ from django_stubs_ext import ValuesQuerySetfrom zerver.lib.cache import (bulk_cached_fetch,cache_with_key,- display_recipient_bulk_get_users_by_id_cache_key,display_recipient_cache_key,+ single_user_display_recipient_cache_key,transformed_bulk_cached_fetch,)from zerver.lib.types import DisplayRecipientT, UserDisplayRecipient@@ -62,12 +62,12 @@ def user_dict_id_fetcher(user_dict: UserDisplayRecipient) -> int:return user_dict["id"]-def bulk_get_user_profile_by_id(uids: List[int]) -> Dict[int, UserDisplayRecipient]:+def bulk_fetch_single_user_display_recipients(uids: List[int]) -> Dict[int, UserDisplayRecipient]:return bulk_cached_fetch(# Use a separate cache key to protect us from conflicts with# the get_user_profile_by_id cache.# (Since we fetch only several fields here)- cache_key_function=display_recipient_bulk_get_users_by_id_cache_key,+ cache_key_function=single_user_display_recipient_cache_key,query_function=lambda ids: list(UserProfile.objects.filter(id__in=ids).values(*display_recipient_fields)),@@ -125,98 +125,40 @@ def bulk_fetch_user_display_recipients(if len(recipient_tuples) == 0:return {}- recipient_id_to_type = {recipient[0]: recipient[1] for recipient in recipient_tuples}+ get_recipient_id = lambda tup: tup[0]+ get_type = lambda tup: tup[1]- recipient_id_to_type_id = {recipient[0]: recipient[2] for recipient in recipient_tuples}+ personal_tuples = [tup for tup in recipient_tuples if get_type(tup) == Recipient.PERSONAL]+ huddle_tuples = [tup for tup in recipient_tuples if get_type(tup) == Recipient.HUDDLE]- recipient_ids = [recipient[0] for recipient in recipient_tuples]+ huddle_recipient_ids = [get_recipient_id(tup) for tup in huddle_tuples]+ huddle_recipient_id_to_user_ids = bulk_get_huddle_user_ids(huddle_recipient_ids)- # Now we have to create display_recipients for personal and huddle messages.- # We do this via generic_bulk_cached_fetch, supplying appropriate functions to it.+ # Find all user ids whose UserProfiles we will need to fetch:+ user_ids_to_fetch: Set[int] = set()- def personal_and_huddle_query_function(- recipient_ids: List[int],- ) -> List[Tuple[int, List[UserDisplayRecipient]]]:- """- Return a list of tuples of the form (recipient_id, [list of UserProfiles])- where [list of UserProfiles] has users corresponding to the recipient,- so the receiving userin Recipient.PERSONAL case,- or in Personal.HUDDLE case - users in the huddle.- This is a pretty hacky return value, but it needs to be in this form,- for this function to work as the query_function in generic_bulk_cached_fetch.- """-- recipients = [- Recipient(- id=recipient_id,- type=recipient_id_to_type[recipient_id],- type_id=recipient_id_to_type_id[recipient_id],- )- for recipient_id in recipient_ids- ]-- # Find all user ids whose UserProfiles we will need to fetch:- user_ids_to_fetch: Set[int] = set()- huddle_user_ids: Dict[int, Set[int]] = {}- huddle_user_ids = bulk_get_huddle_user_ids(- [recipient for recipient in recipients if recipient.type == Recipient.HUDDLE]- )- for recipient in recipients:- if recipient.type == Recipient.PERSONAL:- user_ids_to_fetch.add(recipient.type_id)- else:- user_ids_to_fetch = user_ids_to_fetch.union(huddle_user_ids[recipient.id])-- # Fetch the needed UserProfiles:- user_profiles: Dict[int, UserDisplayRecipient] = bulk_get_user_profile_by_id(- list(user_ids_to_fetch)- )+ for ignore_recipient_id, ignore_recipient_type, user_id in personal_tuples:+ user_ids_to_fetch.add(user_id)- # Build the return value:- result: List[Tuple[int, List[UserDisplayRecipient]]] = []- for recipient in recipients:- if recipient.type == Recipient.PERSONAL:- result.append((recipient.id, [user_profiles[recipient.type_id]]))- else:- result.append(- (- recipient.id,- [user_profiles[user_id] for user_id in huddle_user_ids[recipient.id]],- )- )-- return result-- def personal_and_huddle_cache_transformer(- db_object: Tuple[int, List[UserDisplayRecipient]],- ) -> List[UserDisplayRecipient]:- """- Takes an element of the list returned by the query_function, maps it to the final- display_recipient list.- """- user_profile_list = db_object[1]- display_recipient = user_profile_list-- return display_recipient-- def personal_and_huddle_id_fetcher(db_object: Tuple[int, List[UserDisplayRecipient]]) -> int:- # db_object is a tuple, with recipient_id in the first position- return db_object[0]-- # ItemT = Tuple[int, List[UserDisplayRecipient]] (recipient_id, list of corresponding users)- # CacheItemT = List[UserDisplayRecipient] (display_recipient list)- # ObjKT = int (recipient_id)- personal_and_huddle_display_recipients: Dict[- int, List[UserDisplayRecipient]- ] = transformed_bulk_cached_fetch(- cache_key_function=display_recipient_cache_key,- query_function=personal_and_huddle_query_function,- object_ids=recipient_ids,- id_fetcher=personal_and_huddle_id_fetcher,- cache_transformer=personal_and_huddle_cache_transformer,- )+ for recipient_id in huddle_recipient_ids:+ huddle_user_ids = huddle_recipient_id_to_user_ids[recipient_id]+ user_ids_to_fetch |= huddle_user_ids++ # Fetch the needed user dictionaries.+ user_display_recipients = bulk_fetch_single_user_display_recipients(list(user_ids_to_fetch))++ result = {}++ for recipient_id, ignore_recipient_type, user_id in personal_tuples:+ display_recipients = [user_display_recipients[user_id]]+ result[recipient_id] = display_recipients++ for recipient_id in huddle_recipient_ids:+ user_ids = sorted(huddle_recipient_id_to_user_ids[recipient_id])+ display_recipients = [user_display_recipients[user_id] for user_id in user_ids]+ result[recipient_id] = display_recipients- return personal_and_huddle_display_recipients+ return resultdef bulk_fetch_display_recipients(diff --git a/zerver/models.py b/zerver/models.pyindex e33bb5a14ac..d30ea9a5b96 100644--- a/zerver/models.py+++ b/zerver/models.py@@ -2899,17 +2899,20 @@ def get_huddle_user_ids(recipient: Recipient) -> ValuesQuerySet["Subscription",)-def bulk_get_huddle_user_ids(recipients: List[Recipient]) -> Dict[int, Set[int]]:+def bulk_get_huddle_user_ids(recipient_ids: List[int]) -> Dict[int, Set[int]]:"""- Takes a list of huddle-type recipients, returns a dict+ Takes a list of huddle-type recipient_ids, returns a dictmapping recipient id to list of user ids in the huddle.++ We rely on our caller to pass us recipient_ids that correspond+ to huddles, but technically this function is valid for any type+ of subscription."""- assert all(recipient.type == Recipient.HUDDLE for recipient in recipients)- if not recipients:+ if not recipient_ids:return {}subscriptions = Subscription.objects.filter(- recipient__in=recipients,+ recipient_id__in=recipient_ids,).only("user_profile_id", "recipient_id")result_dict: Dict[int, Set[int]] = defaultdict(set)diff --git a/zerver/tests/test_messages.py b/zerver/tests/test_messages.pyindex bcbcdf0ea3b..224df854889 100644--- a/zerver/tests/test_messages.py+++ b/zerver/tests/test_messages.py@@ -95,7 +95,7 @@ class TestBulkGetHuddleUserIds(ZulipTestCase):second_huddle_user_ids = set(get_huddle_user_ids(second_huddle_recipient))huddle_user_ids = bulk_get_huddle_user_ids(- [first_huddle_recipient, second_huddle_recipient]+ [first_huddle_recipient.id, second_huddle_recipient.id])self.assertEqual(huddle_user_ids[first_huddle_recipient.id], first_huddle_user_ids)self.assertEqual(huddle_user_ids[second_huddle_recipient.id], second_huddle_user_ids)diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex ee883008fe5..48ab3e0bd5a 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -947,7 +947,7 @@ class LoginTest(ZulipTestCase):# seem to be any O(N) behavior. Some of the cache hits are related# to sending messages, such as getting the welcome bot, looking up# the alert words for a realm, etc.- self.assert_length(cache_tries, 20)+ self.assert_length(cache_tries, 19)user_profile = self.nonreg_user("test")self.assert_logged_in_user_id(user_profile.id)diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex fd4aedfabf5..bec20d2329a 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -800,7 +800,7 @@ class QueryCountTest(ZulipTestCase):acting_user=None,)- self.assert_length(cache_tries, 26)+ self.assert_length(cache_tries, 24)peer_add_events = [event for event in events if event["event"].get("op") == "peer_add"]notifications = set()