Welcome to mirror list, hosted at ThFree Co, Russian Federation.

helper.rb « process_memory_cache « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 8d436c14b48a4b7bb06b63705a5497678a3aa9af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# frozen_string_literal: true

module Gitlab
  class ProcessMemoryCache
    module Helper
      def fetch_memory_cache(key, &payload)
        cache = cache_backend.read(key)

        if cache && !stale_cache?(key, cache)
          cache[:data]
        else
          store_cache(key, &payload)
        end
      end

      def invalidate_memory_cache(key)
        touch_cache_timestamp(key)
      end

      private

      def touch_cache_timestamp(key, time = Time.current.to_f)
        shared_backend.write(key, time)
      end

      def stale_cache?(key, cache_info)
        shared_timestamp = shared_backend.read(key)
        return true unless shared_timestamp

        shared_timestamp.to_f > cache_info[:cached_at].to_f
      end

      def store_cache(key)
        data = yield
        time = Time.current.to_f

        cache_backend.write(key, data: data, cached_at: time)
        touch_cache_timestamp(key, time) unless shared_backend.read(key)
        data
      end

      def shared_backend
        Rails.cache
      end

      def cache_backend
        ::Gitlab::ProcessMemoryCache.cache_backend
      end
    end
  end
end