Class: Datadog::Core::BorrowingTokenBucket
- Inherits:
-
Object
- Object
- Datadog::Core::BorrowingTokenBucket
- Includes:
- RefillableBucket
- Defined in:
- lib/datadog/core/borrowing_token_bucket.rb
Overview
Token bucket that permits consumption below zero. The deficit refills over
time at rate.
Instance Attribute Summary
Attributes included from RefillableBucket
#last_refill, #max_tokens, #rate
Instance Method Summary collapse
-
#available? ⇒ Boolean
Whether the balance is currently positive.
-
#consume(size: 1) ⇒ void
Removes
sizetokens; the balance goes below zero whensizeexceeds the available tokens. -
#initialize(rate, max_tokens: rate) ⇒ void
constructor
Initializes the balance at
max_tokens, permitting the balance to go below zero thereafter. -
#try_consume ⇒ Boolean
Removes one token when the balance is positive after a refill, so a check-and-consume reads the clock and runs the refill arithmetic once.
Methods included from RefillableBucket
#available_tokens, #balance_at
Constructor Details
#initialize(rate, max_tokens: rate) ⇒ void
Initializes the balance at max_tokens, permitting the balance to go
below zero thereafter.
20 21 22 23 24 25 |
# File 'lib/datadog/core/borrowing_token_bucket.rb', line 20 def initialize(rate, max_tokens: rate) initialize_bucket(rate, max_tokens) raise ArgumentError, "rate must not be negative: #{rate}" if rate < 0 raise ArgumentError, "max_tokens must not be negative: #{max_tokens}" if max_tokens < 0 end |
Instance Method Details
#available? ⇒ Boolean
Returns whether the balance is currently positive.
28 29 30 |
# File 'lib/datadog/core/borrowing_token_bucket.rb', line 28 def available? balance_at(Core::Utils::Time.get_time) > 0 end |
#consume(size: 1) ⇒ void
This method returns an undefined value.
Removes size tokens; the balance goes below zero when size
exceeds the available tokens.
38 39 40 41 42 43 44 45 |
# File 'lib/datadog/core/borrowing_token_bucket.rb', line 38 def consume(size: 1) raise ArgumentError, "size must be a number: #{size}" unless size.is_a?(Numeric) raise ArgumentError, "size must not be negative: #{size}" if size < 0 refill @tokens = available_tokens - size nil end |
#try_consume ⇒ Boolean
Removes one token when the balance is positive after a refill, so a check-and-consume reads the clock and runs the refill arithmetic once.
51 52 53 54 55 56 57 |
# File 'lib/datadog/core/borrowing_token_bucket.rb', line 51 def try_consume refill return false unless available_tokens > 0 @tokens = available_tokens - 1 true end |