Class: GRApiManager::RateLimiter::MemoryStore

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

Overview

In-memory sliding-window store using Mutex.

Instance Method Summary collapse

Constructor Details

#initializeMemoryStore

Returns a new instance of MemoryStore.



194
195
196
197
# File 'lib/gr_api_manager.rb', line 194

def initialize
  @store = Hash.new { |h, k| h[k] = [] }
  @mutex = Mutex.new
end

Instance Method Details

#allow?(key, max, window) ⇒ Boolean

Returns:

  • (Boolean)


199
200
201
202
203
204
205
206
207
208
# File 'lib/gr_api_manager.rb', line 199

def allow?(key, max, window)
  @mutex.synchronize do
    now    = Time.now.to_f
    cutoff = now - window
    @store[key].reject! { |t| t < cutoff }
    return false if @store[key].size >= max
    @store[key] << now
    true
  end
end

#cleanup!(window) ⇒ Object



218
219
220
221
222
223
224
# File 'lib/gr_api_manager.rb', line 218

def cleanup!(window)
  @mutex.synchronize do
    cutoff = Time.now.to_f - window
    @store.each_value { |times| times.reject! { |t| t < cutoff } }
    @store.delete_if  { |_, times| times.empty? }
  end
end

#remaining(key, max, window) ⇒ Object



210
211
212
213
214
215
216
# File 'lib/gr_api_manager.rb', line 210

def remaining(key, max, window)
  @mutex.synchronize do
    cutoff = Time.now.to_f - window
    active = @store[key].count { |t| t >= cutoff }
    [max - active, 0].max
  end
end

#reset!(key = nil) ⇒ Object



226
227
228
229
230
231
232
233
234
# File 'lib/gr_api_manager.rb', line 226

def reset!(key = nil)
  @mutex.synchronize do
    if key
      @store.delete(key)
    else
      @store.clear
    end
  end
end

#sizeObject



236
237
238
# File 'lib/gr_api_manager.rb', line 236

def size
  @mutex.synchronize { @store.size }
end