2018-10-11 16:12:21 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-07-17 11:24:46 -04:00
|
|
|
module Gitlab
|
|
|
|
module Cache
|
2018-06-21 07:46:52 -04:00
|
|
|
# See https://docs.gitlab.com/ee/development/utilities.html#requestcache
|
2017-07-18 05:48:48 -04:00
|
|
|
module RequestCache
|
2017-07-17 11:24:46 -04:00
|
|
|
def self.extended(klass)
|
|
|
|
return if klass < self
|
|
|
|
|
|
|
|
extension = Module.new
|
2017-07-18 05:48:48 -04:00
|
|
|
klass.const_set(:RequestCacheExtension, extension)
|
2017-07-17 11:24:46 -04:00
|
|
|
klass.prepend(extension)
|
|
|
|
end
|
|
|
|
|
2017-11-17 07:27:16 -05:00
|
|
|
attr_accessor :request_cache_key_block
|
|
|
|
|
2017-07-18 06:04:20 -04:00
|
|
|
def request_cache_key(&block)
|
2017-07-17 11:24:46 -04:00
|
|
|
if block_given?
|
2017-11-17 07:27:16 -05:00
|
|
|
self.request_cache_key_block = block
|
2017-07-17 11:24:46 -04:00
|
|
|
else
|
2017-11-17 07:27:16 -05:00
|
|
|
request_cache_key_block
|
2017-07-17 11:24:46 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-07-18 06:04:20 -04:00
|
|
|
def request_cache(method_name, &method_key_block)
|
2019-10-15 23:06:12 -04:00
|
|
|
const_get(:RequestCacheExtension, false).module_eval do
|
2017-07-18 05:48:48 -04:00
|
|
|
cache_key_method_name = "#{method_name}_cache_key"
|
|
|
|
|
2017-07-17 13:18:20 -04:00
|
|
|
define_method(method_name) do |*args|
|
|
|
|
store =
|
2018-09-20 18:40:15 -04:00
|
|
|
if Gitlab::SafeRequestStore.active?
|
|
|
|
Gitlab::SafeRequestStore.store
|
2017-07-17 13:18:20 -04:00
|
|
|
else
|
|
|
|
ivar_name = # ! and ? cannot be used as ivar name
|
2017-07-18 05:48:48 -04:00
|
|
|
"@cache_#{method_name.to_s.tr('!?', "\u2605\u2606")}"
|
2017-07-17 11:24:46 -04:00
|
|
|
|
2017-07-17 13:18:20 -04:00
|
|
|
instance_variable_get(ivar_name) ||
|
|
|
|
instance_variable_set(ivar_name, {})
|
|
|
|
end
|
|
|
|
|
2017-08-10 12:39:26 -04:00
|
|
|
key = __send__(cache_key_method_name, args) # rubocop:disable GitlabSecurity/PublicSend
|
2017-07-17 11:24:46 -04:00
|
|
|
|
2017-07-18 05:48:48 -04:00
|
|
|
store.fetch(key) { store[key] = super(*args) }
|
2017-07-17 11:24:46 -04:00
|
|
|
end
|
2017-07-17 13:18:20 -04:00
|
|
|
|
|
|
|
define_method(cache_key_method_name) do |args|
|
|
|
|
klass = self.class
|
|
|
|
|
2017-07-18 06:04:20 -04:00
|
|
|
instance_key = instance_exec(&klass.request_cache_key) if
|
|
|
|
klass.request_cache_key
|
2017-07-17 13:18:20 -04:00
|
|
|
|
|
|
|
method_key = instance_exec(&method_key_block) if method_key_block
|
|
|
|
|
|
|
|
[klass.name, method_name, *instance_key, *method_key, *args]
|
|
|
|
.join(':')
|
|
|
|
end
|
|
|
|
|
2020-09-03 17:08:18 -04:00
|
|
|
private cache_key_method_name # rubocop: disable Style/AccessModifierDeclarations
|
2017-07-17 13:18:20 -04:00
|
|
|
end
|
2017-07-17 11:24:46 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|