Class: Sidetiq::Lock::Redis

Inherits:
Object
  • Object
show all
Includes:
Sidetiq::Logging
Defined in:
lib/sidetiq/lock/redis.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, timeout = Sidetiq.config.lock_expire) ⇒ Redis


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

def initialize(key, timeout = Sidetiq.config.lock_expire)
  @key = extract_key(key)
  @timeout = timeout
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key


6
7
8
# File 'lib/sidetiq/lock/redis.rb', line 6

def key
  @key
end

#timeoutObject (readonly)

Returns the value of attribute timeout


6
7
8
# File 'lib/sidetiq/lock/redis.rb', line 6

def timeout
  @timeout
end

Class Method Details

.allObject


8
9
10
11
12
13
14
# File 'lib/sidetiq/lock/redis.rb', line 8

def self.all
  Sidekiq.redis do |redis|
    redis.keys("sidetiq:*:lock").map do |key|
      new(key)
    end
  end
end

Instance Method Details

#lockObject


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/sidetiq/lock/redis.rb', line 54

def lock
  Sidekiq.redis do |redis|
    acquired = false

    watch(redis, key) do
      if !redis.exists(key)
        acquired = !!redis.multi do |multi|
          meta = .for_new_lock(key)
          multi.psetex(key, timeout, meta.to_json)
        end
      end
    end

    acquired
  end
end

#meta_dataObject


48
49
50
51
52
# File 'lib/sidetiq/lock/redis.rb', line 48

def 
   ||= Sidekiq.redis do |redis|
    .from_json(redis.get(key))
  end
end

#stale?Boolean


38
39
40
41
42
43
44
45
46
# File 'lib/sidetiq/lock/redis.rb', line 38

def stale?
  pttl = .pttl

  # Consider PTTL of -1 (never set) and larger than the
  # configured lock_expire as invalid. Locks with timestamps
  # older than 1 minute are also considered stale.
  pttl < 0 || pttl >= Sidetiq.config.lock_expire ||
    .timestamp < (Sidetiq.clock.gettime.to_i - 60)
end

#synchronizeObject


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sidetiq/lock/redis.rb', line 21

def synchronize
  Sidekiq.redis do |redis|
    acquired = lock

    if acquired
      debug "Lock: #{key}"

      begin
        yield redis
      ensure
        unlock
        debug "Unlock: #{key}"
      end
    end
  end
end

#unlockObject


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/sidetiq/lock/redis.rb', line 71

def unlock
  Sidekiq.redis do |redis|
    watch(redis, key) do
      if .owner == Sidetiq::Lock::::OWNER
        redis.multi do |multi|
          multi.del(key)
        end

        true
      else
        false
      end
    end
  end
end

#unlock!Object


87
88
89
90
91
# File 'lib/sidetiq/lock/redis.rb', line 87

def unlock!
  Sidekiq.redis do |redis|
    redis.del(key)
  end
end