Class: Datadog::AppSec::APISecurity::Sampler
- Inherits:
-
Object
- Object
- Datadog::AppSec::APISecurity::Sampler
- 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
-
#initialize(sample_delay) ⇒ Sampler
constructor
A new instance of Sampler.
- #sample?(request, response) ⇒ Boolean
Constructor Details
#initialize(sample_delay) ⇒ Sampler
Returns a new instance of Sampler.
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_local ⇒ Object
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
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}") = Core::Utils::Time.now.to_i = @cache[key] || 0 return false if - <= @sample_delay_seconds @cache.store(key, ) true end |