Sha256: 0e148765bbb226e8a965962b1fcf1549ac67007e1f6c455ff705ba61dca587d8

Contents?: true

Size: 1.08 KB

Versions: 9

Compression:

Stored size: 1.08 KB

Contents

module Scrivito
class CmsRestApi
module RateLimit
  def self.retry_on_rate_limit(request_timer, &block)
    internal_retry(block, request_timer, 0)
  end

  private_class_method def self.internal_retry(request_proc, request_timer, retry_count)
    response = request_proc.call

    if failed_because_of_rate_limit?(response)
      time_to_sleep = calculate_time_to_sleep(response['Retry-After'].to_f, retry_count)

      if request_timer.cover?(Time.now + time_to_sleep.seconds)
        Scrivito::Warning.warn("Rate limit exceeded. Will retry after #{time_to_sleep} seconds.")
        sleep time_to_sleep
        internal_retry(request_proc, request_timer, retry_count + 1)
      else
        raise Scrivito::RateLimitExceeded.new('rate limit exceeded', 429)
      end
    else
      response
    end
  end

  private_class_method def self.calculate_time_to_sleep(retry_after, retry_count)
    backoff_wait_time = 2 ** retry_count * 0.5
    [backoff_wait_time, retry_after].max
  end

  private_class_method def self.failed_because_of_rate_limit?(response)
    response.code == '429'
  end
end
end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
scrivito_sdk-1.18.0 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.18.0.rc1 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.17.0 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.17.0.rc3 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.17.0.rc2 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.17.0.rc1 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.16.0 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.16.0.rc2 app/cms/scrivito/cms_rest_api/rate_limit.rb
scrivito_sdk-1.16.0.rc1 app/cms/scrivito/cms_rest_api/rate_limit.rb