Class: Datadog::Core::BorrowingTokenBucket

Inherits:
Object
  • Object
show all
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

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.

Parameters:

  • rate (Numeric) —

    refill rate, in tokens per second

  • max_tokens (Numeric) (defaults to: rate) —

    ceiling the balance refills toward

Raises:

  • (ArgumentError) —

    when rate or max_tokens is negative, or when either is not a number



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.

Returns:

  • (Boolean) —

    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.

Parameters:

  • size (Numeric) (defaults to: 1) —

    tokens to remove

Raises:

  • (ArgumentError) —

    when size is negative or is not a number



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.

Returns:

  • (Boolean) —

    whether a token was consumed



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