repository_cache.rb 1.06 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6 7
# Interface to the Redis-backed cache store
module Gitlab
  class RepositoryCache
    attr_reader :repository, :namespace, :backend

8
    def initialize(repository, extra_namespace: nil, backend: Rails.cache)
9
      @repository = repository
10
      @namespace = "#{repository.full_path}:#{repository.project.id}"
11
      @namespace = "#{@namespace}:#{extra_namespace}" if extra_namespace
12 13 14 15
      @backend = backend
    end

    def cache_key(type)
16
      "#{type}:#{namespace}"
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
    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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

    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
50 51
  end
end