Created
November 18, 2023 00:46
-
-
Save ixti/77f344ea999ee5046c3368f0cbeb00e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require "concurrent" | |
module Sidekiq | |
module Throttled | |
class ExpirableSet | |
attr_reader :default_ttl | |
def initialize(default_ttl:) | |
@default_ttl = default_ttl.to_i | |
@elements = Concurrent::Map.new | |
end | |
def add(element, ttl: default_ttl) | |
@elements[element] = now + ttl.to_i | |
end | |
def to_a | |
now.then do |horizon| | |
@elements.each_pair.filter_map do |element, sunset| | |
element if horizon <= sunset | |
end | |
end | |
end | |
private | |
def now | |
::Process.clock_gettime(::Process::CLOCK_MONOTONIC) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment