Class: Prefab::RateLimitCache
- Inherits:
-
Object
- Object
- Prefab::RateLimitCache
- 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
-
#data ⇒ Object
readonly
Returns the value of attribute data.
Instance Method Summary collapse
- #fresh?(key) ⇒ Boolean
-
#initialize(duration) ⇒ RateLimitCache
constructor
A new instance of RateLimitCache.
- #prune ⇒ Object
- #set(key) ⇒ Object
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
#data ⇒ Object (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
21 22 23 24 25 26 27 28 |
# File 'lib/prefab/rate_limit_cache.rb', line 21 def fresh?(key) = @data[key] return false unless return false if Time.now.utc.to_i - > @duration true end |
#prune ⇒ Object
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, (, _)| @data.delete(key) if now - > @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 |