|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +module Analytics |
| 4 | + class Series |
| 5 | + class Sparks |
| 6 | + class Downloads |
| 7 | + def initialize(account:, environment:, product_id: nil, package_id: nil, release_id: nil, realtime: true, **) |
| 8 | + @account = account |
| 9 | + @environment = environment |
| 10 | + @product_id = product_id |
| 11 | + @package_id = package_id |
| 12 | + @release_id = release_id |
| 13 | + @realtime = realtime |
| 14 | + end |
| 15 | + |
| 16 | + def metrics = %w[downloads] |
| 17 | + def count(start_date:, end_date:) |
| 18 | + scope = ReleaseDownloadSpark.for_account(account) |
| 19 | + .for_environment(environment) |
| 20 | + .where( |
| 21 | + created_date: start_date..end_date, |
| 22 | + ) |
| 23 | + |
| 24 | + unless product_id.nil? |
| 25 | + scope = scope.where(product_id:) |
| 26 | + end |
| 27 | + |
| 28 | + unless package_id.nil? |
| 29 | + scope = scope.where(package_id:) |
| 30 | + end |
| 31 | + |
| 32 | + unless release_id.nil? |
| 33 | + scope = scope.where(release_id:) |
| 34 | + end |
| 35 | + |
| 36 | + rows = scope.group(:created_date) |
| 37 | + .pluck( |
| 38 | + :created_date, |
| 39 | + Arel.sql('sum(count)'), |
| 40 | + ) |
| 41 | + |
| 42 | + counts = rows.each_with_object({}) do |(date, count), hash| |
| 43 | + hash[['downloads', date]] = count |
| 44 | + end |
| 45 | + |
| 46 | + # defer to gauge for a realtime count since sparks are nightly |
| 47 | + if realtime? && end_date.today? |
| 48 | + gauge = Analytics::Gauge.new(:downloads, account:, environment:, product_id:, package_id:, release_id:) |
| 49 | + |
| 50 | + gauge.measurements.each do |measurement| |
| 51 | + counts[[measurement.metric, end_date]] = measurement.count |
| 52 | + end |
| 53 | + end |
| 54 | + |
| 55 | + counts |
| 56 | + end |
| 57 | + |
| 58 | + private |
| 59 | + |
| 60 | + attr_reader :account, |
| 61 | + :environment, |
| 62 | + :product_id, |
| 63 | + :package_id, |
| 64 | + :release_id, |
| 65 | + :realtime |
| 66 | + |
| 67 | + def realtime? = !!realtime |
| 68 | + end |
| 69 | + end |
| 70 | + end |
| 71 | +end |
0 commit comments