Class: Datadog::AppSec::RateLimiter

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/appsec/rate_limiter.rb

Overview

Simple per-thread rate limiter Since AppSec marks sampling to keep on a security event, this limits the flood of egress traces involving AppSec

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rate) ⇒ RateLimiter

Returns a new instance of RateLimiter.



6
7
8
9
# File 'lib/datadog/appsec/rate_limiter.rb', line 6

def initialize(rate)
  @rate = rate
  @timestamps = []
end

Class Method Details

.limit(name, &block) ⇒ Object



32
33
34
# File 'lib/datadog/appsec/rate_limiter.rb', line 32

def limit(name, &block)
  rate_limiter(name).limit(&block)
end

.reset!(name) ⇒ Object

reset a rate limiter: used for testing



37
38
39
# File 'lib/datadog/appsec/rate_limiter.rb', line 37

def reset!(name)
  Thread.current[:datadog_security_trace_rate_limiter] = nil
end

Instance Method Details

#limitObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/datadog/appsec/rate_limiter.rb', line 11

def limit
  now = Time.now.to_f

  loop do
    oldest = @timestamps.first

    break if oldest.nil? || now - oldest < 1

    @timestamps.shift
  end

  @timestamps << now

  if (count = @timestamps.count) <= @rate
    yield
  else
    Datadog.logger.debug { "Rate limit hit: #{count}/#{@rate} AppSec traces/second" }
  end
end