A platform for community discussion. Free, open, simple.
FIX: Avoid errors when updating post and topic count user stats. (#15876)
Alan Guo Xiang Tanae0625323ac4
diff --git a/app/services/user_stat_count_updater.rb b/app/services/user_stat_count_updater.rbindex 38810e5c689..90866295d7b 100644--- a/app/services/user_stat_count_updater.rb+++ b/app/services/user_stat_count_updater.rb@@ -17,23 +17,24 @@ class UserStatCountUpdaterreturn if post.topic.private_message?stat = user_stat || post.user.user_stat- if post.is_first_post?- stat.public_send(action, :topic_count)- elsif post.post_type == Post.types[:regular]- stat.public_send(action, :post_count)- end- rescue ActiveRecord::StatementInvalid => e- if e.cause.is_a?(PG::CheckViolation)+ column =+ if post.is_first_post?+ :topic_count+ elsif post.post_type == Post.types[:regular]+ :post_count+ end++ return if column.blank?++ if action == :decrement! && stat.public_send(column) < 1# There are still spots in the code base which results in the counter cache going out of sync. However,- # we have a job that runs on a daily basis which will correct the count. Therefore, avoid raising an error for now- # and log the exception instead.- Discourse.warn_exception(- e,- message: "Attempted to insert negative count into UserStat#post_count or UserStat#topic_count"- )- else- raise+ # we have a job that runs on a daily basis which will correct the count. Therefore, we always check that we+ # wouldn't end up with a negative count first before inserting.+ Rails.logger.warn("Attempted to insert negative count into UserStat##{column}\n#{caller.join('\n')}")+ returnend++ stat.public_send(action, column)endendenddiff --git a/spec/services/user_stat_count_updater_spec.rb b/spec/services/user_stat_count_updater_spec.rbindex a765e97072d..2e60a451103 100644--- a/spec/services/user_stat_count_updater_spec.rb+++ b/spec/services/user_stat_count_updater_spec.rb@@ -6,6 +6,7 @@ describe UserStatCountUpdater dofab!(:user) { Fabricate(:user) }fab!(:user_stat) { user.user_stat }fab!(:post) { Fabricate(:post) }+ fab!(:post_2) { Fabricate(:post, topic: post.topic) }before do@orig_logger = Rails.logger@@ -19,6 +20,10 @@ describe UserStatCountUpdater doit 'should log the exception when a negative count is inserted' doUserStatCountUpdater.decrement!(post, user_stat: user_stat)- expect(@fake_logger.warnings.first).to include("PG::CheckViolation")+ expect(@fake_logger.warnings.last).to match("topic_count")++ UserStatCountUpdater.decrement!(post_2, user_stat: user_stat)++ expect(@fake_logger.warnings.last).to match("post_count")endend