2017-12-29 13:52:04 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class ActivityTracker
|
2021-10-14 14:44:59 -04:00
|
|
|
include Redisable
|
|
|
|
|
2019-09-29 15:31:51 -04:00
|
|
|
EXPIRE_AFTER = 6.months.seconds
|
2017-12-29 13:52:04 -05:00
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
def initialize(prefix, type)
|
|
|
|
@prefix = prefix
|
|
|
|
@type = type
|
|
|
|
end
|
2019-02-02 13:11:38 -05:00
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
def add(value = 1, at_time = Time.now.utc)
|
|
|
|
key = key_at(at_time)
|
2017-12-29 13:52:04 -05:00
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
case @type
|
|
|
|
when :basic
|
|
|
|
redis.incrby(key, value)
|
|
|
|
when :unique
|
|
|
|
redis.pfadd(key, value)
|
2017-12-29 13:52:04 -05:00
|
|
|
end
|
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
redis.expire(key, EXPIRE_AFTER)
|
|
|
|
end
|
2017-12-29 13:52:04 -05:00
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
def get(start_at, end_at = Time.now.utc)
|
2024-03-14 17:21:01 -04:00
|
|
|
(start_at.to_date..end_at.to_date).map do |date|
|
2021-10-14 14:44:59 -04:00
|
|
|
key = key_at(date.to_time(:utc))
|
|
|
|
|
2023-02-18 17:09:40 -05:00
|
|
|
value = case @type
|
|
|
|
when :basic
|
|
|
|
redis.get(key).to_i
|
|
|
|
when :unique
|
|
|
|
redis.pfcount(key)
|
|
|
|
end
|
2021-10-14 14:44:59 -04:00
|
|
|
|
|
|
|
[date, value]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def sum(start_at, end_at = Time.now.utc)
|
|
|
|
keys = (start_at.to_date...end_at.to_date).flat_map { |date| [key_at(date.to_time(:utc)), legacy_key_at(date)] }.uniq
|
|
|
|
|
|
|
|
case @type
|
|
|
|
when :basic
|
2023-05-02 10:10:40 -04:00
|
|
|
redis.mget(*keys).sum(&:to_i)
|
2021-10-14 14:44:59 -04:00
|
|
|
when :unique
|
|
|
|
redis.pfcount(*keys)
|
2017-12-29 13:52:04 -05:00
|
|
|
end
|
2021-10-14 14:44:59 -04:00
|
|
|
end
|
2017-12-29 13:52:04 -05:00
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
class << self
|
|
|
|
def increment(prefix)
|
|
|
|
new(prefix, :basic).add
|
|
|
|
end
|
2017-12-29 13:52:04 -05:00
|
|
|
|
2021-10-14 14:44:59 -04:00
|
|
|
def record(prefix, value)
|
|
|
|
new(prefix, :unique).add(value)
|
2017-12-29 13:52:04 -05:00
|
|
|
end
|
|
|
|
end
|
2021-10-14 14:44:59 -04:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def key_at(at_time)
|
|
|
|
"#{@prefix}:#{at_time.beginning_of_day.to_i}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def legacy_key_at(at_time)
|
|
|
|
"#{@prefix}:#{at_time.to_date.cweek}"
|
|
|
|
end
|
2017-12-29 13:52:04 -05:00
|
|
|
end
|