From 96f905f40913b915496039d188297a7949b1a6db Mon Sep 17 00:00:00 2001
From: ThibG <thib@sitedethib.com>
Date: Wed, 6 Mar 2019 19:53:57 +0100
Subject: [PATCH] Add optimistic lock to avoid race conditions when handling
 votes (#10196)

* Add optimistic lock to avoid race conditions when handling votes

* Force-reload polls when getting `ActiveRecord::StaleObjectError`
---
 app/models/poll.rb                                     | 1 +
 app/models/poll_vote.rb                                | 3 +++
 db/migrate/20190306145741_add_lock_version_to_polls.rb | 6 ++++++
 db/schema.rb                                           | 3 ++-
 4 files changed, 12 insertions(+), 1 deletion(-)
 create mode 100644 db/migrate/20190306145741_add_lock_version_to_polls.rb

diff --git a/app/models/poll.rb b/app/models/poll.rb
index ab7236d45..da2e25e71 100644
--- a/app/models/poll.rb
+++ b/app/models/poll.rb
@@ -15,6 +15,7 @@
 #  last_fetched_at :datetime
 #  created_at      :datetime         not null
 #  updated_at      :datetime         not null
+#  lock_version    :integer          default(0), not null
 #
 
 class Poll < ApplicationRecord
diff --git a/app/models/poll_vote.rb b/app/models/poll_vote.rb
index 9ad66bbf8..ad24eb691 100644
--- a/app/models/poll_vote.rb
+++ b/app/models/poll_vote.rb
@@ -32,5 +32,8 @@ class PollVote < ApplicationRecord
   def increment_counter_cache
     poll.cached_tallies[choice] = (poll.cached_tallies[choice] || 0) + 1
     poll.save
+  rescue ActiveRecord::StaleObjectError
+    poll.reload
+    retry
   end
 end
diff --git a/db/migrate/20190306145741_add_lock_version_to_polls.rb b/db/migrate/20190306145741_add_lock_version_to_polls.rb
new file mode 100644
index 000000000..cf506404d
--- /dev/null
+++ b/db/migrate/20190306145741_add_lock_version_to_polls.rb
@@ -0,0 +1,6 @@
+class AddLockVersionToPolls < ActiveRecord::Migration[5.2]
+  def change
+    add_column :polls, :lock_version, :integer, null: false, default: 0
+  end
+end
+
diff --git a/db/schema.rb b/db/schema.rb
index 161619dcf..3d5260270 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
 #
 # It's strongly recommended that you check this file into your version control system.
 
-ActiveRecord::Schema.define(version: 2019_03_04_152020) do
+ActiveRecord::Schema.define(version: 2019_03_06_145741) do
 
   # These are extensions that must be enabled in order to support this database
   enable_extension "plpgsql"
@@ -464,6 +464,7 @@ ActiveRecord::Schema.define(version: 2019_03_04_152020) do
     t.datetime "last_fetched_at"
     t.datetime "created_at", null: false
     t.datetime "updated_at", null: false
+    t.integer "lock_version", default: 0, null: false
     t.index ["account_id"], name: "index_polls_on_account_id"
     t.index ["status_id"], name: "index_polls_on_status_id"
   end