|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "net/http" |
| 4 | +require "zlib" |
| 5 | + |
| 6 | +module Sentry |
| 7 | + module Spotlight |
| 8 | + |
| 9 | + |
| 10 | + # Spotlight Transport class is like HTTPTransport, |
| 11 | + # but it's experimental, with limited featureset. |
| 12 | + # - It does not care about rate limits, assuming working with local Sidecar proxy |
| 13 | + # - Designed to just report events to Spotlight in development. |
| 14 | + # |
| 15 | + # TODO: This needs a cleanup, we could extract most of common code into a module. |
| 16 | + class Transport |
| 17 | + |
| 18 | + GZIP_ENCODING = "gzip" |
| 19 | + GZIP_THRESHOLD = 1024 * 30 |
| 20 | + CONTENT_TYPE = 'application/x-sentry-envelope' |
| 21 | + USER_AGENT = "sentry-ruby/#{Sentry::VERSION}" |
| 22 | + |
| 23 | + # Initialize a new Spotlight transport |
| 24 | + # with the provided Spotlight configuration. |
| 25 | + def initialize(spotlight_configuration) |
| 26 | + @configuration = spotlight_configuration |
| 27 | + end |
| 28 | + |
| 29 | + def send_data(data) |
| 30 | + encoding = "" |
| 31 | + |
| 32 | + if should_compress?(data) |
| 33 | + data = Zlib.gzip(data) |
| 34 | + encoding = GZIP_ENCODING |
| 35 | + end |
| 36 | + |
| 37 | + headers = { |
| 38 | + 'Content-Type' => CONTENT_TYPE, |
| 39 | + 'Content-Encoding' => encoding, |
| 40 | + 'X-Sentry-Auth' => generate_auth_header, |
| 41 | + 'User-Agent' => USER_AGENT |
| 42 | + } |
| 43 | + |
| 44 | + response = conn.start do |http| |
| 45 | + request = ::Net::HTTP::Post.new(@configuration.sidecar_url, headers) |
| 46 | + request.body = data |
| 47 | + http.request(request) |
| 48 | + end |
| 49 | + |
| 50 | + unless response.code.match?(/\A2\d{2}/) |
| 51 | + error_info = "the server responded with status #{response.code}" |
| 52 | + error_info += "\nbody: #{response.body}" |
| 53 | + error_info += " Error in headers is: #{response['x-sentry-error']}" if response['x-sentry-error'] |
| 54 | + |
| 55 | + raise Sentry::ExternalError, error_info |
| 56 | + end |
| 57 | + rescue SocketError => e |
| 58 | + raise Sentry::ExternalError.new(e.message) |
| 59 | + end |
| 60 | + |
| 61 | + private |
| 62 | + |
| 63 | + def should_compress?(data) |
| 64 | + @transport_configuration.encoding == GZIP_ENCODING && data.bytesize >= GZIP_THRESHOLD |
| 65 | + end |
| 66 | + |
| 67 | + # Similar to HTTPTransport connection, but does not support Proxy and SSL |
| 68 | + def conn |
| 69 | + sidecar = URL(@configuration.sidecar_url) |
| 70 | + connection = ::Net::HTTP.new(sidecar.hostname, sidecar.port, nil) |
| 71 | + connection.use_ssl = false |
| 72 | + connection |
| 73 | + end |
| 74 | + |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments