Class: Sidekiq::Throttler::Storage::Redis

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/sidekiq/throttler/storage/redis.rb

Overview

Stores job executions in Redis lists.

Timestamps in each list are ordered with the oldest on the right. Values are inserted on the left (LPUSH) & pruned from the right (RPOP)

Instance Method Summary collapse

Instance Method Details

#append(key, time) ⇒ Object

Add a new entry to the hash.

Parameters:

  • key (String)

    The key to append to

  • The (Time)

    time to insert


65
66
67
68
69
# File 'lib/sidekiq/throttler/storage/redis.rb', line 65

def append(key, time)
  Sidekiq.redis do |conn|
    conn.lpush(namespace_key(key), time.to_i)
  end
end

#count(key) ⇒ Fixnum

Number of executions for +key+.

Parameters:

  • Key (String)

    to fetch count for

Returns:

  • (Fixnum)

    Execution count


20
21
22
23
24
# File 'lib/sidekiq/throttler/storage/redis.rb', line 20

def count(key)
  Sidekiq.redis do |conn|
    conn.llen(namespace_key(key))
  end
end

#prune(key, cutoff) ⇒ Object

Remove entries older than +cutoff+.

Parameters:

  • key (String)

    The key to prune

  • cutoff (Time)

    Oldest allowable time


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/sidekiq/throttler/storage/redis.rb', line 34

def prune(key, cutoff)
  # Repeatedly pop from the right of the list until we encounter
  # a value greater than the cutoff.
  #
  # We compare popped values to account for race conditions,
  # pushing them back if they don't match.
  Sidekiq.redis do |conn|
    prune_one = ->(timestamp) {
      if timestamp && timestamp.to_i <= cutoff.to_i
        last = conn.rpop(namespace_key(key))
        if last == timestamp
          true
        else
          conn.rpush(namespace_key(key), last)
          nil
        end
      end
    }

    loop while prune_one.call(conn.lindex(namespace_key(key), -1))
  end
end

#resetObject

Clear all data from storage.


73
74
75
76
77
78
79
# File 'lib/sidekiq/throttler/storage/redis.rb', line 73

def reset
  Sidekiq.redis do |conn|
    conn.keys(namespace_key("*")).each do |key|
      conn.del(key)
    end
  end
end