A platform for community discussion. Free, open, simple.
PERF: Respect guardian when calculating topics per page in categories (#37259)
Alan Guo Xiang Tan7d3e965ae519
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 8e2361a7e79..624fffdbf07 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -34,6 +34,7 @@ class CategoriesController < ApplicationControllerSYMMETRICAL_CATEGORIES_TO_TOPICS_FACTOR = 1.5MIN_CATEGORIES_TOPICS = 5+ MAX_CATEGORIES_TOPICS = 100MAX_CATEGORIES_LIMIT = 25def redirect@@ -471,12 +472,12 @@ class CategoriesController < ApplicationControllerprivate- def self.topics_per_page+ def topics_per_pagereturn SiteSetting.categories_topics if SiteSetting.categories_topics > 0- count = Category.where(parent_category: nil).count+ count = Category.secured(guardian).where(parent_category: nil).countcount = (SYMMETRICAL_CATEGORIES_TO_TOPICS_FACTOR * count).to_i- count > MIN_CATEGORIES_TOPICS ? count : MIN_CATEGORIES_TOPICS+ count.clamp(MIN_CATEGORIES_TOPICS, MAX_CATEGORIES_TOPICS)enddef categories_and_topics(topics_filter)@@ -658,7 +659,7 @@ class CategoriesController < ApplicationControllerSiteSetting.desktop_category_page_styleend- topic_options = { per_page: CategoriesController.topics_per_page, no_definitions: true }+ topic_options = { per_page: topics_per_page, no_definitions: true }topic_options.merge!(build_topic_list_options)topic_options[:order] = "created" if SiteSetting.desktop_category_page_style =="categories_and_latest_topics_created_date"diff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex 9e38743fd19..5aed4d2c93c 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -1317,6 +1317,34 @@ RSpec.describe CategoriesController doexpect(parsed_topic).to be_presentendend++ it "only counts categories the user can see when calculating topics per page" do+ SiteSetting.categories_topics = 0+ restricted_group = Fabricate(:group)+ 4.times { Fabricate(:private_category, group: restricted_group) }++ # anon sees 2 categories (uncategorized + category): 2 * 1.5 = 3, clamped to min 5+ get "/categories_and_latest.json"+ expect(response.parsed_body["topic_list"]["topics"].size).to eq(5)++ # member sees 6 categories (2 + 4 private): 6 * 1.5 = 9+ restricted_group.add(user)+ sign_in(user)+ get "/categories_and_latest.json"+ expect(response.parsed_body["topic_list"]["topics"].size).to eq(9)+ end++ it "enforces maximum cap on topics per page" do+ SiteSetting.categories_topics = 0+ 5.times { Fabricate(:category) }++ # 7 categories (uncategorized + category + 5 new): 7 * 1.5 = 10, capped to max 7+ stub_const(CategoriesController, :MAX_CATEGORIES_TOPICS, 7) do+ sign_in(admin)+ get "/categories_and_latest.json"+ expect(response.parsed_body["topic_list"]["topics"].size).to eq(7)+ end+ endenddescribe "#visible_groups" do