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

store.rb « etag_caching « gitlab « lib - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d0d790a7c72d6347dd71e872841977e3ffdca570 (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
# frozen_string_literal: true

module Gitlab
  module EtagCaching
    class Store
      InvalidKeyError = Class.new(StandardError)

      EXPIRY_TIME = 20.minutes
      SHARED_STATE_NAMESPACE = 'etag:'

      def get(key)
        Gitlab::Redis::SharedState.with { |redis| redis.get(redis_shared_state_key(key)) }
      end

      def touch(key, only_if_missing: false)
        etag = generate_etag

        Gitlab::Redis::SharedState.with do |redis|
          redis.set(redis_shared_state_key(key), etag, ex: EXPIRY_TIME, nx: only_if_missing)
        end

        etag
      end

      private

      def generate_etag
        SecureRandom.hex
      end

      def redis_shared_state_key(key)
        raise InvalidKeyError, "#{key} is invalid" unless valid_key?(key)

        "#{SHARED_STATE_NAMESPACE}#{key}"
      rescue InvalidKeyError => e
        Gitlab::ErrorTracking.track_and_raise_for_dev_exception(e)
      end

      def valid_key?(key)
        return true if skip_validation?

        path, header = key.split(':', 2)
        env = {
          'PATH_INFO' => path,
          'HTTP_X_GITLAB_GRAPHQL_RESOURCE_ETAG' => header
        }

        fake_request = ActionDispatch::Request.new(env)
        !!Gitlab::EtagCaching::Router.match(fake_request)
      end

      def skip_validation?
        Rails.env.production?
      end
    end
  end
end