Class: BetterAuth::RateLimiter::MemoryStore
- Inherits:
-
Object
- Object
- BetterAuth::RateLimiter::MemoryStore
- Defined in:
- lib/better_auth/rate_limiter.rb
Instance Method Summary collapse
- #consume(key, window:, max:) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(clock: -> { Time.now.to_f }, max_entries: MEMORY_STORE_MAX_ENTRIES) ⇒ MemoryStore
constructor
A new instance of MemoryStore.
- #set(key, value, ttl:, update: false) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(clock: -> { Time.now.to_f }, max_entries: MEMORY_STORE_MAX_ENTRIES) ⇒ MemoryStore
Returns a new instance of MemoryStore.
16 17 18 19 20 21 |
# File 'lib/better_auth/rate_limiter.rb', line 16 def initialize(clock: -> { Time.now.to_f }, max_entries: MEMORY_STORE_MAX_ENTRIES) @clock = clock @max_entries = max_entries @entries = {} @mutex = Mutex.new end |
Instance Method Details
#consume(key, window:, max:) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/better_auth/rate_limiter.rb', line 45 def consume(key, window:, max:) @mutex.synchronize do now = clock.call prune!(now, sweep: true) entry = @entries[key] data = entry[:data] if entry && now <= entry[:expires_at] decision = RateLimiter.decide_consume(data, window: window, max: max, now: now) if decision[:allowed] @entries.delete(key) @entries[key] = {data: decision.fetch(:next).merge(key: key), expires_at: now + window.to_f} prune!(now) end decision.slice(:allowed, :retry_after) end end |
#get(key) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/better_auth/rate_limiter.rb', line 23 def get(key) @mutex.synchronize do entry = @entries[key] return nil unless entry if clock.call > entry[:expires_at] @entries.delete(key) return nil end entry[:data] end end |
#set(key, value, ttl:, update: false) ⇒ Object
37 38 39 40 41 42 43 |
# File 'lib/better_auth/rate_limiter.rb', line 37 def set(key, value, ttl:, update: false) @mutex.synchronize do @entries.delete(key) @entries[key] = {data: value, expires_at: clock.call + ttl.to_f} prune!(sweep: @entries.size > @max_entries) end end |
#size ⇒ Object
61 62 63 |
# File 'lib/better_auth/rate_limiter.rb', line 61 def size @mutex.synchronize { @entries.size } end |