From 535a088d0ba790dcd090d48bc6421a3ea1dfb2ee Mon Sep 17 00:00:00 2001 From: Ujjawal Modi Date: Fri, 9 Jun 2023 01:12:16 +0530 Subject: [PATCH] bots: Refactor code for flushing bots cache. Subsequent commits will add "on_delete=models.RESTRICT" relationships, which will result in the UserProfile objects being deleted after Realm has been deleted from the database. In order to handle this, we update bot_dicts_in_realm_cache_key function to accept realm_id as parameter instead of realm object, so that the code for flushing the cache works even after the realm is deleted. This change is fine because eventually only realm_id is used by this function and there is no need of the complete realm object. --- zerver/lib/cache.py | 10 +++++----- zerver/models.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/zerver/lib/cache.py b/zerver/lib/cache.py index 65bdc26781..d16be41a8b 100644 --- a/zerver/lib/cache.py +++ b/zerver/lib/cache.py @@ -527,8 +527,8 @@ bot_dict_fields: List[str] = [ ] -def bot_dicts_in_realm_cache_key(realm: "Realm") -> str: - return f"bot_dicts_in_realm:{realm.id}" +def bot_dicts_in_realm_cache_key(realm_id: int) -> str: + return f"bot_dicts_in_realm:{realm_id}" def get_stream_cache_key(stream_name: str, realm_id: int) -> str: @@ -605,7 +605,7 @@ def flush_user_profile( # Invalidate our bots_in_realm info dict if any bot has # changed the fields in the dict or become (in)active if user_profile.is_bot and changed(update_fields, bot_dict_fields): - cache_delete(bot_dicts_in_realm_cache_key(user_profile.realm)) + cache_delete(bot_dicts_in_realm_cache_key(user_profile.realm_id)) def flush_muting_users_cache(*, instance: "MutedUser", **kwargs: object) -> None: @@ -634,7 +634,7 @@ def flush_realm( ): cache_delete(realm_user_dicts_cache_key(realm.id)) cache_delete(active_user_ids_cache_key(realm.id)) - cache_delete(bot_dicts_in_realm_cache_key(realm)) + cache_delete(bot_dicts_in_realm_cache_key(realm.id)) cache_delete(realm_alert_words_cache_key(realm)) cache_delete(realm_alert_words_automaton_cache_key(realm)) cache_delete(active_non_guest_user_ids_cache_key(realm.id)) @@ -687,7 +687,7 @@ def flush_stream( Q(default_sending_stream=stream) | Q(default_events_register_stream=stream) ).exists() ): - cache_delete(bot_dicts_in_realm_cache_key(stream.realm)) + cache_delete(bot_dicts_in_realm_cache_key(stream.realm_id)) def flush_used_upload_space_cache( diff --git a/zerver/models.py b/zerver/models.py index 7be56debb4..164eb6db19 100644 --- a/zerver/models.py +++ b/zerver/models.py @@ -4029,7 +4029,7 @@ def get_source_profile(email: str, realm_id: int) -> Optional[UserProfile]: return None -@cache_with_key(bot_dicts_in_realm_cache_key, timeout=3600 * 24 * 7) +@cache_with_key(lambda realm: bot_dicts_in_realm_cache_key(realm.id), timeout=3600 * 24 * 7) def get_bot_dicts_in_realm(realm: Realm) -> List[Dict[str, Any]]: return list(UserProfile.objects.filter(realm=realm, is_bot=True).values(*bot_dict_fields))