Fix account counters being overwritten by parallel writes (#12045)
This commit is contained in:
parent
9e3e3fa5ee
commit
62f60e86c2
4 changed files with 92 additions and 1 deletions
|
@ -11,6 +11,7 @@
|
|||
# created_at :datetime not null
|
||||
# updated_at :datetime not null
|
||||
# last_status_at :datetime
|
||||
# lock_version :integer default(0), not null
|
||||
#
|
||||
|
||||
class AccountStat < ApplicationRecord
|
||||
|
@ -20,10 +21,26 @@ class AccountStat < ApplicationRecord
|
|||
|
||||
def increment_count!(key)
|
||||
update(attributes_for_increment(key))
|
||||
rescue ActiveRecord::StaleObjectError
|
||||
begin
|
||||
reload_with_id
|
||||
rescue ActiveRecord::RecordNotFound
|
||||
# Nothing to do
|
||||
else
|
||||
retry
|
||||
end
|
||||
end
|
||||
|
||||
def decrement_count!(key)
|
||||
update(key => [public_send(key) - 1, 0].max)
|
||||
rescue ActiveRecord::StaleObjectError
|
||||
begin
|
||||
reload_with_id
|
||||
rescue ActiveRecord::RecordNotFound
|
||||
# Nothing to do
|
||||
else
|
||||
retry
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
@ -33,4 +50,9 @@ class AccountStat < ApplicationRecord
|
|||
attrs[:last_status_at] = Time.now.utc if key == :statuses_count
|
||||
attrs
|
||||
end
|
||||
|
||||
def reload_with_id
|
||||
self.id = find_by!(account: account).id if new_record?
|
||||
reload
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue