debian-mirror-gitlab/app/models/concerns/cacheable_attributes.rb

78 lines
1.8 KiB
Ruby
Raw Normal View History

2018-11-20 20:47:30 +05:30
# frozen_string_literal: true
2018-11-08 19:23:39 +05:30
module CacheableAttributes
extend ActiveSupport::Concern
included do
after_commit { self.class.expire }
end
class_methods do
def cache_key
"#{name}:#{Gitlab::VERSION}:#{Rails.version}".freeze
end
2018-12-13 13:39:08 +05:30
# Can be overridden
2018-11-08 19:23:39 +05:30
def current_without_cache
last
end
2018-12-13 13:39:08 +05:30
# Can be overridden
2018-11-08 19:23:39 +05:30
def defaults
{}
end
def build_from_defaults(attributes = {})
2019-02-13 22:33:31 +05:30
final_attributes = defaults
.merge(attributes)
.stringify_keys
.slice(*column_names)
new(final_attributes)
2018-11-08 19:23:39 +05:30
end
def cached
2018-12-05 23:21:45 +05:30
Gitlab::SafeRequestStore[:"#{name}_cached_attributes"] ||= retrieve_from_cache
2018-11-08 19:23:39 +05:30
end
def retrieve_from_cache
record = Rails.cache.read(cache_key)
ensure_cache_setup if record.present?
record
end
def current
cached_record = cached
return cached_record if cached_record.present?
current_without_cache.tap { |current_record| current_record&.cache! }
rescue => e
if Rails.env.production?
Rails.logger.warn("Cached record for #{name} couldn't be loaded, falling back to uncached record: #{e}")
else
raise e
end
# Fall back to an uncached value if there are any problems (e.g. Redis down)
current_without_cache
end
def expire
Rails.cache.delete(cache_key)
rescue
# Gracefully handle when Redis is not available. For example,
# omnibus may fail here during gitlab:assets:compile.
end
def ensure_cache_setup
# This is a workaround for a Rails bug that causes attribute methods not
# to be loaded when read from cache: https://github.com/rails/rails/issues/27348
define_attribute_methods
end
end
def cache!
Rails.cache.write(self.class.cache_key, self, expires_in: 1.minute)
end
end