2020-02-24 04:08:51 -05:00
|
|
|
# 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)
|
|
|
|
"#{key}:set"
|
|
|
|
end
|
|
|
|
|
2020-03-18 11:09:45 -04:00
|
|
|
# Returns the number of keys deleted by Redis
|
2020-03-16 17:09:21 -04:00
|
|
|
def expire(*keys)
|
2020-03-18 11:09:45 -04:00
|
|
|
return 0 if keys.empty?
|
|
|
|
|
2020-03-16 17:09:21 -04:00
|
|
|
with do |redis|
|
|
|
|
keys = keys.map { |key| cache_key(key) }
|
2020-06-24 17:08:46 -04:00
|
|
|
|
|
|
|
Gitlab::Instrumentation::RedisClusterValidator.allow_cross_slot_commands do
|
|
|
|
unlink_or_delete(redis, keys)
|
|
|
|
end
|
2020-03-16 17:09:21 -04:00
|
|
|
end
|
2020-02-24 04:08:51 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def exist?(key)
|
|
|
|
with { |redis| redis.exists(cache_key(key)) }
|
|
|
|
end
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
def read(key)
|
|
|
|
with { |redis| redis.smembers(cache_key(key)) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def include?(key, value)
|
|
|
|
with { |redis| redis.sismember(cache_key(key), value) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def ttl(key)
|
|
|
|
with { |redis| redis.ttl(cache_key(key)) }
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def with(&blk)
|
|
|
|
Gitlab::Redis::Cache.with(&blk) # rubocop:disable CodeReuse/ActiveRecord
|
|
|
|
end
|
2020-03-16 17:09:21 -04:00
|
|
|
|
|
|
|
def unlink_or_delete(redis, keys)
|
|
|
|
if Feature.enabled?(:repository_set_cache_unlink, default_enabled: true)
|
|
|
|
redis.unlink(*keys)
|
|
|
|
else
|
|
|
|
redis.del(*keys)
|
|
|
|
end
|
2020-04-13 23:09:39 -04:00
|
|
|
rescue ::Redis::CommandError => e
|
|
|
|
Gitlab::ErrorTracking.log_exception(e)
|
|
|
|
|
2020-03-16 17:09:21 -04:00
|
|
|
redis.del(*keys)
|
|
|
|
end
|
2020-02-24 04:08:51 -05:00
|
|
|
end
|
|
|
|
end
|