diff --git a/lib/intercom/client.rb b/lib/intercom/client.rb index 883a99a..2af550f 100644 --- a/lib/intercom/client.rb +++ b/lib/intercom/client.rb @@ -156,7 +156,7 @@ def execute_request(request) request.handle_rate_limit = handle_rate_limit request.execute(@base_url, token: @token, api_version: @api_version, **timeouts) ensure - @rate_limit_details = request.rate_limit_details + @rate_limit_details = request.rate_limit_details unless request.rate_limit_details.empty? end attr_writer :base_url diff --git a/lib/intercom/request.rb b/lib/intercom/request.rb index 0be7550..cb43af4 100644 --- a/lib/intercom/request.rb +++ b/lib/intercom/request.rb @@ -72,11 +72,11 @@ def execute(target_base_url = nil, token:, read_timeout: 90, open_timeout: 30, a parsed_body rescue Intercom::RateLimitExceeded => e if @handle_rate_limit - seconds_to_retry = (@rate_limit_details[:reset_at] - Time.now.utc).ceil + seconds_to_retry = ((@rate_limit_details[:reset_at] || Time.now.utc) - Time.now.utc).ceil if (retries -= 1) < 0 raise Intercom::RateLimitExceeded, 'Rate limit retries exceeded. Please examine current API Usage.' else - sleep seconds_to_retry unless seconds_to_retry < 0 + sleep seconds_to_retry unless seconds_to_retry <= 0 retry end else diff --git a/spec/unit/intercom/client_spec.rb b/spec/unit/intercom/client_spec.rb index 660c49d..3e7b114 100644 --- a/spec/unit/intercom/client_spec.rb +++ b/spec/unit/intercom/client_spec.rb @@ -87,6 +87,14 @@ module Intercom client.get('/contacts', id: '123') end + + it 'sets rate limit details to empty hash' do + stub_request(:any, "https://api.intercom.io/test").to_raise(StandardError) + + expect { client.get('/test', {}) }.must_raise(StandardError) + + client.rate_limit_details.must_equal({}) + end end describe 'OAuth clients' do diff --git a/spec/unit/intercom/request_spec.rb b/spec/unit/intercom/request_spec.rb index 2310bc7..cb7a5f1 100644 --- a/spec/unit/intercom/request_spec.rb +++ b/spec/unit/intercom/request_spec.rb @@ -51,6 +51,17 @@ def execute! execute! end + it 'should not call sleep for rate limit if reset is not received' do + stub_request(:any, uri).to_return( + status: [429, "Too Many Requests"], + ).then.to_return(status: [200, "OK"], body: default_body) + + req.handle_rate_limit=true + req.expects(:sleep).never.with(any_parameters) + + execute! + end + it 'should not sleep if rate limit reset time has passed' do stub_request(:any, uri).to_return( status: [429, "Too Many Requests"],