Skip to content

Commit 6f23a82

Browse files
authored
Merge pull request #173 from coderdojo-japan/api-rate-limit
Sleep and retry if raise API rate limit exceeded
2 parents 335793e + f9e4cc0 commit 6f23a82

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

lib/statistics/client.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
module Statistics
22
class Client
3+
class APIRateLimitError < ::StandardError; end
4+
35
class_attribute :debug
46
self.debug = false
57

@@ -99,6 +101,12 @@ def fetch_events(group_id:, since_at: @default_since, until_at: @default_until)
99101
end
100102

101103
events
104+
rescue Faraday::ClientError => e
105+
if e.response[:status] == 429
106+
raise Client::APIRateLimitError
107+
else
108+
raise e
109+
end
102110
end
103111
end
104112
end

lib/tasks/statistics.rake

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,15 @@ namespace :statistics do
4242
raise StopIteration if nm > to
4343
list << nm
4444
}.each { |date|
45-
Statistics::Aggregation.run(date: date)
45+
begin
46+
puts "Aggregate for #{date.strftime('%Y/%m')}"
47+
Statistics::Aggregation.run(date: date)
48+
rescue Statistics::Client::APIRateLimitError
49+
puts 'API rate limit exceeded.'
50+
puts "This task will retry in 60 seconds from now(#{Time.zone.now})."
51+
sleep 60
52+
retry
53+
end
4654
}
4755
end
4856

0 commit comments

Comments
 (0)