client.rb 2.1 KB
Newer Older
1 2 3 4
# frozen_string_literal: true

module Sentry
  class Client
5
    include Sentry::Client::Event
6
    include Sentry::Client::Projects
7
    include Sentry::Client::Issue
8

9
    Error = Class.new(StandardError)
10
    MissingKeysError = Class.new(StandardError)
11
    ResponseInvalidSizeError = Class.new(StandardError)
12 13 14 15 16 17 18 19 20 21

    attr_accessor :url, :token

    def initialize(api_url, token)
      @url = api_url
      @token = token
    end

    private

22 23 24
    def handle_mapping_exceptions(&block)
      yield
    rescue KeyError => e
25
      Gitlab::ErrorTracking.track_exception(e)
26
      raise MissingKeysError, "Sentry API response is missing keys. #{e.message}"
27 28
    end

29 30 31 32 33 34 35 36 37
    def request_params
      {
        headers: {
          'Authorization' => "Bearer #{@token}"
        },
        follow_redirects: false
      }
    end

38
    def http_get(url, params = {})
39
      http_request do
40 41
        Gitlab::HTTP.get(url, **request_params.merge(params))
      end
42 43 44 45
    end

    def http_put(url, params = {})
      http_request do
46
        Gitlab::HTTP.put(url, **request_params.merge(body: params))
47 48 49 50 51 52 53 54
      end
    end

    def http_request
      response = handle_request_exceptions do
        yield
      end

55
      handle_response(response)
56 57
    end

58 59
    def handle_request_exceptions
      yield
60
    rescue Gitlab::HTTP::Error => e
61
      Gitlab::ErrorTracking.track_exception(e)
62 63 64 65 66 67 68 69 70 71
      raise_error 'Error when connecting to Sentry'
    rescue Net::OpenTimeout
      raise_error 'Connection to Sentry timed out'
    rescue SocketError
      raise_error 'Received SocketError when trying to connect to Sentry'
    rescue OpenSSL::SSL::SSLError
      raise_error 'Sentry returned invalid SSL data'
    rescue Errno::ECONNREFUSED
      raise_error 'Connection refused'
    rescue => e
72
      Gitlab::ErrorTracking.track_exception(e)
73 74 75
      raise_error "Sentry request failed due to #{e.class}"
    end

76 77
    def handle_response(response)
      unless response.code == 200
78
        raise_error "Sentry response status code: #{response.code}"
79 80
      end

81
      { body: response.parsed_response, headers: response.headers }
82 83
    end

84 85 86
    def raise_error(message)
      raise Client::Error, message
    end
87 88
  end
end