cache_concern.rb 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # frozen_string_literal: true
  2. module CacheConcern
  3. extend ActiveSupport::Concern
  4. module ActiveRecordCoder
  5. EMPTY_HASH = {}.freeze
  6. class << self
  7. def dump(record)
  8. instances = InstanceTracker.new
  9. serialized_associations = serialize_associations(record, instances)
  10. serialized_records = instances.map { |r| serialize_record(r) }
  11. [serialized_associations, *serialized_records]
  12. end
  13. def load(payload)
  14. instances = InstanceTracker.new
  15. serialized_associations, *serialized_records = payload
  16. serialized_records.each { |attrs| instances.push(deserialize_record(*attrs)) }
  17. deserialize_associations(serialized_associations, instances)
  18. end
  19. private
  20. # Records without associations, or which have already been visited before,
  21. # are serialized by their id alone.
  22. #
  23. # Records with associations are serialized as a two-element array including
  24. # their id and the record's association cache.
  25. #
  26. def serialize_associations(record, instances)
  27. return unless record
  28. if (id = instances.lookup(record))
  29. payload = id
  30. else
  31. payload = instances.push(record)
  32. cached_associations = record.class.reflect_on_all_associations.select do |reflection|
  33. record.association_cached?(reflection.name)
  34. end
  35. unless cached_associations.empty?
  36. serialized_associations = cached_associations.map do |reflection|
  37. association = record.association(reflection.name)
  38. serialized_target = if reflection.collection?
  39. association.target.map { |target_record| serialize_associations(target_record, instances) }
  40. else
  41. serialize_associations(association.target, instances)
  42. end
  43. [reflection.name, serialized_target]
  44. end
  45. payload = [payload, serialized_associations]
  46. end
  47. end
  48. payload
  49. end
  50. def deserialize_associations(payload, instances)
  51. return unless payload
  52. id, associations = payload
  53. record = instances.fetch(id)
  54. associations&.each do |name, serialized_target|
  55. begin
  56. association = record.association(name)
  57. rescue ActiveRecord::AssociationNotFoundError
  58. raise AssociationMissingError, "undefined association: #{name}"
  59. end
  60. target = if association.reflection.collection?
  61. serialized_target.map! { |serialized_record| deserialize_associations(serialized_record, instances) }
  62. else
  63. deserialize_associations(serialized_target, instances)
  64. end
  65. association.target = target
  66. end
  67. record
  68. end
  69. def serialize_record(record)
  70. arguments = [record.class.name, attributes_for_database(record)]
  71. arguments << true if record.new_record?
  72. arguments
  73. end
  74. if Rails.gem_version >= Gem::Version.new('7.0')
  75. def attributes_for_database(record)
  76. attributes = record.attributes_for_database
  77. attributes.transform_values! { |attr| attr.is_a?(::ActiveModel::Type::Binary::Data) ? attr.to_s : attr }
  78. attributes
  79. end
  80. else
  81. def attributes_for_database(record)
  82. attributes = record.instance_variable_get(:@attributes).send(:attributes).transform_values(&:value_for_database)
  83. attributes.transform_values! { |attr| attr.is_a?(::ActiveModel::Type::Binary::Data) ? attr.to_s : attr }
  84. attributes
  85. end
  86. end
  87. def deserialize_record(class_name, attributes_from_database, new_record = false) # rubocop:disable Style/OptionalBooleanParameter
  88. begin
  89. klass = Object.const_get(class_name)
  90. rescue NameError
  91. raise ClassMissingError, "undefined class: #{class_name}"
  92. end
  93. # Ideally we'd like to call `klass.instantiate`, however it doesn't allow to pass
  94. # wether the record was persisted or not.
  95. attributes = klass.attributes_builder.build_from_database(attributes_from_database, EMPTY_HASH)
  96. klass.allocate.init_with_attributes(attributes, new_record)
  97. end
  98. end
  99. class Error < StandardError
  100. end
  101. class ClassMissingError < Error
  102. end
  103. class AssociationMissingError < Error
  104. end
  105. class InstanceTracker
  106. def initialize
  107. @instances = []
  108. @ids = {}.compare_by_identity
  109. end
  110. def map(&block)
  111. @instances.map(&block)
  112. end
  113. def fetch(...)
  114. @instances.fetch(...)
  115. end
  116. def push(instance)
  117. id = @ids[instance] = @instances.size
  118. @instances << instance
  119. id
  120. end
  121. def lookup(instance)
  122. @ids[instance]
  123. end
  124. end
  125. end
  126. class_methods do
  127. def vary_by(value, **kwargs)
  128. before_action(**kwargs) do |controller|
  129. response.headers['Vary'] = value.respond_to?(:call) ? controller.instance_exec(&value) : value
  130. end
  131. end
  132. end
  133. included do
  134. after_action :enforce_cache_control!
  135. end
  136. # Prevents high-entropy headers such as `Cookie`, `Signature` or `Authorization`
  137. # from being used as cache keys, while allowing to `Vary` on them (to not serve
  138. # anonymous cached data to authenticated requests when authentication matters)
  139. def enforce_cache_control!
  140. vary = response.headers['Vary']&.split&.map { |x| x.strip.downcase }
  141. return unless vary.present? && %w(cookie authorization signature).any? { |header| vary.include?(header) && request.headers[header].present? }
  142. response.cache_control.replace(private: true, no_store: true)
  143. end
  144. def render_with_cache(**options)
  145. raise ArgumentError, 'Only JSON render calls are supported' unless options.key?(:json) || block_given?
  146. 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(':')
  147. expires_in = options.delete(:expires_in) || 3.minutes
  148. body = Rails.cache.read(key, raw: true)
  149. if body
  150. render(options.except(:json, :serializer, :each_serializer, :adapter, :fields).merge(json: body))
  151. else
  152. if block_given?
  153. options[:json] = yield
  154. elsif options[:json].is_a?(Symbol)
  155. options[:json] = send(options[:json])
  156. end
  157. render(options)
  158. Rails.cache.write(key, response.body, expires_in: expires_in, raw: true)
  159. end
  160. end
  161. def cache_collection(raw, klass)
  162. return raw unless klass.respond_to?(:with_includes)
  163. raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
  164. return [] if raw.empty?
  165. cached_keys_with_value = begin
  166. Rails.cache.read_multi(*raw).transform_keys(&:id).transform_values { |r| ActiveRecordCoder.load(r) }
  167. rescue ActiveRecordCoder::Error
  168. {} # The serialization format may have changed, let's pretend it's a cache miss.
  169. end
  170. uncached_ids = raw.map(&:id) - cached_keys_with_value.keys
  171. klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
  172. unless uncached_ids.empty?
  173. uncached = klass.where(id: uncached_ids).with_includes.index_by(&:id)
  174. uncached.each_value do |item|
  175. Rails.cache.write(item, ActiveRecordCoder.dump(item))
  176. end
  177. end
  178. raw.filter_map { |item| cached_keys_with_value[item.id] || uncached[item.id] }
  179. end
  180. def cache_collection_paginated_by_id(raw, klass, limit, options)
  181. cache_collection raw.cache_ids.to_a_paginated_by_id(limit, options), klass
  182. end
  183. end