Class: Datadog::Core::TokenBucket
- Inherits:
-
RateLimiter
- Object
- RateLimiter
- Datadog::Core::TokenBucket
- Includes:
- RefillableBucket
- Defined in:
- lib/datadog/core/rate_limiter.rb
Overview
Implementation of the Token Bucket metering algorithm for rate limiting.
Instance Attribute Summary
Attributes included from RefillableBucket
#last_refill, #max_tokens, #rate
Instance Method Summary collapse
-
#allow?(size = 1) ⇒ Boolean
Checks if a message of provided
sizeconforms with the current bucket limit. -
#current_window_rate ⇒ Float
Ratio of 'conformance' per 'total messages' checked on this bucket.
-
#effective_rate ⇒ Float
Ratio of 'conformance' per 'total messages' checked averaged for the past 2 buckets.
-
#initialize(rate, max_tokens = rate) ⇒ TokenBucket
constructor
Initializes the bucket balance and the conformance-rate statistics windows.
Methods included from RefillableBucket
#available_tokens, #balance_at
Constructor Details
#initialize(rate, max_tokens = rate) ⇒ TokenBucket
Initializes the bucket balance and the conformance-rate statistics windows.
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/datadog/core/rate_limiter.rb', line 46 def initialize(rate, max_tokens = rate) super() initialize_bucket(rate, max_tokens) @total_messages = 0 @conforming_messages = 0 @prev_conforming_messages = nil @prev_total_messages = nil @current_window = nil end |
Instance Method Details
#allow?(size = 1) ⇒ 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 from the bucket.
67 68 69 70 71 |
# File 'lib/datadog/core/rate_limiter.rb', line 67 def allow?(size = 1) allowed = should_allow?(size) update_rate_counts(allowed) allowed end |
#current_window_rate ⇒ Float
Ratio of 'conformance' per 'total messages' checked on this bucket
Returns 1.0 when no messages have been checked yet.
98 99 100 101 102 |
# File 'lib/datadog/core/rate_limiter.rb', line 98 def current_window_rate return 1.0 if @total_messages.zero? @conforming_messages.to_f / @total_messages end |
#effective_rate ⇒ Float
Ratio of 'conformance' per 'total messages' checked averaged for the past 2 buckets
Returns 1.0 when no messages have been checked yet.
79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/datadog/core/rate_limiter.rb', line 79 def effective_rate return 0.0 if @rate.zero? return 1.0 if @rate < 0 || @total_messages.zero? return current_window_rate if @prev_conforming_messages.nil? || @prev_total_messages.nil? # Steep: Due to https://github.com/soutaro/steep/issues/477, # the previous nil check does not narrow type to Integer # The annotation fixes the typing error, but it takes effect in the method # @type ivar @prev_total_messages: Integer (@conforming_messages.to_f + @prev_conforming_messages.to_f) / (@total_messages + @prev_total_messages) end |