Class: Prefab::RateLimitCache

Inherits:
Object
  • Object
show all
Defined in:
lib/prefab/rate_limit_cache.rb

Overview

A key-based rate limiter that considers a key to be fresh if it has been seen within the last ‘duration` seconds.

This is used to rate limit the number of times we send a given context to the server.

Because expected usage is to immediately ‘set` on a `fresh?` miss, we do not prune the data structure on `fresh?` calls. Instead, we manually invoke `prune` periodically from the cache consumer.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration) ⇒ RateLimitCache

Returns a new instance of RateLimitCache.



16
17
18
19
# File 'lib/prefab/rate_limit_cache.rb', line 16

def initialize(duration)
  @data = Concurrent::Map.new
  @duration = duration
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



14
15
16
# File 'lib/prefab/rate_limit_cache.rb', line 14

def data
  @data
end

Instance Method Details

#fresh?(key) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
# File 'lib/prefab/rate_limit_cache.rb', line 21

def fresh?(key)
  timestamp = @data[key]

  return false unless timestamp
  return false if Time.now.utc.to_i - timestamp > @duration

  true
end

#pruneObject



34
35
36
37
38
39
# File 'lib/prefab/rate_limit_cache.rb', line 34

def prune
  now = Time.now.utc.to_i
  @data.each_pair do |key, (timestamp, _)|
    @data.delete(key) if now - timestamp > @duration
  end
end

#set(key) ⇒ Object



30
31
32
# File 'lib/prefab/rate_limit_cache.rb', line 30

def set(key)
  @data[key] = Time.now.utc.to_i
end