local-ch / lhc

🚀 Advanced HTTP Client for Ruby. Fueled with interceptors.
GNU General Public License v3.0
43 stars 1 forks source link

Throttle interceptor #156

Closed 10xSebastian closed 5 years ago

10xSebastian commented 5 years ago

This PR introduces the throttle interceptor.

Throttle

The throttle interceptor allows you to raise an exception if a predefined quota of an provider request limit is reached in advance.

  LHC.configure do |c|
    c.interceptors = [LHC::Throttle]
  end
options = { 
  throttle: {
    track: true, # enables tracking of current limit/remaining requests of rate-limiting
    break: '80%', # quota in percent after which errors are raised
    provider: 'local.ch', # name of the provider under which throttling tracking is aggregated,
    limit: { header: 'Rate-Limit-Limit' }, # either a hard-coded integer, or a hash pointing at the response header containing the limit value
    remaining: { header: 'Rate-Limit-Remaining' }, # a hash pointing at the response header containing the current amount of remaining requests
  } 
}

LHC.get('http://local.ch', options)
# { headers: { 'Rate-Limit-Limit' => 100, 'Rate-Limit-Remaining' => 19 } }

LHC.get('http://local.ch', options)
# raises LHC::Throttle::OutOfQuota: Reached predefined quota for local.ch