This instance will be upgraded to Heptapod 0.31.0rc on 2022-05-19 at 11:00 UTC+2 (a few minutes of down time)

cacheable_attributes.rb 1.71 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
5
6
7
8
9
10
module CacheableAttributes
  extend ActiveSupport::Concern

  included do
    after_commit { self.class.expire }
  end

  class_methods do
11
    def cache_key
12
      "#{name}:#{Gitlab::VERSION}:#{Rails.version}".freeze
13
14
    end

15
    # Can be overridden
16
17
18
19
    def current_without_cache
      last
    end

20
    # Can be overridden
21
22
23
24
25
26
27
28
29
    def defaults
      {}
    end

    def build_from_defaults(attributes = {})
      new(defaults.merge(attributes))
    end

    def cached
30
      Gitlab::SafeRequestStore[:"#{name}_cached_attributes"] ||= retrieve_from_cache
31
32
33
34
35
    end

    def retrieve_from_cache
      record = Rails.cache.read(cache_key)
      ensure_cache_setup if record.present?
36

37
      record
38
39
40
41
42
43
44
    end

    def current
      cached_record = cached
      return cached_record if cached_record.present?

      current_without_cache.tap { |current_record| current_record&.cache! }
45
46
47
48
49
50
    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
51
52
53
54
55
56
57
58
59
60
      # 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
61
62
63
64
65
66

    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
67
68
69
  end

  def cache!
70
    Rails.cache.write(self.class.cache_key, self, expires_in: 1.minute)
71
72
  end
end