Class: Sidekiq::Ultimate::ExpirableSet

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

Overview

List that tracks when elements were added and enumerates over those not older than ‘ttl` seconds ago.

## Implementation

Internally list holds an array of arrays. Thus ecah element is a tuple of monotonic timestamp (when element was added) and element itself:

[
  [ 123456.7890, "default" ],
  [ 123456.7891, "urgent" ],
  [ 123457.9621, "urgent" ],
  ...
]

It does not deduplicates elements. Eviction happens only upon elements retrieval (see #each).

Instance Method Summary collapse

Constructor Details

#initializeExpirableSet

Create a new ExpirableSet instance.



33
34
35
36
# File 'lib/sidekiq/ultimate/expirable_set.rb', line 33

def initialize
  @set = Hash.new(0.0)
  @mon = Monitor.new
end

Instance Method Details

#add(element, ttl:) ⇒ ExpirableSet

Adds given element into the set.

Parameters:

  • ttl (Numeric)

    elements time-to-live in seconds

Returns:



50
51
52
53
54
55
56
57
58
59
# File 'lib/sidekiq/ultimate/expirable_set.rb', line 50

def add(element, ttl:)
  @mon.synchronize do
    expires_at = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + ttl

    # do not allow decrease element's expiry
    @set[element] = expires_at if @set[element] < expires_at
  end

  self
end

#each {|element| ... } ⇒ Enumerator, ExpirableSet

Evicts expired elements and calls the given block once for each element left, passing that element as a parameter.

Yields:

  • (element)

Returns:

  • (Enumerator)

    if no block given

  • (ExpirableSet)

    self if block given



67
68
69
70
71
72
73
74
75
76
# File 'lib/sidekiq/ultimate/expirable_set.rb', line 67

def each
  return to_enum __method__ unless block_given?

  @mon.synchronize do
    horizon = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
    @set.each { |k, v| yield(k) if horizon <= v }
  end

  self
end