about summary refs log tree commit diff
diff options
context:
space:
mode:
authormultiple creatures <dev@multiple-creature.party>2020-01-10 21:27:32 -0600
committermultiple creatures <dev@multiple-creature.party>2020-01-10 21:27:32 -0600
commita32afcccd0d34883b88f51a46f0ba0f1fb427adc (patch)
tree04f5590fcd2d9ecd1229938951a6a47f6054abe8
parentd6806025a03081d5438f60c6876a6ad1aad97494 (diff)
speed up search with caching
-rw-r--r--app/services/search_service.rb21
1 files changed, 21 insertions, 0 deletions
diff --git a/app/services/search_service.rb b/app/services/search_service.rb
index 73ff785c9..0ef3f4a00 100644
--- a/app/services/search_service.rb
+++ b/app/services/search_service.rb
@@ -24,6 +24,7 @@ class SearchService < BaseService
 
   def search_for
     results = Status.search_for(@query.gsub(/\A#/, ''), @account, @limit, @offset)
+    cache_collection results, Status
   end
 
   def perform_accounts_search!
@@ -97,4 +98,24 @@ class SearchService < BaseService
       domain_blocking_by_domain: Account.domain_blocking_map_by_domain(domains, account.id),
     }
   end
+
+	def cache_collection(raw, klass)
+    return raw unless klass.respond_to?(:with_includes)
+
+    raw                    = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
+    cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id)
+    uncached_ids           = raw.map(&:id) - cached_keys_with_value.keys
+
+    klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
+
+    unless uncached_ids.empty?
+      uncached = klass.where(id: uncached_ids).with_includes.each_with_object({}) { |item, h| h[item.id] = item }
+
+      uncached.each_value do |item|
+        Rails.cache.write(item, item)
+      end
+    end
+
+    raw.map { |item| cached_keys_with_value[item.id] || uncached[item.id] }.compact
+  end
 end