fix: mutex timeout and error handling (#8770)

Fixes the follow cases 
- The ensure block released the lock even on LockAcquisitionError
- Custom timeout was not allowed

This also refactored the with_lock method, now the key has to be constructed in the parent function itself

Co-authored-by: Sojan Jose <sojan@pepalo.com>
This commit is contained in:
Shivam Mishra
2024-01-24 15:48:21 +05:30
committed by GitHub
parent a861257f73
commit 3760f206e8
6 changed files with 54 additions and 25 deletions

View File

@@ -4,16 +4,6 @@ RSpec.describe MutexApplicationJob do
let(:lock_manager) { instance_double(Redis::LockManager) }
let(:lock_key) { 'test_key' }
let(:test_mutex_job_class) do
stub_const('TestMutexJob', Class.new(MutexApplicationJob) do
def perform
with_lock('test_key') do
# Do nothing
end
end
end)
end
before do
allow(Redis::LockManager).to receive(:new).and_return(lock_manager)
allow(lock_manager).to receive(:lock).and_return(true)
@@ -22,24 +12,43 @@ RSpec.describe MutexApplicationJob do
describe '#with_lock' do
it 'acquires the lock and yields the block if lock is not acquired' do
expect(lock_manager).to receive(:lock).with(lock_key).and_return(true)
expect(lock_manager).to receive(:lock).with(lock_key, Redis::LockManager::LOCK_TIMEOUT).and_return(true)
expect(lock_manager).to receive(:unlock).with(lock_key).and_return(true)
expect { |b| described_class.new.send(:with_lock, lock_key, &b) }.to yield_control
end
it 'acquires the lock with custom timeout' do
expect(lock_manager).to receive(:lock).with(lock_key, 5.seconds).and_return(true)
expect(lock_manager).to receive(:unlock).with(lock_key).and_return(true)
expect { |b| described_class.new.send(:with_lock, lock_key, 5.seconds, &b) }.to yield_control
end
it 'raises LockAcquisitionError if it cannot acquire the lock' do
allow(lock_manager).to receive(:lock).with(lock_key).and_return(false)
allow(lock_manager).to receive(:lock).with(lock_key, Redis::LockManager::LOCK_TIMEOUT).and_return(false)
expect do
described_class.new.send(:with_lock, lock_key) do
# Do nothing
end
end.to raise_error(MutexApplicationJob::LockAcquisitionError)
expect(lock_manager).not_to receive(:unlock)
end
it 'raises StandardError if it execution raises it' do
allow(lock_manager).to receive(:lock).with(lock_key, Redis::LockManager::LOCK_TIMEOUT).and_return(false)
allow(lock_manager).to receive(:unlock).with(lock_key).and_return(true)
expect do
described_class.new.send(:with_lock, lock_key) do
raise StandardError
end
end.to raise_error(StandardError)
end
it 'ensures that the lock is released even if there is an error during block execution' do
expect(lock_manager).to receive(:lock).with(lock_key).and_return(true)
expect(lock_manager).to receive(:lock).with(lock_key, Redis::LockManager::LOCK_TIMEOUT).and_return(true)
expect(lock_manager).to receive(:unlock).with(lock_key).and_return(true)
expect do