Class: Datadog::AppSec::APISecurity::Sampler

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

Overview

A thread-local sampler for API security based on defined delay between samples with caching capability.

Constant Summary collapse

THREAD_KEY =
:datadog_appsec_api_security_sampler
MAX_CACHE_SIZE =
4096

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sample_delay) ⇒ Sampler

Returns a new instance of Sampler.

Raises:

  • (ArgumentError)


37
38
39
40
41
42
# File 'lib/datadog/appsec/api_security/sampler.rb', line 37

def initialize(sample_delay)
  raise ArgumentError, 'sample_delay must be an Integer' unless sample_delay.is_a?(Integer)

  @cache = LRUCache.new(MAX_CACHE_SIZE)
  @sample_delay_seconds = sample_delay
end

Class Method Details

.reset!Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



26
27
28
# File 'lib/datadog/appsec/api_security/sampler.rb', line 26

def reset!
  Thread.current.thread_variable_set(THREAD_KEY, nil)
end

.thread_localObject



18
19
20
21
22
23
# File 'lib/datadog/appsec/api_security/sampler.rb', line 18

def thread_local
  sampler = Thread.current.thread_variable_get(THREAD_KEY)
  return sampler unless sampler.nil?

  Thread.current.thread_variable_set(THREAD_KEY, new(sample_delay))
end

Instance Method Details

#sample?(request, response) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/datadog/appsec/api_security/sampler.rb', line 44

def sample?(request, response)
  return true if @sample_delay_seconds.zero?

  key = Zlib.crc32("#{request.request_method}#{RouteExtractor.route_pattern(request)}#{response.status}")
  current_timestamp = Core::Utils::Time.now.to_i
  cached_timestamp = @cache[key] || 0

  return false if current_timestamp - cached_timestamp <= @sample_delay_seconds

  @cache.store(key, current_timestamp)
  true
end