Class: Rjob::Scripts::CheckLeadership

Inherits:
RedisScript show all
Defined in:
lib/rjob/scripts/check_leadership.rb

Instance Attribute Summary

Attributes inherited from RedisScript

#sha1

Instance Method Summary collapse

Methods inherited from RedisScript

#key_params

Instance Method Details

#arg_paramsObject



4
5
6
# File 'lib/rjob/scripts/check_leadership.rb', line 4

def arg_params
  %i(worker_name time_now prefix heartbeat_timeout)
end

#lua_scriptObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rjob/scripts/check_leadership.rb', line 8

def lua_script
  <<~LUA
    local worker_name = ARGV[1]
    local time_now = ARGV[2]
    local prefix = ARGV[3]
    local heartbeat_timeout = tonumber(ARGV[4])
    local r = redis
    if r.call('setnx', prefix .. ':leaderworker', worker_name) == 1 then
      return worker_name
    else
      local leader = r.call('get', prefix .. ':leaderworker')
      local last_hb = tonumber(r.call('hget', prefix .. ':worker:' .. leader, 'heartbeat'))
      if last_hb == nil or time_now - last_hb > heartbeat_timeout then
        r.call('set', prefix .. ':leaderworker', worker_name)
        return worker_name
      end
      return leader
    end
  LUA
end