Class: ThrottleMachines::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/throttle_machines/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, &config_block) ⇒ Middleware

Returns a new instance of Middleware.



5
6
7
8
9
10
# File 'lib/throttle_machines/middleware.rb', line 5

def initialize(app, &config_block)
  @app = app
  @rules = []

  instance_eval(&config_block) if config_block
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/throttle_machines/middleware.rb', line 12

def call(env)
  request = Rack::Request.new(env)

  @rules.each do |rule|
    next unless rule[:matcher].call(request)

    key = rule[:key_generator].call(request)
    limiter = ThrottleMachines.limiter(
      key,
      limit: rule[:limit],
      period: rule[:period],
      algorithm: rule[:algorithm]
    )

    return rate_limit_response(limiter) unless limiter.allow?
  end

  @app.call(env)
rescue ThrottledError => e
  rate_limit_response(e.limiter)
end

#throttle(path, limit:, period:, by: :ip, algorithm: :gcra) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/throttle_machines/middleware.rb', line 34

def throttle(path, limit:, period:, by: :ip, algorithm: :gcra)
  @rules << {
    matcher: build_matcher(path),
    key_generator: build_key_generator(by),
    limit: limit,
    period: period,
    algorithm: algorithm
  }
end