Class: Embulk::Input::Mixpanel

Inherits:
InputPlugin
  • Object
show all
Defined in:
lib/embulk/input/mixpanel.rb

Constant Summary collapse

GUESS_RECORDS_COUNT =
10
NOT_PROPERTY_COLUMN =
"event".freeze
KNOWN_KEYS =

mixpanel.com/help/questions/articles/special-or-reserved-properties mixpanel.com/help/questions/articles/what-properties-do-mixpanels-libraries-store-by-default

JavaScript to extract key names from HTML: run it on Chrome Devtool when opening their document > Array.from(document.querySelectorAll(“strong”)).map(function(s){ return s.textContent.match(//) ? s.parentNode.textContent.match(/((.*?))/) : s.textContent.split(“,”).join(“ ”) }).join(“ ”) > Array.from(document.querySelectorAll(“li”)).map(function(s){ m = s.textContent.match(/((.*?))/); return m && m }).filter(function(k) { return k && !k.match(“utm”) }).join(“ ”)

%W(
  #{NOT_PROPERTY_COLUMN}
  distinct_id ip mp_name_tag mp_note token time mp_country_code length campaign_id $email $phone $distinct_id $ios_devices $android_devices $first_name  $last_name  $name $city $region $country_code $timezone $unsubscribed
  $city $region mp_country_code $browser $browser_version $device $current_url $initial_referrer $initial_referring_domain $os $referrer $referring_domain $screen_height $screen_width $search_engine $city $region $mp_country_code $timezone $browser_version $browser $initial_referrer $initial_referring_domain $os $last_seen $city $region mp_country_code $app_release $app_version $carrier $ios_ifa $os_version $manufacturer $lib_version $model $os $screen_height $screen_width $wifi $city $region $mp_country_code $timezone $ios_app_release $ios_app_version $ios_device_model $ios_lib_version $ios_version $ios_ifa $last_seen $city $region mp_country_code $app_version $bluetooth_enabled $bluetooth_version $brand $carrier $has_nfc $has_telephone $lib_version $manufacturer $model $os $os_version $screen_dpi $screen_height $screen_width $wifi $google_play_services $city $region mp_country_code $timezone $android_app_version $android_app_version_code $android_lib_version $android_os $android_os_version $android_brand $android_model $android_manufacturer $last_seen
).uniq.freeze
SLICE_DAYS_COUNT =

NOTE: It takes long time to fetch data between from_date to to_date by one API request. So this plugin fetches data between each 7 (SLICE_DAYS_COUNT) days.

7

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_guess_start_dateObject



254
255
256
# File 'lib/embulk/input/mixpanel.rb', line 254

def self.default_guess_start_date
  Date.today - SLICE_DAYS_COUNT - 1
end

.export_params(config) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
# File 'lib/embulk/input/mixpanel.rb', line 242

def self.export_params(config)
  event = config.param(:event, :array, default: nil)
  event = event.nil? ? nil : event.to_json

  {
    api_key: config.param(:api_key, :string),
    event: event,
    where: config.param(:where, :string, default: nil),
    bucket: config.param(:bucket, :string, default: nil),
  }
end

.giveup_when_mixpanel_is_downObject



157
158
159
160
161
# File 'lib/embulk/input/mixpanel.rb', line 157

def self.giveup_when_mixpanel_is_down
  unless MixpanelApi::Client.mixpanel_available?
    raise Embulk::DataError.new("Mixpanel service is down. Please retry later.")
  end
end

.guess(config) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/embulk/input/mixpanel.rb', line 91

def self.guess(config)
  giveup_when_mixpanel_is_down

  client = MixpanelApi::Client.new(config.param(:api_key, :string), config.param(:api_secret, :string))

  range = guess_range(config)
  Embulk.logger.info "Guessing schema using #{range.first}..#{range.last} records"

  params = export_params(config).merge(
    "from_date" => range.first,
    "to_date" => range.last,
  )

  columns = guess_from_records(client.export_for_small_dataset(params))
  return {"columns" => columns}
end

.guess_from_records(records) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/embulk/input/mixpanel.rb', line 268

def self.guess_from_records(records)
  sample_props = records.first(GUESS_RECORDS_COUNT).map{|r| r["properties"]}
  schema = Guess::SchemaGuess.from_hash_records(sample_props)
  columns = schema.map do |col|
    next if col.name == "time"
    result = {
      name: col.name,
      type: col.type,
    }
    result[:format] = col.format if col.format
    result
  end.compact
  columns.unshift(name: NOT_PROPERTY_COLUMN, type: :string)
  columns.unshift(name: "time", type: :long)
end

.guess_range(config) ⇒ Object



258
259
260
261
262
263
264
265
266
# File 'lib/embulk/input/mixpanel.rb', line 258

def self.guess_range(config)
  from_date = config.param(:from_date, :string, default: default_guess_start_date.to_s)
  fetch_days = config.param(:fetch_days, :integer, default: SLICE_DAYS_COUNT)
  range = RangeGenerator.new(from_date, fetch_days).generate_range
  if range.empty?
    return default_guess_start_date..(Date.today - 1)
  end
  range
end

.resume(task, columns, count, &control) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/embulk/input/mixpanel.rb', line 79

def self.resume(task, columns, count, &control)
  task_reports = yield(task, columns, count)

  # NOTE: If this plugin supports to run by multi threads, this
  # implementation is terrible.
  task_report = task_reports.first
  next_to_date = Date.parse(task_report[:to_date]).next

  next_config_diff = {from_date: next_to_date.to_s}
  return next_config_diff
end

.transaction(config, &control) ⇒ Object



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
72
73
74
75
76
77
# File 'lib/embulk/input/mixpanel.rb', line 32

def self.transaction(config, &control)
  timezone = config.param(:timezone, :string)
  TimezoneValidator.new(timezone).validate

  from_date = config.param(:from_date, :string, default: (Date.today - 2).to_s)
  fetch_days = config.param(:fetch_days, :integer, default: nil)
  range = RangeGenerator.new(from_date, fetch_days).generate_range
  Embulk.logger.info "Try to fetch data from #{range.first} to #{range.last}"

  fetch_unknown_columns = config.param(:fetch_unknown_columns, :bool, default: true)

  task = {
    params: export_params(config),
    dates: range,
    timezone: timezone,
    api_key: config.param(:api_key, :string),
    api_secret: config.param(:api_secret, :string),
    schema: config.param(:columns, :array),
    fetch_unknown_columns: fetch_unknown_columns,
    fetch_custom_properties: config.param(:fetch_custom_properties, :bool, default: false),
    retry_initial_wait_sec: config.param(:retry_initial_wait_sec, :integer, default: 1),
    retry_limit: config.param(:retry_limit, :integer, default: 5),
  }

  if task[:fetch_unknown_columns] && task[:fetch_custom_properties]
    raise Embulk::ConfigError.new("Don't set true both `fetch_unknown_columns` and `fetch_custom_properties`.")
  end

  columns = task[:schema].map do |column|
    name = column["name"]
    type = column["type"].to_sym

    Column.new(nil, name, type, column["format"])
  end

  if fetch_unknown_columns
    Embulk.logger.warn "Deprecated `unknown_columns`. Use `fetch_custom_properties` instead."
    columns << Column.new(nil, "unknown_columns", :json)
  end

  if task[:fetch_custom_properties]
    columns << Column.new(nil, "custom_properties", :json)
  end

  resume(task, columns, 1, &control)
end

Instance Method Details

#initObject



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

def init
  @api_key = task[:api_key]
  @api_secret = task[:api_secret]
  @params = task[:params]
  @timezone = task[:timezone]
  @schema = task[:schema]
  @dates = task[:dates]
  @fetch_unknown_columns = task[:fetch_unknown_columns]
  @retryer = PerfectRetry.new do |config|
    config.limit = task[:retry_limit]
    config.sleep = proc{|n| task[:retry_initial_wait_sec] * (2 * (n - 1)) }
    config.dont_rescues = [Embulk::ConfigError]
    config.rescues = [RuntimeError]
    config.log_level = nil
    config.logger = Embulk.logger
  end
end

#runObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/embulk/input/mixpanel.rb', line 126

def run
  self.class.giveup_when_mixpanel_is_down

  @dates.each_slice(SLICE_DAYS_COUNT) do |dates|
    unless preview?
      Embulk.logger.info "Fetching data from #{dates.first} to #{dates.last} ..."
    end

    fetch(dates).each do |record|
      values = extract_values(record)
      if @fetch_unknown_columns
        unknown_values = extract_unknown_values(record)
        values << unknown_values.to_json
      end
      if task[:fetch_custom_properties]
        values << collect_custom_properties(record)
      end
      page_builder.add(values)
    end

    break if preview?
  end

  page_builder.finish

  task_report = {to_date: @dates.last || (Date.today - 1)}
  return task_report
end