Class: SpeedLimiter::Throttle

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/speed_limiter/throttle.rb

Overview

with actual throttle limits

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config:, **params) {|count| ... } ⇒ Throttle

Returns a new instance of Throttle.

Parameters:

  • params (Hash)

    a customizable set of options

Options Hash (**params):

  • :key (String)

    key name

  • :limit (Integer)

    limit count per period

  • :period (Integer)

    period time (seconds)

  • :on_throttled (Proc)

    Block called when limit exceeded, with ttl(Float) and key as argument

Yields:

  • (count)

    Block called to not reach limit

Yield Parameters:

  • count (Integer)

    count of period

Yield Returns:

  • (any)

    block return value



19
20
21
22
23
# File 'lib/speed_limiter/throttle.rb', line 19

def initialize(config:, **params, &block)
  @config = config
  @params = ThrottleParams.new(config: config, **params)
  @block = block
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



24
25
26
# File 'lib/speed_limiter/throttle.rb', line 24

def block
  @block
end

#configObject (readonly)

Returns the value of attribute config.



24
25
26
# File 'lib/speed_limiter/throttle.rb', line 24

def config
  @config
end

#paramsObject (readonly)

Returns the value of attribute params.



24
25
26
# File 'lib/speed_limiter/throttle.rb', line 24

def params
  @params
end

Instance Method Details

#throttleObject



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/speed_limiter/throttle.rb', line 28

def throttle
  return block.call(create_state) if config.no_limit?

  loop do
    count, ttl = redis.increment(redis_key, period)

    break(block.call(create_state(count: count, ttl: ttl))) if count <= limit

    wait_for_interval(count)
  end
end