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.
This commit is contained in:
Ujjawal Modi 2023-06-09 01:12:16 +05:30 committed by Tim Abbott
parent fd0434a052
commit 535a088d0b
2 changed files with 6 additions and 6 deletions

View File

@ -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(

View File

@ -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))