with_advisory_lock icon indicating copy to clipboard operation
with_advisory_lock copied to clipboard

Why not raise exception when the lock couldn't be acquired in the given timeout?

Open sullerandras opened this issue 2 years ago • 1 comments

I know that this is documented behaviour but it trips me over every time when i use this gem. I think it would be more sensible to raise an error if it couldn't acquire the lock, instead of simply not executing the block. The caller could handle the exception if executing the block was optional.

sullerandras avatar Jan 12 '22 10:01 sullerandras

Fair point. You wanna take a it ?

seuros avatar Jul 30 '22 17:07 seuros

Needed something similar, wrote a wrapper over theadvisory_lock to achieve to this

module AdvisoryLockManager
  class LockAcquireError < StandardError; end

  def self.with_lock!(lock_id, opts, &block)
    raise LockAcquireError.new("Failed to acquire error for #{lock_id}") unless with_lock(lock_id, opts, &block)
  end

  def self.with_lock(lock_id, opts = {}, &block)
    ActiveRecord::Base.with_advisory_lock(lock_id, opts) do
      yield
    end
  end
end

Use it like this

AdvisoryLockManager.with_lock!("hachi",{timeout_seconds: 1}) { sleep 10 }

Screenshot 2022-11-23 at 6 41 21 PM

Patch should ideally look like this at https://github.com/ClosureTree/with_advisory_lock/blob/master/lib/with_advisory_lock/concern.rb

module ClassMethods
      def with_advisory_lock(lock_name, options = {}, &block)
        result = with_advisory_lock_result(lock_name, options, &block)
        result.lock_was_acquired? ? result.result : false
      end
   
      def with_advisory_lock!(lock_name, options = {}, &block)
        raise WithAdvisoryLock::LockAcquireError.new("Failed to acquire lock for #{lock_name}" unless with_advisory_lock(lock_name,options,&block)
      end
      ......
 end  

I can submit a patch to the library if it is needed @seuros ?

jatindhankhar avatar Nov 23 '22 13:11 jatindhankhar

yes

seuros avatar Nov 23 '22 17:11 seuros

@seuros This should be good right ?

#65

jatindhankhar avatar Nov 24 '22 15:11 jatindhankhar