Class: Redis::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/robust-redis-lock/version.rb,
lib/redis-lock.rb

Defined Under Namespace

Classes: Error, LostLock, NotLocked, Recovered, Script, Timeout

Constant Summary collapse

VERSION =
'1.3.1'
NAMESPACE =
'redis:lock'

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Lock.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/redis-lock.rb', line 48

def initialize(key, options={})
  @options = options

  @key = key
  @key_group_key = self.class.key_group_key(@options)

  @redis    = @options[:redis] || self.class.redis
  raise "redis cannot be nil" if @redis.nil?

  @timeout    = @options[:timeout]    || self.class.timeout
  @expire     = @options[:expire]     || self.class.expire
  @sleep      = @options[:sleep]      || self.class.sleep
  @token      = @options[:token]
end

Class Attribute Details

.expireObject

Returns the value of attribute expire.



15
16
17
# File 'lib/redis-lock.rb', line 15

def expire
  @expire
end

.key_groupObject

Returns the value of attribute key_group.



16
17
18
# File 'lib/redis-lock.rb', line 16

def key_group
  @key_group
end

.redisObject

Returns the value of attribute redis.



12
13
14
# File 'lib/redis-lock.rb', line 12

def redis
  @redis
end

.sleepObject

Returns the value of attribute sleep.



14
15
16
# File 'lib/redis-lock.rb', line 14

def sleep
  @sleep
end

.timeoutObject

Returns the value of attribute timeout.



13
14
15
# File 'lib/redis-lock.rb', line 13

def timeout
  @timeout
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



8
9
10
# File 'lib/redis-lock.rb', line 8

def key
  @key
end

#recovery_dataObject (readonly)

Returns the value of attribute recovery_data.



9
10
11
# File 'lib/redis-lock.rb', line 9

def recovery_data
  @recovery_data
end

Class Method Details

.all(options = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/redis-lock.rb', line 28

def all(options={})
  redis = options[:redis] || self.redis
  raise "redis cannot be nil" if redis.nil?

  redis.zrangebyscore(key_group_key(options), 0, "+inf").to_a.map do |key_token|
    key, token = key_token.scan(/(.*):(.*)$/).first
    self.new(key, options.merge(:token => token))
  end
end

.expired(options = {}) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/redis-lock.rb', line 18

def expired(options={})
  redis = options[:redis] || self.redis
  raise "redis cannot be nil" if redis.nil?

  redis.zrangebyscore(key_group_key(options), 0, Time.now.to_i).to_a.map do |key_token|
    key, token = key_token.scan(/(.*):(.*)$/).first
    self.new(key, options.merge(:token => token))
  end
end

.key_group_key(options) ⇒ Object



38
39
40
# File 'lib/redis-lock.rb', line 38

def key_group_key(options)
  [NAMESPACE, (options[:key_group] || self.key_group), 'group'].join(':')
end

Instance Method Details

#==(other) ⇒ Object



214
215
216
# File 'lib/redis-lock.rb', line 214

def ==(other)
  @key == other.key
end

#extendObject



171
172
173
# File 'lib/redis-lock.rb', line 171

def extend
  raise Redis::Lock::LostLock.new(self) unless try_extend
end

#lock(options = {}) ⇒ Object

Raises:



76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/redis-lock.rb', line 76

def lock(options={})
  locked   = false
  start_at = now

  while now - start_at < @timeout
    break if locked = try_lock(options)
    sleep @sleep.to_f
  end

  raise Timeout.new(self)   unless locked
  raise Recovered.new(self) if locked == :recovered
end

#namespaced_keyObject



222
223
224
# File 'lib/redis-lock.rb', line 222

def namespaced_key
  NAMESPACE + ':' + @key
end

#nowObject



210
211
212
# File 'lib/redis-lock.rb', line 210

def now
  Time.now
end

#synchronizeObject



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/redis-lock.rb', line 63

def synchronize
  begin
    lock
  rescue Recovered
  end

  begin
    yield
  ensure
    unlock
  end
end

#to_sObject



218
219
220
# File 'lib/redis-lock.rb', line 218

def to_s
  @key
end

#try_extendObject

Raises:



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/redis-lock.rb', line 175

def try_extend
  raise NotLocked.new('extend', self) unless @token

  @@extend_script ||= Script.new <<-LUA
      local key = KEYS[1]
      local key_group = KEYS[2]
      local bare_key = ARGV[1]
      local expires_at = tonumber(ARGV[2])
      local token = ARGV[3]
      local token_key = 'redis:lock:token'

      if redis.call('hget', key, 'token') == token then
        local next_token = redis.call('incr', token_key)

        redis.call('hset', key, 'expires_at', expires_at)
        redis.call('hset', key, 'token', next_token)

        redis.call('zrem', key_group, bare_key .. ':' .. token)
        redis.call('zadd', key_group, expires_at, bare_key .. ':' .. next_token)

        return { next_token, redis.call('hget', key, 'recovery_data') }
      else
        return false
      end
  LUA
  result = @@extend_script.eval(@redis, :keys => [namespaced_key, @key_group_key], :argv => [@key, now.to_i + @expire, @token])

  if result
    @token, @recovery_data = result
    true
  else
    false
  end
end

#try_lock(options = {}) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/redis-lock.rb', line 89

def try_lock(options={})
  raise "recovery_data must be a string" if options[:recovery_data] && !options[:recovery_data].is_a?(String)

  # This script loading is not thread safe (touching a class variable), but
  # that's okay, because the race is harmless.
  @@lock_script ||= Script.new <<-LUA
      local key = KEYS[1]
      local key_group = KEYS[2]
      local bare_key = ARGV[1]
      local now = tonumber(ARGV[2])
      local expires_at = tonumber(ARGV[3])
      local recovery_data = ARGV[4]
      local token_key = 'redis:lock:token'

      local prev_expires_at = tonumber(redis.call('hget', key, 'expires_at'))
      if prev_expires_at and prev_expires_at > now then
        return {'locked', nil, nil}
      end

      local next_token = redis.call('incr', token_key)

      redis.call('hset', key, 'expires_at', expires_at)
      redis.call('zadd', key_group, expires_at, bare_key .. ':' .. next_token)

      local return_value = nil
      if prev_expires_at then
        redis.call('zrem', key_group, bare_key .. ':' .. redis.call('hget', key, 'token'))
        return_value =  {'recovered', next_token, redis.call('hget', key, 'recovery_data')}
      else
        redis.call('hset', key, 'recovery_data', recovery_data)
        return_value =  {'acquired', next_token, nil}
      end

      redis.call('hset', key, 'token', next_token)
      return return_value
  LUA
  result, token, recovery_data = @@lock_script.eval(@redis,
                                                    :keys => [namespaced_key, @key_group_key],
                                                    :argv => [@key, now.to_i, now.to_i + @expire, options[:recovery_data]])

  case result
  when 'locked'
    false
  when 'acquired'
    @token = token
    true
  when 'recovered'
    @token = token
    @recovery_data = recovery_data
    :recovered
  end
end

#try_unlockObject

Raises:



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/redis-lock.rb', line 146

def try_unlock
  raise NotLocked.new('unlock', self) unless @token

  # Since it's possible that the operations in the critical section took a long time,
  # we can't just simply release the lock. The unlock method checks if @expire_at
  # remains the same, and do not release when the lock timestamp was overwritten.
  @@unlock_script ||= Script.new <<-LUA
      local key = KEYS[1]
      local key_group = KEYS[2]
      local bare_key = ARGV[1]
      local token = ARGV[2]

      if redis.call('hget', key, 'token') == token then
        redis.call('del', key)
        redis.call('zrem', key_group, bare_key .. ':' .. token)
        return true
      else
        return false
      end
  LUA
  !!@@unlock_script.eval(@redis, :keys => [namespaced_key, @key_group_key], :argv => [@key, @token]).tap do
    @token = nil
  end
end

#unlockObject



142
143
144
# File 'lib/redis-lock.rb', line 142

def unlock
  raise Redis::Lock::LostLock.new(self) unless try_unlock
end