Skip to content

A platform for community discussion. Free, open, simple.

PERF: Avoid slow preloading in `SiteSerializer` (#33283)

Alan Guo Xiang Tan684569c30e85
diff --git a/app/controllers/admin/config/flags_controller.rb b/app/controllers/admin/config/flags_controller.rb
index 0d83da70da9..c0f3f888ebc 100644
--- a/app/controllers/admin/config/flags_controller.rb
+++ b/app/controllers/admin/config/flags_controller.rb
@@ -29,7 +29,7 @@ class Admin::Config::FlagsController < Admin::AdminController
Flags::CreateFlag.call(service_params) do
on_success do |flag:|
Discourse.request_refresh!
- render json: flag, serializer: FlagSerializer, used_flag_ids: Flag.used_flag_ids
+ render json: flag, serializer: FlagSerializer
end
on_failure { render(json: failed_json, status: 422) }
on_failed_policy(:invalid_access) { raise Discourse::InvalidAccess }
@@ -44,7 +44,7 @@ class Admin::Config::FlagsController < Admin::AdminController
Flags::UpdateFlag.call(service_params) do
on_success do |flag:|
Discourse.request_refresh!
- render json: flag, serializer: FlagSerializer, used_flag_ids: Flag.used_flag_ids
+ render json: flag, serializer: FlagSerializer
end
on_failure { render(json: failed_json, status: 422) }
on_model_not_found(:message) { raise Discourse::NotFound }
diff --git a/app/models/flag.rb b/app/models/flag.rb
index 619e43bdd00..6b7ae4017dd 100644
--- a/app/models/flag.rb
+++ b/app/models/flag.rb
@@ -37,9 +37,17 @@ class Flag < ActiveRecord::Base
PostActionType.reload_types
end
- def self.used_flag_ids
- PostAction.distinct(:post_action_type_id).pluck(:post_action_type_id) |
- ReviewableScore.distinct(:reviewable_score_type).pluck(:reviewable_score_type)
+ def self.used_flag_ids(flag_ids)
+ sql =
+ flag_ids
+ .reduce([]) do |queries, flag_id|
+ queries << "(SELECT #{flag_id} FROM post_actions WHERE post_action_type_id = #{flag_id} LIMIT 1)"
+ queries << "(SELECT #{flag_id} FROM reviewable_scores WHERE reviewable_score_type = #{flag_id} LIMIT 1)"
+ queries
+ end
+ .join(" UNION ")
+
+ DB.query_single(sql)
end
def system?
diff --git a/app/models/post_action.rb b/app/models/post_action.rb
index 1e3b2dd93d9..4e9d6cbf071 100644
--- a/app/models/post_action.rb
+++ b/app/models/post_action.rb
@@ -274,6 +274,7 @@ end
#
# idx_unique_actions (user_id,post_action_type_id,post_id,targets_topic) UNIQUE WHERE ((deleted_at IS NULL) AND (disagreed_at IS NULL) AND (deferred_at IS NULL))
# idx_unique_flags (user_id,post_id,targets_topic) UNIQUE WHERE ((deleted_at IS NULL) AND (disagreed_at IS NULL) AND (deferred_at IS NULL) AND (post_action_type_id = ANY (ARRAY[3, 4, 7, 8])))
+# index_post_actions_on_post_action_type_id (post_action_type_id)
# index_post_actions_on_post_action_type_id_and_disagreed_at (post_action_type_id,disagreed_at) WHERE (disagreed_at IS NULL)
# index_post_actions_on_post_id (post_id)
# index_post_actions_on_user_id (user_id)
diff --git a/app/models/reviewable_score.rb b/app/models/reviewable_score.rb
index 38584c0d4fd..80b96258c3f 100644
--- a/app/models/reviewable_score.rb
+++ b/app/models/reviewable_score.rb
@@ -121,6 +121,7 @@ end
#
# Indexes
#
-# index_reviewable_scores_on_reviewable_id (reviewable_id)
-# index_reviewable_scores_on_user_id (user_id)
+# index_reviewable_scores_on_reviewable_id (reviewable_id)
+# index_reviewable_scores_on_reviewable_score_type (reviewable_score_type)
+# index_reviewable_scores_on_user_id (user_id)
#
diff --git a/app/serializers/flag_serializer.rb b/app/serializers/flag_serializer.rb
index b70dbbdfbb4..7e532c441a0 100644
--- a/app/serializers/flag_serializer.rb
+++ b/app/serializers/flag_serializer.rb
@@ -42,7 +42,7 @@ class FlagSerializer < ApplicationSerializer
end
def is_used
- @options[:used_flag_ids].include?(object.id)
+ @options[:used_flag_ids]&.include?(object.id) || object.used?
end
def applies_to
diff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rb
index b3fea677d5b..44968ce72b3 100644
--- a/app/serializers/site_serializer.rb
+++ b/app/serializers/site_serializer.rb
@@ -128,11 +128,13 @@ class SiteSerializer < ApplicationSerializer
types = ordered_flags(PostActionType.types.values)
ActiveModel::ArraySerializer.new(types).as_json
else
+ flags = Flag.unscoped.order(:position).where(score_type: false).all
+
ActiveModel::ArraySerializer.new(
- Flag.unscoped.order(:position).where(score_type: false).all,
+ flags,
each_serializer: FlagSerializer,
target: :post_action,
- used_flag_ids: Flag.used_flag_ids,
+ used_flag_ids: self.used_flag_ids(flags.map(&:id)),
).as_json
end
end
@@ -146,16 +148,19 @@ class SiteSerializer < ApplicationSerializer
types = ordered_flags(PostActionType.topic_flag_types.values)
ActiveModel::ArraySerializer.new(types, each_serializer: TopicFlagTypeSerializer).as_json
else
- ActiveModel::ArraySerializer.new(
+ flags =
Flag
.unscoped
.where("'Topic' = ANY(applies_to)")
.where(score_type: false)
.order(:position)
- .all,
+ .all
+
+ ActiveModel::ArraySerializer.new(
+ flags,
each_serializer: FlagSerializer,
target: :topic_flag,
- used_flag_ids: Flag.used_flag_ids,
+ used_flag_ids: self.used_flag_ids(flags.map(&:id)),
).as_json
end
end
@@ -405,4 +410,8 @@ class SiteSerializer < ApplicationSerializer
def ordered_flags(flags)
flags.map { |id| PostActionType.new(id: id) }
end
+
+ def used_flag_ids(flag_ids)
+ @used_flag_ids ||= Flag.used_flag_ids(flag_ids)
+ end
end
diff --git a/db/migrate/20250620025548_add_index_to_post_actions_on_post_action_type_id.rb b/db/migrate/20250620025548_add_index_to_post_actions_on_post_action_type_id.rb
new file mode 100644
index 00000000000..be447fd9e5f
--- /dev/null
+++ b/db/migrate/20250620025548_add_index_to_post_actions_on_post_action_type_id.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class AddIndexToPostActionsOnPostActionTypeId < ActiveRecord::Migration[7.2]
+ disable_ddl_transaction!
+
+ def up
+ execute <<~SQL
+ DROP INDEX IF EXISTS index_post_actions_on_post_action_type_id;
+ SQL
+
+ execute <<~SQL
+ CREATE INDEX CONCURRENTLY index_post_actions_on_post_action_type_id ON post_actions (post_action_type_id);
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/db/migrate/20250620033435_add_index_reviewable_scores_on_reviewable_score_type.rb b/db/migrate/20250620033435_add_index_reviewable_scores_on_reviewable_score_type.rb
new file mode 100644
index 00000000000..e5b6ff321c6
--- /dev/null
+++ b/db/migrate/20250620033435_add_index_reviewable_scores_on_reviewable_score_type.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+class AddIndexReviewableScoresOnReviewableScoreType < ActiveRecord::Migration[7.2]
+ disable_ddl_transaction!
+
+ def up
+ execute <<~SQL
+ DROP INDEX IF EXISTS index_reviewable_scores_on_reviewable_score_type;
+ SQL
+
+ execute <<~SQL
+ CREATE INDEX CONCURRENTLY index_reviewable_scores_on_reviewable_score_type ON reviewable_scores (reviewable_score_type);
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/spec/models/flag_spec.rb b/spec/models/flag_spec.rb
index 9c2597e815e..b4024f6b8ba 100644
--- a/spec/models/flag_spec.rb
+++ b/spec/models/flag_spec.rb
@@ -81,28 +81,22 @@ RSpec.describe Flag, type: :model do
end
describe ".used_flag_ids" do
- fab!(:post_action) { Fabricate(:post_action, post_action_type_id: PostActionType.types[:like]) }
- fab!(:post_action_2) do
- Fabricate(:post_action, post_action_type_id: PostActionType.types[:like])
- end
- fab!(:post_action_3) do
- Fabricate(:post_action, post_action_type_id: PostActionType.types[:off_topic])
- end
+ fab!(:used_by_post_action_flag) { Fabricate(:flag) }
+ fab!(:used_by_reviewable_score_flag) { Fabricate(:flag) }
+ fab!(:unused_flag) { Fabricate(:flag) }
+
+ fab!(:post_action) { Fabricate(:post_action, post_action_type_id: used_by_post_action_flag.id) }
+
fab!(:reviewable_score) do
- Fabricate(:reviewable_score, reviewable_score_type: PostActionType.types[:off_topic])
- end
- fab!(:reviewable_score_2) do
- Fabricate(:reviewable_score, reviewable_score_type: PostActionType.types[:illegal])
+ Fabricate(:reviewable_score, reviewable_score_type: used_by_reviewable_score_flag.id)
end
- it "returns an array of unique flag ids" do
- expect(Flag.used_flag_ids).to eq(
- [
- PostActionType.types[:like],
- PostActionType.types[:off_topic],
- PostActionType.types[:illegal],
- ],
- )
+ it "returns the ids of flags that are associated to a `PostAction` or `ReviewableScore`" do
+ expect(
+ Flag.used_flag_ids(
+ [used_by_post_action_flag.id, used_by_reviewable_score_flag.id, unused_flag.id],
+ ),
+ ).to contain_exactly(used_by_post_action_flag.id, used_by_reviewable_score_flag.id)
end
end
end
diff --git a/spec/serializers/flag_serializer_spec.rb b/spec/serializers/flag_serializer_spec.rb
index 6f8f913642e..b12e9b0899e 100644
--- a/spec/serializers/flag_serializer_spec.rb
+++ b/spec/serializers/flag_serializer_spec.rb
@@ -5,12 +5,12 @@ RSpec.describe FlagSerializer do
context "when system flag" do
it "returns translated name" do
- serialized = described_class.new(flag, used_flag_ids: []).as_json
+ serialized = described_class.new(flag).as_json
expect(serialized[:flag][:name]).to eq(I18n.t("post_action_types.illegal.title"))
end
it "returns translated description" do
- serialized = described_class.new(flag, used_flag_ids: []).as_json
+ serialized = described_class.new(flag).as_json
expect(serialized[:flag][:description]).to eq(I18n.t("post_action_types.illegal.description"))
end
end
@@ -18,7 +18,7 @@ RSpec.describe FlagSerializer do
context "when custom flag" do
it "returns translated name and description" do
flag = Fabricate(:flag, name: "custom title", description: "custom description")
- serialized = described_class.new(flag, used_flag_ids: []).as_json
+ serialized = described_class.new(flag).as_json
expect(serialized[:flag][:name]).to eq("custom title")
expect(serialized[:flag][:description]).to eq("custom description")
flag.destroy!
@@ -26,29 +26,44 @@ RSpec.describe FlagSerializer do
end
it "returns is_flag true for flags" do
- serialized = described_class.new(flag, used_flag_ids: []).as_json
+ serialized = described_class.new(flag).as_json
expect(serialized[:flag][:is_flag]).to be true
end
it "returns is_flag false for like" do
flag = Flag.unscoped.find_by(name: "like")
- serialized = described_class.new(flag, used_flag_ids: []).as_json
+ serialized = described_class.new(flag).as_json
expect(serialized[:flag][:is_flag]).to be false
end
- it "returns is_used false when not used" do
- serialized = described_class.new(flag, used_flag_ids: []).as_json
- expect(serialized[:flag][:is_used]).to be false
+ it "returns applies_to" do
+ serialized = described_class.new(flag).as_json
+ expect(serialized[:flag][:applies_to]).to eq(%w[Post Topic Chat::Message])
end
- it "returns is_used true when used" do
- serialized = described_class.new(flag, used_flag_ids: [flag.id]).as_json
- expect(serialized[:flag][:is_used]).to be true
- end
+ describe "#is_used" do
+ fab!(:unused_flag) { Fabricate(:flag) }
- it "returns applies_to" do
- serialized = described_class.new(flag, used_flag_ids: []).as_json
- expect(serialized[:flag][:applies_to]).to eq(%w[Post Topic Chat::Message])
+ fab!(:used_flag) do
+ flag = Fabricate(:flag)
+ Fabricate(:post_action, post_action_type_id: flag.id)
+ flag
+ end
+
+ it "returns false when flag is not used" do
+ serialized = described_class.new(unused_flag).as_json
+ expect(serialized[:flag][:is_used]).to be false
+ end
+
+ it "returns true when flag is used" do
+ serialized = described_class.new(used_flag).as_json
+ expect(serialized[:flag][:is_used]).to be true
+ end
+
+ it "returns true when flag's id is in used_flag_ids option" do
+ serialized = described_class.new(unused_flag, used_flag_ids: [unused_flag.id]).as_json
+ expect(serialized[:flag][:is_used]).to be true
+ end
end
describe "#description" do