summaryrefslogtreecommitdiff
path: root/lib/gitlab/web_hooks/recursion_detection/uuid.rb
blob: 9c52399818de47e81f12bfed6b19416497acfecb (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
# frozen_string_literal: true

module Gitlab
  module WebHooks
    module RecursionDetection
      class UUID
        HEADER = "#{::Gitlab::WebHooks::GITLAB_EVENT_HEADER}-UUID"

        include Singleton

        attr_accessor :request_uuid

        def initialize
          self.new_uuids_for_hooks = {}
        end

        class << self
          # Back the Singleton with RequestStore so it is isolated to this request.
          def instance
            Gitlab::SafeRequestStore[:web_hook_recursion_detection_uuid] ||= new
          end
        end

        # Returns a UUID, which will be either:
        #
        #   - The UUID that was recycled from the request headers if the request was made by a webhook.
        #   - A new UUID initialized for the webhook.
        def uuid_for_hook(hook)
          request_uuid || new_uuid_for_hook(hook)
        end

        def header(hook)
          { HEADER => uuid_for_hook(hook) }
        end

        private

        attr_accessor :new_uuids_for_hooks

        def new_uuid_for_hook(hook)
          new_uuids_for_hooks[hook.id] ||= SecureRandom.uuid
        end
      end
    end
  end
end