Sha256: 3a0266b1ed684712d33114952957421c4f1dbcf08d185da094cf8dc9ed29b3f8

Contents?: true

Size: 981 Bytes

Versions: 20

Compression:

Stored size: 981 Bytes

Contents

# Wraps platform-api and adds API rate limits
#
# Instead of:
#
#     platform_api.pipeline.create(name: @name)
#
# Use:
#
#     api_rate_limit = ApiRateLimit.new(platform_api)
#     api_rate_limit.call.pipeline.create(name: @name)
#
class ApiRateLimit
  def initialize(platform_api)
    @platform_api = platform_api
    @capacity = 1
    @called   = 0
  end


  # Sleeps for progressively longer when api rate limit capacity
  # is lower.
  #
  # Unfortunatley `@platform_api.rate_limit` is an extra API
  # call, so by checking our limit, we also are using our limit 😬
  # to partially mitigate this, only check capacity every 5
  # api calls, or if the current capacity is under 1000
  def call
    @called += 1

    if @called > 5 || @capacity < 1000
      @called = 0
      @capacity = @platform_api.rate_limit.info["remaining"]
    end

    sleep_time = (60/@capacity) if @capacity > 0.1 # no divide by zero
    sleep(sleep_time || 60)

    return @platform_api
  end
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
heroku_hatchet-5.0.3 lib/hatchet/api_rate_limit.rb
heroku_hatchet-5.0.2 lib/hatchet/api_rate_limit.rb
heroku_hatchet-5.0.1 lib/hatchet/api_rate_limit.rb
heroku_hatchet-5.0.0 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.1.2 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.1.1 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.1.0 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.13 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.12 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.11 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.10 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.9 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.8 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.7 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.6 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.5 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.4 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.3 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.2 lib/hatchet/api_rate_limit.rb
heroku_hatchet-4.0.1 lib/hatchet/api_rate_limit.rb