cache_concern.rb 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. def attributes_for_database(record)
  75. attributes = record.attributes_for_database
  76. attributes.transform_values! { |attr| attr.is_a?(::ActiveModel::Type::Binary::Data) ? attr.to_s : attr }
  77. attributes
  78. end
  79. def deserialize_record(class_name, attributes_from_database, new_record = false) # rubocop:disable Style/OptionalBooleanParameter
  80. begin
  81. klass = Object.const_get(class_name)
  82. rescue NameError
  83. raise ClassMissingError, "undefined class: #{class_name}"
  84. end
  85. # Ideally we'd like to call `klass.instantiate`, however it doesn't allow to pass
  86. # wether the record was persisted or not.
  87. attributes = klass.attributes_builder.build_from_database(attributes_from_database, EMPTY_HASH)
  88. klass.allocate.init_with_attributes(attributes, new_record)
  89. end
  90. end
  91. class Error < StandardError
  92. end
  93. class ClassMissingError < Error
  94. end
  95. class AssociationMissingError < Error
  96. end
  97. class InstanceTracker
  98. def initialize
  99. @instances = []
  100. @ids = {}.compare_by_identity
  101. end
  102. def map(&block)
  103. @instances.map(&block)
  104. end
  105. def fetch(...)
  106. @instances.fetch(...)
  107. end
  108. def push(instance)
  109. id = @ids[instance] = @instances.size
  110. @instances << instance
  111. id
  112. end
  113. def lookup(instance)
  114. @ids[instance]
  115. end
  116. end
  117. end
  118. class_methods do
  119. def vary_by(value, **kwargs)
  120. before_action(**kwargs) do |controller|
  121. response.headers['Vary'] = value.respond_to?(:call) ? controller.instance_exec(&value) : value
  122. end
  123. end
  124. end
  125. included do
  126. after_action :enforce_cache_control!
  127. end
  128. # Prevents high-entropy headers such as `Cookie`, `Signature` or `Authorization`
  129. # from being used as cache keys, while allowing to `Vary` on them (to not serve
  130. # anonymous cached data to authenticated requests when authentication matters)
  131. def enforce_cache_control!
  132. vary = response.headers['Vary']&.split&.map { |x| x.strip.downcase }
  133. return unless vary.present? && %w(cookie authorization signature).any? { |header| vary.include?(header) && request.headers[header].present? }
  134. response.cache_control.replace(private: true, no_store: true)
  135. end
  136. def render_with_cache(**options)
  137. raise ArgumentError, 'Only JSON render calls are supported' unless options.key?(:json) || block_given?
  138. 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(':')
  139. expires_in = options.delete(:expires_in) || 3.minutes
  140. body = Rails.cache.read(key, raw: true)
  141. if body
  142. render(options.except(:json, :serializer, :each_serializer, :adapter, :fields).merge(json: body))
  143. else
  144. if block_given?
  145. options[:json] = yield
  146. elsif options[:json].is_a?(Symbol)
  147. options[:json] = send(options[:json])
  148. end
  149. render(options)
  150. Rails.cache.write(key, response.body, expires_in: expires_in, raw: true)
  151. end
  152. end
  153. def cache_collection(raw, klass)
  154. return raw unless klass.respond_to?(:with_includes)
  155. raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
  156. return [] if raw.empty?
  157. cached_keys_with_value = begin
  158. Rails.cache.read_multi(*raw).transform_keys(&:id).transform_values { |r| ActiveRecordCoder.load(r) }
  159. rescue ActiveRecordCoder::Error
  160. {} # The serialization format may have changed, let's pretend it's a cache miss.
  161. end
  162. uncached_ids = raw.map(&:id) - cached_keys_with_value.keys
  163. klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
  164. unless uncached_ids.empty?
  165. uncached = klass.where(id: uncached_ids).with_includes.index_by(&:id)
  166. uncached.each_value do |item|
  167. Rails.cache.write(item, ActiveRecordCoder.dump(item))
  168. end
  169. end
  170. raw.filter_map { |item| cached_keys_with_value[item.id] || uncached[item.id] }
  171. end
  172. def cache_collection_paginated_by_id(raw, klass, limit, options)
  173. cache_collection raw.cache_ids.to_a_paginated_by_id(limit, options), klass
  174. end
  175. end