about summary refs log tree commit diff
path: root/app/lib/admin/metrics/retention.rb
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2022-02-22 15:27:08 +0100
committerGitHub <noreply@github.com>2022-02-22 15:27:08 +0100
commitb377022cf9dfac4d98d0d10b511aeb65e540e0a3 (patch)
tree80d5c32b1e4885b053d89babed15298b151a192b /app/lib/admin/metrics/retention.rb
parent83388269631f377e9853858916aa8c3897f90bb4 (diff)
Add caching layer to metrics (#17617)
Diffstat (limited to 'app/lib/admin/metrics/retention.rb')
-rw-r--r--app/lib/admin/metrics/retention.rb26
1 files changed, 26 insertions, 0 deletions
diff --git a/app/lib/admin/metrics/retention.rb b/app/lib/admin/metrics/retention.rb
index 0179a6e28..f6135ac1e 100644
--- a/app/lib/admin/metrics/retention.rb
+++ b/app/lib/admin/metrics/retention.rb
@@ -1,6 +1,8 @@
 # frozen_string_literal: true
 
 class Admin::Metrics::Retention
+  CACHE_TTL = 5.minutes.freeze
+
   class Cohort < ActiveModelSerializers::Model
     attributes :period, :frequency, :data
   end
@@ -9,13 +11,37 @@ class Admin::Metrics::Retention
     attributes :date, :rate, :value
   end
 
+  attr_reader :loaded
+
+  alias loaded? loaded
+
   def initialize(start_at, end_at, frequency)
     @start_at  = start_at&.to_date
     @end_at    = end_at&.to_date
     @frequency = %w(day month).include?(frequency) ? frequency : 'day'
+    @loaded    = false
+  end
+
+  def cache_key
+    ['metrics/retention', @start_at, @end_at, @frequency].join(';')
   end
 
   def cohorts
+    load
+  end
+
+  protected
+
+  def load
+    unless loaded?
+      @values = Rails.cache.fetch(cache_key, expires_in: CACHE_TTL) { perform_query }
+      @loaded = true
+    end
+
+    @values
+  end
+
+  def perform_query
     sql = <<-SQL.squish
       SELECT axis.*, (
         WITH new_users AS (