FIX: Switch alerts category ids cache to distributed cache. (#23)

FIX: Switch alerts category ids cache to distributed cache. (#23)

A per process cache does not really work well when ActiveRecord callbacks are only executed on a single process.

Follow-up to ce5e52ba317381fa516da1a08ea095940224457c

diff --git a/plugin.rb b/plugin.rb
index 1917b8e..95eb2c0 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -74,16 +74,20 @@ after_initialize do
   end
 
   add_class_method(:topic, :clear_alerts_category_ids_cache) do
-    @alerts_category_ids = nil
+    @alerts_category_ids_cache&.clear
     Jobs.enqueue(:create_alert_topics_index)
   end
 
   add_class_method(:topic, :alerts_category_ids_cache) do
-    @alerts_category_ids ||= alerts_category_ids
+    @alerts_category_ids_cache ||= DistributedCache.new("alerts_category_ids_cache")
+
+    @alerts_category_ids_cache.defer_get_set("alert_category_ids") do
+      alerts_category_ids
+    end
   end
 
   add_class_method(:topic, :alerts_category_ids) do
-    category_ids = PluginStoreRow
+    PluginStoreRow
       .where(plugin_name: ::DiscoursePrometheusAlertReceiver::PLUGIN_NAME)
       .pluck("value::json->'category_id'")
   end
diff --git a/spec/serializers/site_serializer_spec.rb b/spec/serializers/site_serializer_spec.rb
index 1922ea6..5775d69 100644
--- a/spec/serializers/site_serializer_spec.rb
+++ b/spec/serializers/site_serializer_spec.rb
@@ -9,11 +9,21 @@ RSpec.describe SiteSerializer do
       SiteSerializer.new(site, root: false, scope: guardian).as_json
     end
 
+    fab!(:category) { Fabricate(:category) }
+
+    fab!(:plugin_store_row) do
+      PluginStore.set(
+        ::DiscoursePrometheusAlertReceiver::PLUGIN_NAME,
+        'sometoken',
+        { category_id: category.id }
+      )
+    end
+
     before do
-      topic1 = Fabricate(:post).topic
-      topic2 = Fabricate(:post).topic
-      topic3 = Fabricate(:post).topic
-      topic4 = Fabricate(:post).topic
+      topic1 = Fabricate(:post, topic: Fabricate(:topic, category: category)).topic
+      topic2 = Fabricate(:post, topic: Fabricate(:topic, category: category)).topic
+      topic3 = Fabricate(:post, topic: Fabricate(:topic, category: category)).topic
+      topic4 = Fabricate(:post, topic: Fabricate(:topic, category: category)).topic
       topic4.trash!
 
       {

GitHub sha: 989667a516dc85ae41d51d4bf9f30e633a687700

This commit appears in #23 which was approved by martin. It was merged by tgxworld.