Class: Sidekiq::Throttled::ExpirableSet

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/sidekiq/throttled/expirable_set.rb

Overview

Set of elements with expirations.

Examples:

set = ExpirableSet.new(10.0)
set.add("a")
sleep(5)
set.add("b")
set.to_a # => ["a", "b"]
sleep(5)
set.to_a # => ["b"]

Instance Method Summary collapse

Constructor Details

#initialize(ttl) ⇒ ExpirableSet

Returns a new instance of ExpirableSet.

Parameters:

  • ttl (Float)

    expiration is seconds

Raises:

  • (ArgumentError)

    if ‘ttl` is not positive Float



24
25
26
27
28
29
# File 'lib/sidekiq/throttled/expirable_set.rb', line 24

def initialize(ttl)
  raise ArgumentError, "ttl must be positive Float" unless ttl.is_a?(Float) && ttl.positive?

  @elements = Concurrent::Map.new
  @ttl      = ttl
end

Instance Method Details

#add(element) ⇒ ExpirableSet

Returns self.

Parameters:

  • element (Object)

Returns:



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sidekiq/throttled/expirable_set.rb', line 33

def add(element)
  # cleanup expired elements to avoid mem-leak
  horizon = now
  expired = @elements.each_pair.select { |(_, sunset)| expired?(sunset, horizon) }
  expired.each { |pair| @elements.delete_pair(*pair) }

  # add new element
  @elements[element] = now + @ttl

  self
end

#each {|Object| ... } ⇒ Object

Yields:

  • (Object)

    Gives each live (not expired) element to the block



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/sidekiq/throttled/expirable_set.rb', line 46

def each
  return to_enum __method__ unless block_given?

  horizon = now

  @elements.each_pair do |element, sunset|
    yield element unless expired?(sunset, horizon)
  end

  self
end