Class: Lockistics::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/lockistics/lock.rb

Constant Summary collapse

LUA_ACQUIRE =
"return redis.call('setnx', KEYS[1], 1) == 1 and redis.call('expire', KEYS[1], KEYS[2]) and 1 or 0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, options = {}) ⇒ Lock

Returns a new instance of Lock.



11
12
13
14
15
16
17
# File 'lib/lockistics/lock.rb', line 11

def initialize(key, options={})
  @key     = key
  @options = Lockistics.configuration.lock_defaults.merge(options)
  @options[:expire] = 999_999_999 unless @options[:expire].to_i > 0 # :expire => false
  @exceeded_before_release = false
  @lock_retries = 0
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



7
8
9
# File 'lib/lockistics/lock.rb', line 7

def key
  @key
end

#lock_retriesObject

Returns the value of attribute lock_retries.



7
8
9
# File 'lib/lockistics/lock.rb', line 7

def lock_retries
  @lock_retries
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/lockistics/lock.rb', line 7

def options
  @options
end

Instance Method Details

#acquire_lockObject



19
20
21
22
23
24
25
26
27
28
# File 'lib/lockistics/lock.rb', line 19

def acquire_lock
  return true if options[:pass_through]
  if got_lock?
    true
  elsif options[:wait]
    wait_for_lock
  else
    false
  end
end

#exceeded_before_release?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/lockistics/lock.rb', line 44

def exceeded_before_release?
  @exceeded_before_release
end

#namespaced_keyObject



53
54
55
# File 'lib/lockistics/lock.rb', line 53

def namespaced_key
  @namespaced_key ||= "#{Lockistics.configuration.namespace}.lock.#{key}"
end

#release_lockObject



48
49
50
51
# File 'lib/lockistics/lock.rb', line 48

def release_lock
  return true if options[:pass_through]
  @exceeded_before_release = redis.del(namespaced_key) == 0
end

#wait_for_lockObject



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/lockistics/lock.rb', line 30

def wait_for_lock
  until got_lock?
    @lock_retries += 1
    if lock_retries <= options[:retries]
      sleep options[:sleep]
    elsif options[:raise]
      raise LockTimeout, "while waiting for #{key}"
    else
      return false
    end
  end
  true
end