Class: Datadog::Sampling::TokenBucket
- Inherits:
-
RateLimiter
- Object
- RateLimiter
- Datadog::Sampling::TokenBucket
- Defined in:
- lib/ddtrace/sampling/rate_limiter.rb
Overview
Implementation of the Token Bucket metering algorithm for rate limiting.
Instance Attribute Summary collapse
-
#max_tokens ⇒ Object
readonly
Returns the value of attribute max_tokens.
-
#rate ⇒ Object
readonly
Returns the value of attribute rate.
Instance Method Summary collapse
-
#allow?(size) ⇒ Boolean
Checks if a message of provided
sizeconforms with the current bucket limit. -
#available_tokens ⇒ Numeric
Number of tokens currently available.
-
#effective_rate ⇒ Float
Ratio of ‘conformance’ per ‘total messages’ checked on this bucket.
-
#initialize(rate, max_tokens = rate) ⇒ TokenBucket
constructor
A new instance of TokenBucket.
Constructor Details
#initialize(rate, max_tokens = rate) ⇒ TokenBucket
Returns a new instance of TokenBucket.
34 35 36 37 38 39 40 41 42 |
# File 'lib/ddtrace/sampling/rate_limiter.rb', line 34 def initialize(rate, max_tokens = rate) @rate = rate @max_tokens = max_tokens @tokens = max_tokens = 0 = 0 @last_refill = Utils::Time.get_time end |
Instance Attribute Details
#max_tokens ⇒ Object (readonly)
Returns the value of attribute max_tokens.
28 29 30 |
# File 'lib/ddtrace/sampling/rate_limiter.rb', line 28 def max_tokens @max_tokens end |
#rate ⇒ Object (readonly)
Returns the value of attribute rate.
28 29 30 |
# File 'lib/ddtrace/sampling/rate_limiter.rb', line 28 def rate @rate end |
Instance Method Details
#allow?(size) ⇒ Boolean
Checks if a message of provided size conforms with the current bucket limit.
If it does, return true and remove size tokens from the bucket. If it does not, return false without affecting the tokens form the bucket.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/ddtrace/sampling/rate_limiter.rb', line 53 def allow?(size) return false if @rate.zero? return true if @rate < 0 increment_total_count return false if @tokens < size increment_conforming_count @tokens -= size true end |
#available_tokens ⇒ Numeric
Returns number of tokens currently available.
84 85 86 |
# File 'lib/ddtrace/sampling/rate_limiter.rb', line 84 def available_tokens @tokens end |
#effective_rate ⇒ Float
Ratio of ‘conformance’ per ‘total messages’ checked on this bucket.
Returns 1.0 when no messages have been checked yet.
76 77 78 79 80 81 |
# File 'lib/ddtrace/sampling/rate_limiter.rb', line 76 def effective_rate return 0.0 if @rate.zero? return 1.0 if @rate < 0 || .zero? .to_f / end |