lockable.rb 749 B

12345678910111213141516171819
  1. # frozen_string_literal: true
  2. module Lockable
  3. # @param [String] lock_name
  4. # @param [ActiveSupport::Duration] autorelease Automatically release the lock after this time
  5. # @param [Boolean] raise_on_failure Raise an error if a lock cannot be acquired, or fail silently
  6. # @raise [Mastodon::RaceConditionError]
  7. def with_redis_lock(lock_name, autorelease: 15.minutes, raise_on_failure: true)
  8. with_redis do |redis|
  9. RedisLock.acquire(redis: redis, key: "lock:#{lock_name}", autorelease: autorelease.seconds) do |lock|
  10. if lock.acquired?
  11. yield
  12. elsif raise_on_failure
  13. raise Mastodon::RaceConditionError, "Could not acquire lock for #{lock_name}, try again later"
  14. end
  15. end
  16. end
  17. end
  18. end