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

repository_set_cache.rb « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 838f44c0f9e0d607c1b090914d12c3b8735f6dff (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# frozen_string_literal: true

# Interface to the Redis-backed cache store for keys that use a Redis set
module Gitlab
  class RepositorySetCache < Gitlab::SetCache
    attr_reader :repository, :namespace, :expires_in

    def initialize(repository, extra_namespace: nil, expires_in: 2.weeks)
      @repository = repository
      @namespace = "#{repository.full_path}"
      @namespace += ":#{repository.project.id}" if repository.project
      @namespace = "#{@namespace}:#{extra_namespace}" if extra_namespace
      @expires_in = expires_in
    end

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

    def write(key, value)
      full_key = cache_key(key)

      with do |redis|
        redis.multi do |multi|
          multi.unlink(full_key)

          # Splitting into groups of 1000 prevents us from creating a too-long
          # Redis command
          value.each_slice(1000) { |subset| multi.sadd(full_key, subset) }

          multi.expire(full_key, expires_in)
        end
      end

      value
    end

    def fetch(key, &block)
      full_key = cache_key(key)

      smembers, exists = with do |redis|
        redis.multi do |multi|
          multi.smembers(full_key)
          multi.exists?(full_key) # rubocop:disable CodeReuse/ActiveRecord
        end
      end

      return smembers if exists

      write(key, yield)
    end

    # Searches the cache set using SSCAN with the MATCH option. The MATCH
    # parameter is the pattern argument.
    # See https://redis.io/commands/scan#the-match-option for more information.
    # Returns an Enumerator that enumerates all SSCAN hits.
    def search(key, pattern, &block)
      full_key = cache_key(key)

      with do |redis|
        exists = redis.exists?(full_key) # rubocop:disable CodeReuse/ActiveRecord
        write(key, yield) unless exists

        redis.sscan_each(full_key, match: pattern)
      end
    end

    private

    def cache
      Gitlab::Redis::RepositoryCache
    end

    def with(&blk)
      cache.with(&blk) # rubocop:disable CodeReuse/ActiveRecord
    end
  end
end