Sha256: c9a0f2aa257f26c083020869f31cdc409e8b22e1ce6ae5564f9074f6757f28a8

Contents?: true

Size: 1.36 KB

Versions: 17

Compression:

Stored size: 1.36 KB

Contents

module Datadog
  module AppSec
    # 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 RateLimiter
      def initialize(rate)
        @rate = rate
        @timestamps = []
      end

      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

      class << self
        def limit(name, &block)
          rate_limiter(name).limit(&block)
        end

        # reset a rate limiter: used for testing
        def reset!(name)
          Thread.current[:datadog_security_trace_rate_limiter] = nil
        end

        protected

        def rate_limiter(name)
          case name
          when :traces
            Thread.current[:datadog_security_trace_rate_limiter] ||= RateLimiter.new(trace_rate_limit)
          else
            raise "unsupported rate limiter: #{name.inspect}"
          end
        end

        def trace_rate_limit
          Datadog.configuration.appsec.trace_rate_limit
        end
      end
    end
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
ddtrace-1.23.3 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.23.2 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.23.1 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.22.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.21.1 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.21.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.20.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.19.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.18.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.17.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.16.2 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.16.1 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.16.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.15.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.14.0 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.13.1 lib/datadog/appsec/rate_limiter.rb
ddtrace-1.13.0 lib/datadog/appsec/rate_limiter.rb