Class: Gitlab::SetCache

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/set_cache.rb

Direct Known Subclasses

ReactiveCacheSetCache, RepositorySetCache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expires_in: 2.weeks) ⇒ SetCache

Returns a new instance of SetCache.


9
10
11
# File 'lib/gitlab/set_cache.rb', line 9

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

Instance Attribute Details

#expires_inObject (readonly)

Returns the value of attribute expires_in.


7
8
9
# File 'lib/gitlab/set_cache.rb', line 7

def expires_in
  @expires_in
end

Instance Method Details

#cache_key(key) ⇒ Object


13
14
15
# File 'lib/gitlab/set_cache.rb', line 13

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

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)

30
31
32
# File 'lib/gitlab/set_cache.rb', line 30

def exist?(key)
  with { |redis| redis.exists(cache_key(key)) }
end

#expire(*keys) ⇒ Object

Returns the number of keys deleted by Redis


18
19
20
21
22
23
24
25
26
27
28
# File 'lib/gitlab/set_cache.rb', line 18

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

#include?(key, value) ⇒ Boolean

Returns:

  • (Boolean)

50
51
52
# File 'lib/gitlab/set_cache.rb', line 50

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

#read(key) ⇒ Object


46
47
48
# File 'lib/gitlab/set_cache.rb', line 46

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

#try_include?(key, value) ⇒ Boolean

Like include?, but also tells us if the cache was populated when it ran by returning two booleans: [member_exists, set_exists]

Returns:

  • (Boolean)

56
57
58
59
60
61
62
63
64
65
# File 'lib/gitlab/set_cache.rb', line 56

def try_include?(key, value)
  full_key = cache_key(key)

  with do |redis|
    redis.multi do
      redis.sismember(full_key, value)
      redis.exists(full_key)
    end
  end
end

#ttl(key) ⇒ Object


67
68
69
# File 'lib/gitlab/set_cache.rb', line 67

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

#write(key, value) ⇒ Object


34
35
36
37
38
39
40
41
42
43
44
# File 'lib/gitlab/set_cache.rb', line 34

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

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

  value
end