cache_concern.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # frozen_string_literal: true
  2. module CacheConcern
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def vary_by(value, **kwargs)
  6. before_action(**kwargs) do |controller|
  7. response.headers['Vary'] = value.respond_to?(:call) ? controller.instance_exec(&value) : value
  8. end
  9. end
  10. end
  11. included do
  12. after_action :enforce_cache_control!
  13. end
  14. # Prevents high-entropy headers such as `Cookie`, `Signature` or `Authorization`
  15. # from being used as cache keys, while allowing to `Vary` on them (to not serve
  16. # anonymous cached data to authenticated requests when authentication matters)
  17. def enforce_cache_control!
  18. vary = response.headers['Vary']&.split&.map { |x| x.strip.downcase }
  19. return unless vary.present? && %w(cookie authorization signature).any? { |header| vary.include?(header) && request.headers[header].present? }
  20. response.cache_control.replace(private: true, no_store: true)
  21. end
  22. def render_with_cache(**options)
  23. raise ArgumentError, 'Only JSON render calls are supported' unless options.key?(:json) || block_given?
  24. key = options.delete(:key) || [[params[:controller], params[:action]].join('/'), options[:json].respond_to?(:cache_key) ? options[:json].cache_key : nil, options[:fields].nil? ? nil : options[:fields].join(',')].compact.join(':')
  25. expires_in = options.delete(:expires_in) || 3.minutes
  26. body = Rails.cache.read(key, raw: true)
  27. if body
  28. render(options.except(:json, :serializer, :each_serializer, :adapter, :fields).merge(json: body))
  29. else
  30. if block_given?
  31. options[:json] = yield
  32. elsif options[:json].is_a?(Symbol)
  33. options[:json] = send(options[:json])
  34. end
  35. render(options)
  36. Rails.cache.write(key, response.body, expires_in: expires_in, raw: true)
  37. end
  38. end
  39. def cache_collection(raw, klass)
  40. return raw unless klass.respond_to?(:with_includes)
  41. raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
  42. return [] if raw.empty?
  43. cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id)
  44. uncached_ids = raw.map(&:id) - cached_keys_with_value.keys
  45. klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
  46. unless uncached_ids.empty?
  47. uncached = klass.where(id: uncached_ids).with_includes.index_by(&:id)
  48. Rails.cache.write_multi(uncached.values.to_h { |i| [i, i] })
  49. end
  50. raw.filter_map { |item| cached_keys_with_value[item.id] || uncached[item.id] }
  51. end
  52. def cache_collection_paginated_by_id(raw, klass, limit, options)
  53. cache_collection raw.cache_ids.to_a_paginated_by_id(limit, options), klass
  54. end
  55. end