summaryrefslogtreecommitdiff
path: root/lib/gitlab/repository_cache.rb
blob: 56007574b1b75fb11974993f74a0f46ac65ce49c (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

# Interface to the Redis-backed cache store
module Gitlab
  class RepositoryCache
    attr_reader :repository, :namespace, :backend

    def initialize(repository, extra_namespace: nil, backend: Rails.cache)
      @repository = repository
      @namespace = "#{repository.full_path}:#{repository.project.id}"
      @namespace = "#{@namespace}:#{extra_namespace}" if extra_namespace
      @backend = backend
    end

    def cache_key(type)
      "#{type}:#{namespace}"
    end

    def expire(key)
      backend.delete(cache_key(key))
    end

    def fetch(key, &block)
      backend.fetch(cache_key(key), &block)
    end

    def exist?(key)
      backend.exist?(cache_key(key))
    end

    def read(key)
      backend.read(cache_key(key))
    end

    def write(key, value)
      backend.write(cache_key(key), value)
    end

    def fetch_without_caching_false(key, &block)
      value = read(key)
      return value if value

      value = yield

      # Don't cache false values
      write(key, value) if value

      value
    end
  end
end