Module: Coil::QueueLocking

Extended by:
QueueLocking
Includes:
Kernel
Included in:
QueueLocking
Defined in:
lib/coil/queue_locking.rb

Defined Under Namespace

Classes: Key, LockWaitTimeout

Instance Method Summary collapse

Instance Method Details

#locking(queue_type:, message_type:, message_keys:, wait: true, &blk) ⇒ Object

Run an action while holding advisory locks on a list of keys for messages of a given type in a given queue.

By default, this waits until the locks can be obtained. To instead raise a QueueLocking::LockWaitTimeout error if locks cannot be obtained immediately, specify ‘wait: false`.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/coil/queue_locking.rb', line 54

def locking(queue_type:, message_type:, message_keys:, wait: true, &blk)
  keys = message_keys.compact.map do |message_key|
    Key.new(queue_type:, message_type:, message_key:)
  end

  # Acquire locks in a consistent order to avoid deadlocks.
  ks = keys.uniq(&:int64).sort_by(&:int64).reverse

  fn = ks.reduce(blk) do |f, key|
    -> do
      with_lock(key:, wait:, &f)
    end
  end

  ApplicationRecord.transaction(&fn)
end