From e6299a310fa6068d2b681e24f7d69f862fec4eee Mon Sep 17 00:00:00 2001 From: Andrei Prigorshnev Date: Tue, 31 Oct 2023 18:17:37 +0400 Subject: [PATCH] FIX: Further optimize mentioning groups in chat messages (#24122) A follow-up to faac6773. This PR eliminates one more heavy join by forcing Active Record to do two queries instead. Also, along the way, I made this change: ``` # this generates two quries to the groups table def groups_to_mention @groups_to_mention = mentionable_groups - groups_with_too_many_members end # so I changed it to (this makes only one query to the groups table): def groups_to_mention @groups_to_mention ||= mentionable_groups.where("user_count <= ?", SiteSetting.max_users_notified_per_group_mention) end ``` This one is kind of a premature optimization, because we don't have evidence that this extra query is a problem, but it seems cleaner this way. Commits history on this PR may help better understand the change. --- plugins/chat/lib/chat/notifier.rb | 1 - plugins/chat/lib/chat/parsed_mentions.rb | 11 ++++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/plugins/chat/lib/chat/notifier.rb b/plugins/chat/lib/chat/notifier.rb index 0bc4ab7a765..2728dc0c13e 100644 --- a/plugins/chat/lib/chat/notifier.rb +++ b/plugins/chat/lib/chat/notifier.rb @@ -198,7 +198,6 @@ module Chat @parsed_mentions .group_mentions .not_suspended - .where("user_count <= ?", SiteSetting.max_users_notified_per_group_mention) .where.not(username_lower: @user.username_lower) .where.not(id: already_covered_ids) diff --git a/plugins/chat/lib/chat/parsed_mentions.rb b/plugins/chat/lib/chat/parsed_mentions.rb index ed693ddb415..a246ef8f26f 100644 --- a/plugins/chat/lib/chat/parsed_mentions.rb +++ b/plugins/chat/lib/chat/parsed_mentions.rb @@ -51,8 +51,9 @@ module Chat end def group_mentions - mentionable_groups_ids = mentionable_groups.pluck(:id) - chat_users.includes(:groups).joins(:groups).where("groups.id IN (?)", mentionable_groups_ids) + group_ids = groups_to_mention.pluck(:id) + group_user_ids = GroupUser.where(group_id: group_ids).pluck(:user_id) + chat_users.where(id: group_user_ids) end def here_mentions @@ -64,7 +65,11 @@ module Chat end def groups_to_mention - @groups_to_mention = mentionable_groups - groups_with_too_many_members + @groups_to_mention ||= + mentionable_groups.where( + "user_count <= ?", + SiteSetting.max_users_notified_per_group_mention, + ) end def groups_with_disabled_mentions