Class: Istox::RaceConditionHelper
- Inherits:
-
Object
- Object
- Istox::RaceConditionHelper
- Defined in:
- lib/istox/helpers/race_condition_helper.rb
Class Method Summary collapse
- .acquire(key, expired_seconds: 20) ⇒ Object
- .acquire!(key, expired_seconds: 20) ⇒ Object
-
.lock!(key, expired_seconds: 20) ⇒ Object
lock with block.
- .release(key) ⇒ Object
- .request_redis ⇒ Object
Class Method Details
.acquire(key, expired_seconds: 20) ⇒ Object
10 11 12 13 14 15 16 17 |
# File 'lib/istox/helpers/race_condition_helper.rb', line 10 def acquire(key, expired_seconds: 20) result = request_redis.set('race-condition||' + key.to_s, 'EMPTY', nx: true, ex: expired_seconds.to_i.seconds) log.info("Acquiring lock for key: #{key}, expired in #{expired_seconds} seconds, result: #{result}") # if result false means the key already exist [true, 1].include?(result) end |
.acquire!(key, expired_seconds: 20) ⇒ Object
4 5 6 7 8 |
# File 'lib/istox/helpers/race_condition_helper.rb', line 4 def acquire!(key, expired_seconds: 20) result = acquire(key, expired_seconds: expired_seconds) raise 'Duplicate request detected, please refresh the page and try again.' if result == false end |
.lock!(key, expired_seconds: 20) ⇒ Object
lock with block
26 27 28 29 30 31 32 33 |
# File 'lib/istox/helpers/race_condition_helper.rb', line 26 def lock!(key, expired_seconds: 20) acquire!(key, expired_seconds: expired_seconds) yield release(key) rescue StandardError => e release(key) raise e end |
.release(key) ⇒ Object
19 20 21 22 23 |
# File 'lib/istox/helpers/race_condition_helper.rb', line 19 def release(key) request_redis.del('race-condition||' + key.to_s) log.info("Releasing lock for key: #{key}") end |
.request_redis ⇒ Object
35 36 37 |
# File 'lib/istox/helpers/race_condition_helper.rb', line 35 def request_redis @request_redis ||= ::Istox::RedisManager.request_redis end |