Class: Hudu::RateThrottleMiddleware

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/hudu/rate_throttle_middleware.rb

Overview

A Faraday middleware for rate limiting requests.

This middleware ensures that the number of requests made through a Faraday connection does not exceed a specified limit within a given time period.

Examples:

Add middleware to a Faraday connection

connection = Faraday.new(url: 'https://api.example.com') do |faraday|
  faraday.use RateThrottleMiddleware, limit: 300, period: 60
  faraday.adapter Faraday.default_adapter
end

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(app, limit: 300, period: 60) ⇒ RateThrottleMiddleware

Initializes the RateThrottleMiddleware.

Examples:

middleware = RateThrottleMiddleware.new(app, limit: 300, period: 60)

Parameters:

  • app (#call)

    The next middleware or the actual Faraday adapter.

  • limit (Integer) (defaults to: 300)

    The maximum number of requests allowed within the specified period. Default is 300.

  • period (Integer) (defaults to: 60)

    The time period in seconds over which the limit applies. Default is 60 seconds.



29
30
31
32
33
34
35
36
# File 'lib/hudu/rate_throttle_middleware.rb', line 29

def initialize(app, limit: 300, period: 60)
  super(app)
  @limit = limit
  @period = period
  @requests = []
  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Instance Method Details

#call(env) ⇒ Object



38
39
40
41
# File 'lib/hudu/rate_throttle_middleware.rb', line 38

def call(env)
  throttle_request
  @app.call(env)
end