Class: Fbe::Middleware::RateLimit

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/fbe/middleware/rate_limit.rb

Overview

Faraday middleware that caches GitHub API rate limit information.

This middleware intercepts calls to the /rate_limit endpoint and caches the results locally. It tracks the remaining requests count and decrements it for each API call. Every 100 requests, it refreshes the cached data by allowing the request to pass through to the GitHub API.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright (c) 2024-2026 Zerocracy

License

MIT

Examples:

Usage in Faraday middleware stack

connection = Faraday.new do |f|
  f.use Fbe::Middleware::RateLimit
end

Instance Method Summary collapse

Constructor Details

#initialize(app, tracker = nil) ⇒ RateLimit

Initializes the rate limit middleware.

Parameters:

  • app (Object)

    The next middleware in the stack



30
31
32
33
34
35
36
37
38
# File 'lib/fbe/middleware/rate_limit.rb', line 30

def initialize(app, tracker = nil)
  super(app)
  @cached = nil
  @remaining = nil
  @searchleft = nil
  @counter = 0
  @lock = Mutex.new
  tracker[:rate_limit] = self unless tracker.nil?
end

Instance Method Details

#call(env) ⇒ Faraday::Response

Processes the HTTP request and handles rate limit caching.

Parameters:

  • env (Faraday::Env)

    The request environment

Returns:

  • (Faraday::Response)

    The response from cache or the next middleware



44
45
46
47
48
49
50
51
52
53
# File 'lib/fbe/middleware/rate_limit.rb', line 44

def call(env)
  if env.url.path == '/rate_limit'
    @lock.synchronize { handle_rate_limit_request(env) }
  else
    @lock.synchronize { track_request(env.url.path) }
    @app.call(env).on_complete do |response_env|
      @lock.synchronize { sync(response_env, env.url.path) }
    end
  end
end

#remaining(resource = :core) ⇒ Integer?

Returns the remaining requests count tracked by this middleware.

Parameters:

  • resource (Symbol) (defaults to: :core)

    The GitHub API resource (:core or :search)

Returns:

  • (Integer, nil)

    The remaining count, or nil when the resource is absent



59
60
61
62
63
# File 'lib/fbe/middleware/rate_limit.rb', line 59

def remaining(resource = :core)
  @lock.synchronize do
    resource == :search ? @searchleft : @remaining
  end
end