Class: CodeSunset::AggregateDailyRollupsJob

Inherits:
ApplicationJob
  • Object
show all
Defined in:
app/jobs/code_sunset/aggregate_daily_rollups_job.rb

Instance Method Summary collapse

Instance Method Details

#perform(start_date: nil, end_date: nil) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/jobs/code_sunset/aggregate_daily_rollups_job.rb', line 5

def perform(start_date: nil, end_date: nil)
  range = normalize_range(start_date, end_date)
  relation = CodeSunset::Event.where(occurred_at: range)

  rows = relation
    .group(:feature_key, :app_env, Arel.sql("DATE(occurred_at)"))
    .pluck(
      :feature_key,
      :app_env,
      Arel.sql("DATE(occurred_at)"),
      Arel.sql("COUNT(*)"),
      Arel.sql("COUNT(DISTINCT #{CodeSunset::Event.user_identifier_expression})"),
      Arel.sql("COUNT(DISTINCT #{CodeSunset::Event.org_identifier_expression})"),
      Arel.sql("MAX(occurred_at)")
    )

  upserts = rows.map do |feature_key, app_env, day, hits_count, unique_users_count, unique_orgs_count, last_seen_at|
    {
      feature_key: feature_key,
      app_env: app_env,
      day: day,
      hits_count: hits_count,
      unique_users_count: unique_users_count,
      unique_orgs_count: unique_orgs_count,
      last_seen_at: last_seen_at,
      created_at: Time.current,
      updated_at: Time.current
    }
  end

  return if upserts.empty?

  CodeSunset::DailyRollup.upsert_all(upserts, unique_by: %i[feature_key app_env day])
end