Class: Rack::Throttle::SlidingWindow::LeakyBucket

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/throttle/limiters/sliding_window.rb

Overview

LeakyBucket is an internal class used to implement the SlidingWindow limiter strategy. It is a (slightly tweaked) implementation of the Leaky Bucket Algorithm.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(maximum, outflow) ⇒ LeakyBucket

Returns a new instance of LeakyBucket.

Parameters:

  • maximum (Integer)
  • outflow (Float)


68
69
70
71
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 68

def initialize(maximum, outflow)
  @maximum, @outflow = maximum, outflow
  @count, @last_touched = 0, Time.now
end

Instance Attribute Details

#countObject (readonly)

Returns the value of attribute count.



63
64
65
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 63

def count
  @count
end

#last_touchedObject (readonly)

Returns the value of attribute last_touched.



63
64
65
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 63

def last_touched
  @last_touched
end

#maximumObject

Returns the value of attribute maximum.



62
63
64
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 62

def maximum
  @maximum
end

#outflowObject

Returns the value of attribute outflow.



62
63
64
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 62

def outflow
  @outflow
end

Instance Method Details

#full?Boolean

Returns:

  • (Boolean)


89
90
91
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 89

def full?
  count == maximum
end

#increment!Object



83
84
85
86
87
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 83

def increment!
  @count = 0 if count < 0
  @count += 1
  @count = maximum if count > maximum
end

#leak!Object



73
74
75
76
77
78
79
80
81
# File 'lib/rack/throttle/limiters/sliding_window.rb', line 73

def leak!
  t = Time.now
  time = t - last_touched
  loss = (outflow * time).to_f
  if loss > 0
    @count -= loss
    @last_touched = t
  end
end