FIX: Avoid raising error when updating post and topic count user stats. (#15873)

There are still spots in the code base which results in us trying to turn the post and topic count negative. 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.
This commit is contained in:
Alan Guo Xiang Tan 2022-02-09 12:51:13 +08:00 committed by GitHub
parent 71f7f7ed49
commit ab5361d69a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -22,6 +22,18 @@ class UserStatCountUpdater
elsif post.post_type == Post.types[:regular] elsif post.post_type == Post.types[:regular]
stat.public_send(action, :post_count) stat.public_send(action, :post_count)
end end
rescue ActiveRecord::StatementInvalid => e
if e.cause.is_a?(PG::CheckViolation)
# 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
end
end end
end end
end end

View File

@ -0,0 +1,24 @@
# frozen_string_literal: true
require 'rails_helper'
describe UserStatCountUpdater do
fab!(:user) { Fabricate(:user) }
fab!(:user_stat) { user.user_stat }
fab!(:post) { Fabricate(:post) }
before do
@orig_logger = Rails.logger
Rails.logger = @fake_logger = FakeLogger.new
end
after do
Rails.logger = @orig_logger
end
it 'should log the exception when a negative count is inserted' do
UserStatCountUpdater.decrement!(post, user_stat: user_stat)
expect(@fake_logger.warnings.first).to include("PG::CheckViolation")
end
end