Class: Fbe::Middleware::RateLimit
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Fbe::Middleware::RateLimit
- 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
Instance Method Summary collapse
-
#call(env) ⇒ Faraday::Response
Processes the HTTP request and handles rate limit caching.
-
#initialize(app, tracker = nil) ⇒ RateLimit
constructor
Initializes the rate limit middleware.
-
#remaining(resource = :core) ⇒ Integer?
Returns the remaining requests count tracked by this middleware.
Constructor Details
#initialize(app, tracker = nil) ⇒ RateLimit
Initializes the rate limit middleware.
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.
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.
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 |