Class: Redis::Lock

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

Defined Under Namespace

Classes: ErrorBase, LostLock, Recovered, Script, Timeout

Constant Summary collapse

VERSION =
'1.0.0'
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



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/redis-lock.rb', line 35

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
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

.expired(options = {}) ⇒ Object



18
19
20
21
22
23
# 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 { |key| self.new(key, options) }
end

.key_group_key(options) ⇒ Object



25
26
27
# File 'lib/redis-lock.rb', line 25

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

Instance Method Details

#==(other) ⇒ Object



173
174
175
# File 'lib/redis-lock.rb', line 173

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

#extendObject



146
147
148
# File 'lib/redis-lock.rb', line 146

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

#lock(options = {}) ⇒ Object

Raises:



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/redis-lock.rb', line 59

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

#nowObject



169
170
171
# File 'lib/redis-lock.rb', line 169

def now
  Time.now
end

#synchronize(&block) ⇒ Object



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

def synchronize(&block)
  lock
  begin
    block.call
  ensure
    try_unlock
  end
rescue Recovered
end

#to_sObject



177
178
179
# File 'lib/redis-lock.rb', line 177

def to_s
  @key
end

#try_extendObject



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

def try_extend
  @@extend_script ||= Script.new "      local key = KEYS[1]\n      local key_group = KEYS[2]\n      local bare_key = ARGV[1]\n      local expires_at = tonumber(ARGV[2])\n      local token = ARGV[3]\n\n      if redis.call('hget', key, 'token') == token then\n        redis.call('hset', key, 'expires_at', expires_at)\n        redis.call('zadd', key_group, expires_at, bare_key)\n        return true\n      else\n        return false\n      end\n  LUA\n  !!@@extend_script.eval(@redis, :keys => [NAMESPACE + @key, @key_group_key], :argv => [@key, now.to_i + @expire, @token])\nend\n"

#try_lock(options = {}) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
# File 'lib/redis-lock.rb', line 72

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 "      local key = KEYS[1]\n      local key_group = KEYS[2]\n      local bare_key = ARGV[1]\n      local now = tonumber(ARGV[2])\n      local expires_at = tonumber(ARGV[3])\n      local recovery_data = ARGV[4]\n      local token_key = 'redis:lock:token'\n\n      local prev_expires_at = tonumber(redis.call('hget', key, 'expires_at'))\n      if prev_expires_at and prev_expires_at > now then\n        return {'locked', nil, nil}\n      end\n\n      local next_token = redis.call('incr', token_key)\n\n      redis.call('hset', key, 'expires_at', expires_at)\n      redis.call('hset', key, 'token', next_token)\n      redis.call('zadd', key_group, expires_at, bare_key)\n\n      if prev_expires_at then\n        return {'recovered', next_token, redis.call('hget', key, 'recovery_data')}\n      else\n        redis.call('hset', key, 'recovery_data', recovery_data)\n        return {'acquired', next_token, nil}\n      end\n  LUA\n  result, token, recovery_data = @@lock_script.eval(@redis,\n                                                    :keys => [NAMESPACE + @key, @key_group_key],\n                                                    :argv => [@key, now.to_i, now.to_i + @expire, options[:recovery_data]])\n\n  case result\n  when 'locked'\n    false\n  when 'acquired'\n    @token = token\n    true\n  when 'recovered'\n    @token = token\n    @recovery_data = recovery_data\n    :recovered\n  end\nend\n"

#try_unlockObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/redis-lock.rb', line 125

def try_unlock
  # 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 "      local key = KEYS[1]\n      local key_group = KEYS[2]\n      local bare_key = ARGV[1]\n      local token = ARGV[2]\n\n      if redis.call('hget', key, 'token') == token then\n        redis.call('del', key)\n        redis.call('zrem', key_group, bare_key)\n        return true\n      else\n        return false\n      end\n  LUA\n  !!@@unlock_script.eval(@redis, :keys => [NAMESPACE + @key, @key_group_key], :argv => [@key, @token])\nend\n"

#unlockObject



121
122
123
# File 'lib/redis-lock.rb', line 121

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