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

set_cache.rb « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: c7818cb34180989339fa199809b76bff5a1d792a (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
79
80
81
82
83
84
85
# frozen_string_literal: true

# Interface to the Redis-backed cache store to keep track of complete cache keys
# for a ReactiveCache resource.
module Gitlab
  class SetCache
    attr_reader :expires_in

    def initialize(expires_in: 2.weeks)
      @expires_in = expires_in
    end

    def cache_key(key)
      "#{cache_namespace}:#{key}:set"
    end

    # Returns the number of keys deleted by Redis
    def expire(*keys)
      return 0 if keys.empty?

      with do |redis|
        keys_to_expire = keys.map { |key| cache_key(key) }

        Gitlab::Instrumentation::RedisClusterValidator.allow_cross_slot_commands do
          redis.unlink(*keys_to_expire)
        end
      end
    end

    def exist?(key)
      with { |redis| redis.exists?(cache_key(key)) } # rubocop:disable CodeReuse/ActiveRecord
    end

    def write(key, value)
      with do |redis|
        redis.pipelined do |pipeline|
          pipeline.sadd(cache_key(key), value)

          pipeline.expire(cache_key(key), expires_in)
        end
      end

      value
    end

    def read(key)
      with { |redis| redis.smembers(cache_key(key)) }
    end

    def include?(key, value)
      with { |redis| redis.sismember(cache_key(key), value) }
    end

    # Like include?, but also tells us if the cache was populated when it ran
    # by returning two booleans: [member_exists, set_exists]
    def try_include?(key, value)
      full_key = cache_key(key)

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

    def ttl(key)
      with { |redis| redis.ttl(cache_key(key)) }
    end

    def count(key)
      with { |redis| redis.scard(cache_key(key)) }
    end

    private

    def with(&blk)
      Gitlab::Redis::Cache.with(&blk) # rubocop:disable CodeReuse/ActiveRecord
    end

    def cache_namespace
      Gitlab::Redis::Cache::CACHE_NAMESPACE
    end
  end
end