summaryrefslogtreecommitdiff
path: root/app/services/protected_branches/cache_service.rb
blob: fed5dca258186a76f7e5680afc29ba9da7a73d4b (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
# frozen_string_literal: true

module ProtectedBranches
  class CacheService < ProtectedBranches::BaseService
    CACHE_ROOT_KEY = 'cache:gitlab:protected_branch'
    TTL_UNSET = -1
    CACHE_EXPIRE_IN = 1.day
    CACHE_LIMIT = 1000

    def fetch(ref_name)
      record = OpenSSL::Digest::SHA256.hexdigest(ref_name)

      Gitlab::Redis::Cache.with do |redis|
        cached_result = redis.hget(redis_key, record)

        break Gitlab::Redis::Boolean.decode(cached_result) unless cached_result.nil?

        value = yield

        redis.hset(redis_key, record, Gitlab::Redis::Boolean.encode(value))

        # We don't want to extend cache expiration time
        if redis.ttl(redis_key) == TTL_UNSET
          redis.expire(redis_key, CACHE_EXPIRE_IN)
        end

        # If the cache record has too many elements, then something went wrong and
        # it's better to drop the cache key.
        if redis.hlen(redis_key) > CACHE_LIMIT
          redis.unlink(redis_key)
        end

        value
      end
    end

    def refresh
      Gitlab::Redis::Cache.with { |redis| redis.unlink(redis_key) }
    end

    private

    def redis_key
      @redis_key ||= [CACHE_ROOT_KEY, @project.id].join(':')
    end
  end
end