Class: R4r::LeakyTokenBucket

Inherits:
TokenBucket show all
Defined in:
lib/r4r/token_bucket.rb

Overview

A leaky bucket expires tokens after approximately ‘ttl` time. Thus, a bucket left alone will empty itself.

Instance Method Summary collapse

Constructor Details

#initialize(ttl_ms:, reserve:, clock: nil) ⇒ LeakyTokenBucket

Creates a new [R4r::LeakyTokenBucket]

Parameters:

  • ttl_ms (Fixnum)

    the (approximate) time in milliseconds after which a token will expire.

  • reserve (Fixnum)

    the number of reserve tokens over the TTL period. That is, every ‘ttl` has `reserve` tokens in addition to the ones added to the bucket.

  • clock (R4r::Clock) (defaults to: nil)

    the current time



95
96
97
98
99
100
# File 'lib/r4r/token_bucket.rb', line 95

def initialize(ttl_ms:, reserve:, clock: nil)
  @ttl_ms = ttl_ms.to_i
  @reserve = reserve.to_i
  @clock = (clock || R4r.clock)
  @window = R4r::WindowedAdder.new(range_ms: ttl_ms, slices: 10, clock: @clock)
end

Instance Method Details

#countObject

See Also:



124
125
126
# File 'lib/r4r/token_bucket.rb', line 124

def count
  @window.sum + @reserve
end

#put(n) ⇒ Object

Raises:

  • (ArgumentError)

See Also:



103
104
105
106
107
108
# File 'lib/r4r/token_bucket.rb', line 103

def put(n)
  n = n.to_i
  raise ArgumentError, "n cannot be nagative" unless n >= 0

  @window.add(n)
end

#try_get(n) ⇒ Object

Raises:

  • (ArgumentError)

See Also:



111
112
113
114
115
116
117
118
119
120
121
# File 'lib/r4r/token_bucket.rb', line 111

def try_get(n)
  n = n.to_i
  raise ArgumentError, "n cannot be nagative" unless n >= 0

  ok = count >= n
  if ok
    @window.add(n * -1)
  end

  ok
end