Class: Embulk::Input::GoogleAnalytics::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/embulk/input/google_analytics/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(task, is_preview = false) ⇒ Client

Returns a new instance of Client.



16
17
18
19
# File 'lib/embulk/input/google_analytics/client.rb', line 16

def initialize(task, is_preview = false)
  @task = task
  @is_preview = is_preview
end

Instance Attribute Details

#task ⇒ Object (readonly)

Returns the value of attribute task.



14
15
16
# File 'lib/embulk/input/google_analytics/client.rb', line 14

def task
  @task
end

Instance Method Details

#auth ⇒ Object



216
217
218
219
220
221
222
223
224
225
# File 'lib/embulk/input/google_analytics/client.rb', line 216

def auth
  retryer.with_retry do
    Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: StringIO.new(task["json_key_content"]),
      scope: "https://www.googleapis.com/auth/analytics.readonly"
    )
  end
rescue Google::Apis::AuthorizationError => e
  raise ConfigError.new(e.message)
end

#build_report_request(page_token = nil) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/embulk/input/google_analytics/client.rb', line 189

def build_report_request(page_token = nil)
  query = {
    view_id: view_id,
    dimensions: [{name: task["time_series"]}] + task["dimensions"].map{|d| {name: d}},
    metrics: task["metrics"].map{|m| {expression: m}},
    include_empty_rows: true,
    page_size: preview? ? 10 : 10000,
  }

  if task["start_date"] || task["end_date"]
    query[:date_ranges] = [{
      start_date: task["start_date"],
      end_date: task["end_date"],
    }]
  end

  if page_token
    query[:page_token] = page_token
  end

  [query]
end

#canonical_column_names(columns) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/embulk/input/google_analytics/client.rb', line 144

def canonical_column_names(columns)
  result = []
  columns.each do |col|
    if col[:id].match(/XX/)
      # for such columns:
      # https://developers.google.com/analytics/devguides/reporting/core/dimsmets#view=detail&group=content_grouping
      # https://developers.google.com/analytics/devguides/reporting/metadata/v3/devguide#attributes
      min = [
        col[:attributes][:minTemplateIndex],
        col[:attributes][:premiumMinTemplateIndex],
      ].compact.min
      max = [
        col[:attributes][:maxTemplateIndex],
        col[:attributes][:premiumMaxTemplateIndex],
      ].compact.max

      min.upto(max) do |n|
        actual_id = col[:id].gsub(/XX/, n.to_s)
        result << col.merge(id: actual_id)
      end
    else
      result << col
    end
  end
  result
end

#each_report_row(&block) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/embulk/input/google_analytics/client.rb', line 25

def each_report_row(&block)
  page_token = nil
  Embulk.logger.info "view_id:#{view_id} timezone has been set as '#{get_profile[:timezone]}'"

  loop do
    result = get_reports(page_token)
    report = result.to_h[:reports].first

    unless page_token
      # display for first request only
      Embulk.logger.info "Total: #{report[:data][:row_count]} rows. Fetched first response"
    end

    if !report[:data].has_key?(:rows)
      Embulk.logger.warn "Result doesn't contain rows."
      break
    end

    if report[:data][:rows].empty?
      Embulk.logger.warn "Result has 0 rows."
      break
    end

    dimensions = report[:column_header][:dimensions]
    metrics = report[:column_header][:metric_header][:metric_header_entries].map{|m| m[:name]}
    report[:data][:rows].each do |row|
      dim = dimensions.zip(row[:dimensions]).to_h
      met = metrics.zip(row[:metrics].first[:values]).to_h
      format_row = dim.merge(met)
      raw_time = format_row[task["time_series"]]
      Embulk.logger.info "#{raw_time}"
      optimize_value_by_query_limit?(raw_time)
      next if too_early_data?(raw_time)
      format_row[task["time_series"]] = time_parse_with_profile_timezone(raw_time)
      format_row["view_id"] = view_id
      block.call format_row
    end
    Embulk.logger.info "still here"

    break if preview?

    unless page_token = report[:next_page_token]
      break
    end
    Embulk.logger.info "Fetching report with page_token: #{page_token}"
  end
end

#get_all_profiles ⇒ Object



88
89
90
91
92
93
94
95
96
# File 'lib/embulk/input/google_analytics/client.rb', line 88

def get_all_profiles
  service = Google::Apis::AnalyticsV3::AnalyticsService.new
  service.authorization = auth

  Embulk.logger.debug "Fetching profile from API"
  retryer.with_retry do
    service.list_profiles("~all", "~all")
  end
end

#get_columns_list ⇒ Object



139
140
141
142
# File 'lib/embulk/input/google_analytics/client.rb', line 139

def get_columns_list
  columns = get_custom_dimensions + 
  canonical_column_names(columns)
end

#get_custom_dimensions ⇒ Object



180
181
182
183
184
185
186
187
# File 'lib/embulk/input/google_analytics/client.rb', line 180

def get_custom_dimensions
  # https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/customDimensions/list
  service = Google::Apis::AnalyticsV3::AnalyticsService.new
  service.authorization = auth
  retryer.with_retry do
    service.list_custom_dimensions(get_profile[:account_id], get_profile[:web_property_id]).to_h[:items]
  end
end

#get_metadata_columns ⇒ Object



171
172
173
174
175
176
177
178
# File 'lib/embulk/input/google_analytics/client.rb', line 171

def 
  # https://developers.google.com/analytics/devguides/reporting/metadata/v3/reference/metadata/columns/list
  service = Google::Apis::AnalyticsV3::AnalyticsService.new
  service.authorization = auth
  retryer.with_retry do
    service.("ga").to_h[:items]
  end
end

#get_profile ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/embulk/input/google_analytics/client.rb', line 73

def get_profile
  @profile ||=
    begin
      profile = get_all_profiles.to_h[:items].find do |prof|
        prof[:id] == view_id
      end

      unless profile
        raise Embulk::ConfigError.new("Can't find view_id:#{view_id} profile via Google Analytics API.")
      end

      profile
    end
end

#get_reports(page_token = nil) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/embulk/input/google_analytics/client.rb', line 125

def get_reports(page_token = nil)
  # https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet
  service = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
  service.authorization = auth

  request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new
  request.report_requests = build_report_request(page_token)

  Embulk.logger.info "Query to Core Report API: #{request.to_json}"
  retryer.with_retry do
    service.batch_get_reports request
  end
end

#optimize_value_by_query_limit?(data) ⇒ Boolean

Returns:

  • (Boolean)


98
99
100
101
102
103
104
# File 'lib/embulk/input/google_analytics/client.rb', line 98

def optimize_value_by_query_limit?(data)
  # For any date range, Analytics returns a maximum of 1 million rows for the report. Rows in excess of 1 million are rolled-up into an (other) row.
  # See more details: https://support.google.com/analytics/answer/1009671
  if data.to_s == "(other)"
    raise Embulk::DataError.new('Stop fetching data from Analytics because over 1M data fetching was limited. Please reduce data range to fetch data according to this article: https://support.google.com/analytics/answer/1009671.')
  end
end

#preview? ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/embulk/input/google_analytics/client.rb', line 21

def preview?
  @is_preview
end

#retryer ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/embulk/input/google_analytics/client.rb', line 248

def retryer
  PerfectRetry.new do |config|
    config.limit = task["retry_limit"]
    config.logger = Embulk.logger
    config.log_level = nil

    # https://developers.google.com/analytics/devguides/reporting/core/v4/errors
    # https://developers.google.com/analytics/devguides/reporting/core/v4/limits-quotas#additional_quota
    # https://github.com/google/google-api-ruby-client/blob/master/lib/google/apis/errors.rb
    # https://github.com/google/google-api-ruby-client/blob/0.9.11/lib/google/apis/core/http_command.rb#L33
    config.rescues = Google::Apis::Core::HttpCommand::RETRIABLE_ERRORS
    config.dont_rescues = [Embulk::DataError, Embulk::ConfigError]
    config.sleep = lambda{|n| task["retry_initial_wait_sec"]* (2 ** (n-1)) }
    config.raise_original_error = true
  end
end

#swap_time_zone(&block) ⇒ Object



227
228
229
230
231
232
233
# File 'lib/embulk/input/google_analytics/client.rb', line 227

def swap_time_zone(&block)
  orig_timezone = Time.zone
  Time.zone = get_profile[:timezone]
  yield
ensure
  Time.zone = orig_timezone
end

#time_parse_with_profile_timezone(time_string) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/embulk/input/google_analytics/client.rb', line 106

def time_parse_with_profile_timezone(time_string)
  date_format =
    case task["time_series"]
    when "ga:dateHour"
      "%Y%m%d%H"
    when "ga:date"
      "%Y%m%d"
    end
  parts = Date._strptime(time_string, date_format)
  unless parts
    # strptime was failed. Google API returns unexpected date string.
    Embulk.logger.warn("Failed to parse #{task["time_series"]} data. The value is '#{time_string}'(#{time_string.class}) and it doesn't match with '#{date_format}'.")
  end

  swap_time_zone do
    Time.zone.local(*parts.values_at(:year, :mon, :mday, :hour)).to_time
  end
end

#too_early_data?(time_str) ⇒ Boolean

Returns:

  • (Boolean)


235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/embulk/input/google_analytics/client.rb', line 235

def too_early_data?(time_str)
  # fetching 20160720 data on 2016-07-20, it is too early fetching
  swap_time_zone do
    now = Time.zone.now
    case task["time_series"]
    when "ga:dateHour"
      time_str.to_i >= now.strftime("%Y%m%d%H").to_i
    when "ga:date"
      time_str.to_i >= now.strftime("%Y%m%d").to_i
    end
  end
end

#view_id ⇒ Object



212
213
214
# File 'lib/embulk/input/google_analytics/client.rb', line 212

def view_id
  task["view_id"]
end