Skip to content

Commit 39b3fd5

Browse files
committed
Merge remote-tracking branch 'upstream/master' into support-facebook-api
2 parents 9d5736f + 6f23a82 commit 39b3fd5

File tree

2 files changed

+40
-6
lines changed

2 files changed

+40
-6
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

lib/tasks/statistics.rake

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,38 @@ require_relative '../statistics.rb'
22

33
namespace :statistics do
44
desc '月次のイベント履歴を集計します'
5-
task :aggregation, [:from_yyyymm, :to_yyyymm] => :environment do |tasks, args|
5+
task :aggregation, [:from, :to] => :environment do |tasks, args|
66
date_from_str = -> (str) {
7-
d = %w(%Y%m %Y/%m %Y-%m).map { |fmt|
7+
formats = %w(%Y%m %Y/%m %Y-%m)
8+
d = formats.map { |fmt|
89
begin
910
Time.zone.strptime(str, fmt)
1011
rescue ArgumentError
12+
Time.zone.local(str) if str.length == 4
1113
end
1214
}.compact.first
13-
raise ArgumentError, "Invalid format: `#{str}`" if d.nil?
15+
raise ArgumentError, "Invalid format: `#{str}`, allow format is #{formats.push('%Y').join(' or ')}" if d.nil?
1416
d
1517
}
1618

17-
from = (args[:from_yyyymm] ? date_from_str.call(args[:from_yyyymm]) : Time.current.prev_month).beginning_of_month
18-
to = (args[:to_yyyymm] ? date_from_str.call(args[:to_yyyymm]) : Time.current.prev_month).end_of_month
19+
from = if args[:from]
20+
if args[:from].length == 4
21+
date_from_str.call(args[:from]).beginning_of_year
22+
else
23+
date_from_str.call(args[:from]).beginning_of_month
24+
end
25+
else
26+
Time.current.prev_month.beginning_of_month
27+
end
28+
to = if args[:to]
29+
if args[:to].length == 4
30+
date_from_str.call(args[:to]).end_of_year
31+
else
32+
date_from_str.call(args[:to]).end_of_month
33+
end
34+
else
35+
Time.current.prev_month.end_of_month
36+
end
1937

2038
EventHistory.where(evented_at: from..to).delete_all
2139

@@ -24,7 +42,15 @@ namespace :statistics do
2442
raise StopIteration if nm > to
2543
list << nm
2644
}.each { |date|
27-
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
2854
}
2955
end
3056

0 commit comments

Comments
 (0)