From 83ac1563829b36ac54907464b703d81e989589b5 Mon Sep 17 00:00:00 2001 From: Karina Kwiatek Date: Wed, 1 Nov 2023 08:45:56 +0100 Subject: [PATCH] Refactor `QuestionWorker` to send to individual users rather than all followers at once --- app/workers/question_worker.rb | 23 ++++++++++------------- lib/use_case/question/create_followers.rb | 9 +++++---- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/app/workers/question_worker.rb b/app/workers/question_worker.rb index 969b725f..6cffd5af 100644 --- a/app/workers/question_worker.rb +++ b/app/workers/question_worker.rb @@ -5,22 +5,17 @@ class QuestionWorker sidekiq_options queue: :question, retry: false - # @param user_id [Integer] user id passed from Devise + # @param follower_id [Integer] user id passed from Devise # @param question_id [Integer] newly created question id - def perform(user_id, question_id) - user = User.find(user_id) - question = Question.find(question_id) + def perform(follower_id, question_id) + follower = User.includes(:web_push_subscriptions, :mute_rules, :muted_users).find(follower_id) + question = Question.includes(:user).find(question_id) webpush_app = Rpush::App.find_by(name: "webpush") - user.followers.each do |f| - next if skip_inbox?(f, question, user) + return if skip_inbox?(follower, question, user) - inbox = Inbox.create(user_id: f.id, question_id:, new: true) - f.push_notification(webpush_app, inbox) if webpush_app - end - rescue StandardError => e - logger.info "failed to ask question: #{e.message}" - Sentry.capture_exception(e) + inbox = Inbox.create(user_id: follower.id, question_id:, new: true) + follower.push_notification(webpush_app, inbox) if webpush_app end private @@ -35,7 +30,9 @@ class QuestionWorker false end + # @param [User] user + # @param [Question] question def muted?(user, question) - MuteRule.where(user:).any? { |rule| rule.applies_to? question } + user.mute_rules.any? { |rule| rule.applies_to? question } end end diff --git a/lib/use_case/question/create_followers.rb b/lib/use_case/question/create_followers.rb index 04fe3844..fd4a73de 100644 --- a/lib/use_case/question/create_followers.rb +++ b/lib/use_case/question/create_followers.rb @@ -13,13 +13,14 @@ module UseCase author_is_anonymous: false, author_identifier:, user: source_user, - direct: false + direct: false, ) increment_asked_count increment_metric - QuestionWorker.perform_async(source_user_id, question.id) + args = source_user.followers.map { |f| [f.id, question.id] } + QuestionWorker.perform_bulk(args) { status: 201, @@ -40,12 +41,12 @@ module UseCase anonymous: false, followers: true, generated: false, - } + }, ) end def source_user - @source_user ||= ::User.find(source_user_id) + @source_user ||= ::User.includes(:followers).find(source_user_id) end end end