2018-11-20 20:47:30 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
module RedisCacheable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
include Gitlab::Utils::StrongMemoize
|
|
|
|
|
|
|
|
CACHED_ATTRIBUTES_EXPIRY_TIME = 24.hours
|
|
|
|
|
|
|
|
class_methods do
|
|
|
|
def cached_attr_reader(*attributes)
|
|
|
|
attributes.each do |attribute|
|
2018-11-08 19:23:39 +05:30
|
|
|
define_method(attribute) do
|
|
|
|
unless self.has_attribute?(attribute)
|
|
|
|
raise ArgumentError, "`cached_attr_reader` requires the #{self.class.name}\##{attribute} attribute to have a database column"
|
|
|
|
end
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
cached_attribute(attribute) || read_attribute(attribute)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def cached_attribute(attribute)
|
2018-11-08 19:23:39 +05:30
|
|
|
cached_value = (cached_attributes || {})[attribute]
|
|
|
|
cast_value_from_cache(attribute, cached_value) if cached_value
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
def cache_attributes(values)
|
2023-01-13 00:05:48 +05:30
|
|
|
with_redis do |redis|
|
|
|
|
redis.set(cache_attribute_key, Gitlab::Json.dump(values), ex: CACHED_ATTRIBUTES_EXPIRY_TIME)
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
2018-11-08 19:23:39 +05:30
|
|
|
|
|
|
|
clear_memoization(:cached_attributes)
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def cache_attribute_key
|
|
|
|
"cache:#{self.class.name}:#{self.id}:attributes"
|
|
|
|
end
|
|
|
|
|
|
|
|
def cached_attributes
|
|
|
|
strong_memoize(:cached_attributes) do
|
2023-01-13 00:05:48 +05:30
|
|
|
with_redis do |redis|
|
2018-03-17 18:26:18 +05:30
|
|
|
data = redis.get(cache_attribute_key)
|
2020-05-24 23:13:21 +05:30
|
|
|
Gitlab::Json.parse(data, symbolize_names: true) if data
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2018-11-08 19:23:39 +05:30
|
|
|
|
2023-01-13 00:05:48 +05:30
|
|
|
def with_redis(&block)
|
|
|
|
Gitlab::Redis::Cache.with(&block) # rubocop:disable CodeReuse/ActiveRecord
|
|
|
|
end
|
|
|
|
|
2018-11-08 19:23:39 +05:30
|
|
|
def cast_value_from_cache(attribute, value)
|
2019-02-13 22:33:31 +05:30
|
|
|
self.class.type_for_attribute(attribute.to_s).cast(value)
|
2018-11-08 19:23:39 +05:30
|
|
|
end
|
2018-03-17 18:26:18 +05:30
|
|
|
end
|