Class: SidekiqVigil::LeaderElection

Inherits:
Object
  • Object
show all
Defined in:
lib/sidekiq_vigil/leader_election.rb

Constant Summary collapse

EXTEND_SCRIPT =
<<~LUA
  if redis.call("get", KEYS[1]) == ARGV[1] then
    return redis.call("pexpire", KEYS[1], ARGV[2])
  end
  return 0
LUA
RELEASE_SCRIPT =
<<~LUA
  if redis.call("get", KEYS[1]) == ARGV[1] then
    return redis.call("del", KEYS[1])
  end
  return 0
LUA

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(storage:, ttl:, token: SecureRandom.uuid) ⇒ LeaderElection

Returns a new instance of LeaderElection.



22
23
24
25
26
27
# File 'lib/sidekiq_vigil/leader_election.rb', line 22

def initialize(storage:, ttl:, token: SecureRandom.uuid)
  @storage = storage
  @ttl_ms = (ttl * 1000).to_i
  @token = token
  @leader = false
end

Instance Attribute Details

#tokenObject (readonly)

Returns the value of attribute token.



20
21
22
# File 'lib/sidekiq_vigil/leader_election.rb', line 20

def token
  @token
end

Instance Method Details

#acquireObject



29
30
31
# File 'lib/sidekiq_vigil/leader_election.rb', line 29

def acquire
  @leader = storage.acquire_lock("leader", token, ttl_ms: ttl_ms)
end

#extendObject



33
34
35
# File 'lib/sidekiq_vigil/leader_election.rb', line 33

def extend
  @leader = storage.eval(EXTEND_SCRIPT, keys: ["leader"], argv: [token, ttl_ms]).to_i == 1
end

#leader?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/sidekiq_vigil/leader_election.rb', line 37

def leader?
  @leader
end

#releaseObject



41
42
43
44
45
46
47
48
# File 'lib/sidekiq_vigil/leader_election.rb', line 41

def release
  released = storage.eval(RELEASE_SCRIPT, keys: ["leader"], argv: [token]).to_i == 1
  @leader = false
  released
rescue StandardError
  @leader = false
  false
end