blob: 7ef3e7384817e17f68a01ab9cc3f0979b690bfa5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# frozen_string_literal: true
module Gitlab
module ExclusiveLeaseHelpers
# Wrapper around ExclusiveLease that adds retry logic
class SleepingLock
delegate :cancel, to: :@lease
MAX_ATTEMPTS = 65
DEFAULT_ATTEMPTS = 10
def initialize(key, timeout:, delay:)
@lease = ::Gitlab::ExclusiveLease.new(key, timeout: timeout)
@delay = delay
@attempts = 0
end
def obtain(max_attempts = DEFAULT_ATTEMPTS)
until held?
raise FailedToObtainLockError, 'Failed to obtain a lock' if attempts >= [max_attempts, MAX_ATTEMPTS].min
sleep(sleep_sec) unless first_attempt?
try_obtain
end
end
def retried?
attempts > 1
end
private
attr_reader :delay, :attempts
def held?
@uuid.present?
end
def try_obtain
@uuid ||= @lease.try_obtain
@attempts += 1
end
def first_attempt?
attempts == 0
end
def sleep_sec
delay.respond_to?(:call) ? delay.call(attempts) : delay
end
end
end
end
|