Class: RailsRateLimit::Stores::Memcached

Inherits:
Base
  • Object
show all
Defined in:
lib/rails_rate_limit/stores/memcached.rb

Instance Method Summary collapse

Methods inherited from Base

resolve

Constructor Details

#initializeMemcached

Returns a new instance of Memcached.



6
7
8
9
# File 'lib/rails_rate_limit/stores/memcached.rb', line 6

def initialize
  @memcached = RailsRateLimit.configuration.memcached_connection
  raise "Memcached connection not configured" unless @memcached
end

Instance Method Details

#count_requests(key, period) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rails_rate_limit/stores/memcached.rb', line 11

def count_requests(key, period)
  now = current_time
  min_time = now - period
  key = cache_key(key)

  timestamps = get_timestamps(key)
  valid_timestamps = cleanup_old_requests(timestamps, min_time)

  count = valid_timestamps.size

  if valid_timestamps.empty?
    begin
      @memcached.delete(key)
    rescue StandardError
      nil
    end
    0
  else
    begin
      @memcached.set(key, valid_timestamps, period)
    rescue StandardError
      nil
    end
    count
  end
rescue StandardError => e
  RailsRateLimit.logger&.error("RailsRateLimit::Stores::Memcached#count_requests error: #{e.message}")
  0
end

#record_request(key, period) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rails_rate_limit/stores/memcached.rb', line 41

def record_request(key, period)
  now = current_time
  min_time = now - period
  key = cache_key(key)

  timestamps = get_timestamps(key)
  timestamps = cleanup_old_requests(timestamps, min_time)
  timestamps << now
  count = timestamps.size

  begin
    @memcached.set(key, timestamps, period)
  rescue StandardError
    nil
  end
  count
rescue StandardError => e
  RailsRateLimit.logger&.error("RailsRateLimit::Stores::Memcached#record_request error: #{e.message}")
  0
end