Class: Treblle

Inherits:
Object
  • Object
show all
Defined in:
lib/treblle.rb

Overview

Treblle middleware for request interception and gathering.

Constant Summary collapse

TREBLLE_URI =
'https://rocknrolla.treblle.com'
TREBLLE_VERSION =
'0.6'

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Treblle

Returns a new instance of Treblle.



12
13
14
# File 'lib/treblle.rb', line 12

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
58
59
# File 'lib/treblle.rb', line 16

def call(env)
  request = ActionDispatch::Request.new(env)
  started_at = Time.now

  begin
    status, headers, response = @app.call(env)
    to_parse = response.clone
    to_parse = to_parse.try(:body) if to_parse.respond_to?(:body)

    begin
      json_response = JSON.parse(to_parse)
    rescue JSON::ParserError, TypeError
      # continue with original values when unable to parse reponse to json
      return [status, headers, response]
    end

    params = {
      ended_at: Time.now,
      env: env,
      headers: headers,
      json_response: json_response,
      request: request,
      started_at: started_at,
      status: status
    }
    capture(params)
  rescue Exception => e
    status = status_code_for_exception(e)
    params = {
      ended_at: Time.now,
      env: env,
      exception: e,
      headers: headers,
      request: request,
      started_at: started_at,
      status: status
    }
    # send error payload to treblle, but raise exception as well
    capture(params)
    raise e
  end

  [status, headers, response]
end

#capture(params) ⇒ Object

Creates data to send in a format that Treblle expects and does the sending in a new thread for perfomance reasons.

Parameters:

  • params (Object)


64
65
66
67
68
69
70
71
72
73
# File 'lib/treblle.rb', line 64

def capture(params)
  data = DataBuilder.new(params).call
  return if data&.bytesize.to_i > 2.megabytes # ignore the capture for unnaturally large requests

  Thread.new do
    send_to_treblle(data)
  end
rescue Exception => e
  Rails.logger.error(e.message)
end

#send_to_treblle(data) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/treblle.rb', line 75

def send_to_treblle(data)
  uri = URI(TREBLLE_URI)
  req = Net::HTTP::Post.new(uri)
  req['Content-Type'] = 'application/json'
  req['x-api-key'] = ENV.fetch('TREBLLE_API_KEY') { '' }
  req.body = data
  puts data
  res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
    http.request(req)
  end
  puts res.try(:body)
end

#status_code_for_exception(exception) ⇒ Object



88
89
90
91
92
93
# File 'lib/treblle.rb', line 88

def status_code_for_exception(exception)
  exception_wrapper = ActionDispatch::ExceptionWrapper.new(nil, exception)
  exception_wrapper.status_code
rescue
  500
end