From aa6ca108e7311630cd4b4e57e4659f7a04dc4bbe Mon Sep 17 00:00:00 2001 From: Goran Colovic Date: Fri, 10 Dec 2021 17:32:10 +0100 Subject: [PATCH] fix bug rate_limit_details returned as nil if net:http failed a request, and bug if intercom request header does not contain X-RateLimit-Reset header --- lib/intercom/client.rb | 2 +- lib/intercom/request.rb | 4 ++-- spec/unit/intercom/client_spec.rb | 8 ++++++++ spec/unit/intercom/request_spec.rb | 11 +++++++++++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/intercom/client.rb b/lib/intercom/client.rb index 883a99ae..2af550fe 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 0be75505..cb43af48 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 660c49d9..3e7b114a 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 2310bc79..cb7a5f1e 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"],