exceptbox 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ namespace :exceptbox do
4
+ desc "Send a test error to Exceptbox to check the setup"
5
+ task test: :environment do
6
+ config = Exceptbox.configuration
7
+
8
+ abort "Exceptbox: no API key. Set EXCEPTBOX_API_KEY or config.api_key." unless config.valid_api_key?
9
+
10
+ unless config.notify_release_stage?
11
+ puts "Exceptbox: release stage #{config.release_stage.inspect} is not in enabled_release_stages " \
12
+ "#{config.enabled_release_stages.inspect}; sending the test anyway."
13
+ end
14
+
15
+ stages = config.enabled_release_stages
16
+ config.enabled_release_stages = nil
17
+ config.async = false
18
+
19
+ status = nil
20
+ original = Exceptbox::Delivery.transport
21
+ Exceptbox::Delivery.transport = lambda do |*args|
22
+ result = original.call(*args)
23
+ status = Array(result).first
24
+ result
25
+ end
26
+
27
+ begin
28
+ raise Exceptbox::TestError, "Test error from #{config.app_type || 'Ruby'} (rake exceptbox:test)"
29
+ rescue Exceptbox::TestError => e
30
+ Exceptbox.notify(e, severity: "info", source: "test")
31
+ ensure
32
+ Exceptbox::Delivery.transport = original
33
+ config.enabled_release_stages = stages
34
+ end
35
+
36
+ case status
37
+ when 200..299 then puts "Exceptbox: test error sent to #{config.endpoint}. It should appear in your dashboard."
38
+ when 401, 403 then abort "Exceptbox: the API key was rejected (HTTP #{status})."
39
+ when nil then abort "Exceptbox: could not reach #{config.endpoint}. See the log for details."
40
+ else abort "Exceptbox: unexpected response HTTP #{status}."
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Exceptbox
4
+ VERSION = "0.1.0"
5
+ end
data/lib/exceptbox.rb ADDED
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "exceptbox/version"
4
+ require "exceptbox/configuration"
5
+ require "exceptbox/context"
6
+ require "exceptbox/cleaner"
7
+ require "exceptbox/stacktrace"
8
+ require "exceptbox/event"
9
+ require "exceptbox/request_data"
10
+ require "exceptbox/breadcrumbs"
11
+ require "exceptbox/delivery"
12
+ require "exceptbox/async_queue"
13
+ require "exceptbox/integrations/rack"
14
+ require "exceptbox/integrations/at_exit"
15
+
16
+ # Exceptbox: error monitoring for Ruby and Rails.
17
+ #
18
+ # Exceptbox.configure do |config|
19
+ # config.api_key = ENV["EXCEPTBOX_API_KEY"]
20
+ # end
21
+ #
22
+ # Exceptbox.notify(exception) # report a rescued exception
23
+ # Exceptbox.notify("Payment provider timed out") # or just a message
24
+ # Exceptbox.notify(e, severity: "info") { |event| event.add_metadata(:order, id: 42) }
25
+ #
26
+ # Exceptbox.set_user(current_user) # attach the user to errors in this request/job
27
+ # Exceptbox.add_metadata(:account, plan: "pro") # extra data, shown as a tab in the dashboard
28
+ # Exceptbox.leave_breadcrumb("Charged card", { amount: 100 })
29
+ module Exceptbox
30
+ # Raised by `rake exceptbox:test` to check the setup end to end.
31
+ class TestError < StandardError; end
32
+
33
+ class << self
34
+ def configuration
35
+ @configuration ||= Configuration.new
36
+ end
37
+
38
+ def configure
39
+ yield configuration
40
+ configuration.logger&.warn("No API key set; errors will not be sent") unless configuration.valid_api_key?
41
+ configuration
42
+ end
43
+
44
+ # Reports an exception (or a message). Never raises: a failure here must
45
+ # not replace the app's original error. Returns true when the event was
46
+ # accepted for sending.
47
+ #
48
+ # Rescued exceptions default to severity "warning"; unhandled ones (from
49
+ # the integrations) are "error".
50
+ def notify(exception, severity: "warning", handled: true, metadata: nil, context: nil, source: "notify", &block)
51
+ config = configuration
52
+ return false unless config.valid_api_key? && config.notify_release_stage?
53
+
54
+ exception = normalize(exception)
55
+ return false unless exception
56
+ return false if already_notified?(exception)
57
+ return false if config.ignored?(exception, request: request_source?(source))
58
+
59
+ event = build_event(exception, config, severity: severity, handled: handled, source: source, context: context)
60
+ metadata&.each { |section, data| event.add_metadata(section, data) }
61
+ block&.call(event)
62
+ return false if event.ignored? || rejected_by_callbacks?(event, config)
63
+
64
+ mark_notified(exception)
65
+ deliver(event.to_h, config)
66
+ rescue StandardError => e
67
+ configuration.logger&.error("Failed to notify: #{e.class}: #{e.message}")
68
+ false
69
+ end
70
+
71
+ def set_user(user)
72
+ Context.current.user = user
73
+ end
74
+
75
+ def add_metadata(section, data)
76
+ Context.current.add_metadata(section, data)
77
+ end
78
+
79
+ def leave_breadcrumb(name, metadata = {}, type: "manual")
80
+ Breadcrumbs.leave(name, metadata, type: type)
81
+ end
82
+
83
+ # Context shown as the error's location, e.g. "PaymentsController#create"
84
+ def set_context(name)
85
+ Context.current.context_name = name.to_s
86
+ end
87
+
88
+ # Sends everything still queued (e.g. at the end of a short script).
89
+ def flush(timeout: AsyncQueue::SHUTDOWN_TIMEOUT)
90
+ @queue&.flush(timeout: timeout)
91
+ end
92
+
93
+ def reset!
94
+ @queue&.shutdown
95
+ @queue = nil
96
+ @configuration = nil
97
+ Context.clear!
98
+ Delivery.reset!
99
+ end
100
+
101
+ private
102
+
103
+ def normalize(exception)
104
+ exception = message_exception(exception) if exception.is_a?(String)
105
+ return nil unless exception.is_a?(Exception)
106
+
107
+ # A view error reaches the middleware wrapped in ActionView::Template::Error;
108
+ # report what really failed (and keep ignored classes ignored).
109
+ if defined?(::ActionView::Template::Error) && exception.is_a?(::ActionView::Template::Error) && exception.cause
110
+ exception = exception.cause
111
+ end
112
+ exception
113
+ end
114
+
115
+ def message_exception(message)
116
+ error = RuntimeError.new(message)
117
+ error.set_backtrace(caller_locations.reject { |loc| loc.path.include?("/lib/exceptbox") }.map(&:to_s))
118
+ error
119
+ end
120
+
121
+ def build_event(exception, config, severity:, handled:, source:, context:)
122
+ current = Context.current
123
+ event = Event.new(exception, config: config, handled: handled, severity: severity, source: source)
124
+ event.context = context || current.context_name || controller_action(current.env)
125
+ event.request = RequestData.from_env(current.env, config) if current.env
126
+ event.job = current.job
127
+ event.user = current.user || resolve_user(current.env, config)
128
+ current.metadata.each { |section, data| event.add_metadata(section, data) }
129
+ event.add_breadcrumbs(current.breadcrumbs.dup)
130
+ event
131
+ end
132
+
133
+ # "OrdersController#create", from what Rails' router stored in the env
134
+ def controller_action(env)
135
+ return nil unless env.is_a?(Hash)
136
+
137
+ if (controller = env["action_controller.instance"])
138
+ "#{controller.class.name}##{controller.action_name}"
139
+ elsif (params = env["action_dispatch.request.path_parameters"]) && params[:controller]
140
+ "#{params[:controller].split('/').map { |part| part.split('_').map(&:capitalize).join }.join('::')}Controller##{params[:action]}"
141
+ end
142
+ rescue StandardError
143
+ nil
144
+ end
145
+
146
+ def resolve_user(env, config)
147
+ resolver = config.current_user
148
+ return nil unless resolver.respond_to?(:call)
149
+
150
+ resolver.arity.zero? ? resolver.call : resolver.call(env)
151
+ rescue StandardError
152
+ nil
153
+ end
154
+
155
+ def rejected_by_callbacks?(event, config)
156
+ config.before_notify_callbacks.any? do |callback|
157
+ result = callback.call(event)
158
+ result == false || event.ignored?
159
+ rescue StandardError => e
160
+ config.logger&.warn("before_notify callback failed: #{e.class}: #{e.message}")
161
+ false
162
+ end
163
+ end
164
+
165
+ def deliver(payload, config)
166
+ if config.async
167
+ (@queue ||= AsyncQueue.new(config)).push(payload)
168
+ else
169
+ Delivery.deliver([payload], config)
170
+ true
171
+ end
172
+ end
173
+
174
+ # The same exception can pass through several layers (job hook, Rack
175
+ # middleware, Rails' executor): report it once.
176
+ def already_notified?(exception)
177
+ exception.instance_variable_defined?(:@__exceptbox_notified)
178
+ end
179
+
180
+ def mark_notified(exception)
181
+ exception.instance_variable_set(:@__exceptbox_notified, true)
182
+ rescue FrozenError
183
+ nil
184
+ end
185
+
186
+ def request_source?(source)
187
+ %w[request application.action_dispatch].include?(source.to_s)
188
+ end
189
+ end
190
+ end
191
+
192
+ require "exceptbox/integrations/sidekiq" if defined?(::Sidekiq)
193
+ require "exceptbox/integrations/railtie" if defined?(::Rails::Railtie)
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Exceptbox
6
+ module Generators
7
+ # rails generate exceptbox:install YOUR_API_KEY
8
+ class InstallGenerator < ::Rails::Generators::Base
9
+ source_root File.expand_path("templates", __dir__)
10
+
11
+ argument :api_key, type: :string, required: false,
12
+ desc: "Your project's API key (or set EXCEPTBOX_API_KEY later)"
13
+
14
+ def create_initializer
15
+ template "exceptbox.rb.tt", "config/initializers/exceptbox.rb"
16
+ end
17
+
18
+ def show_next_steps
19
+ say "\nExceptbox installed. Next:", :green
20
+ say " 1. #{api_key ? 'Keep the API key out of git: move it to EXCEPTBOX_API_KEY' : 'Set EXCEPTBOX_API_KEY in your environment'}"
21
+ say " 2. Run `bin/rails exceptbox:test` to send a test error\n"
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,33 @@
1
+ # Exceptbox error monitoring (generated by `rails generate exceptbox:install`).
2
+ #
3
+ # Reported automatically: unhandled exceptions in requests, ActiveJob and
4
+ # Sidekiq jobs, rake tasks and runner scripts, and Rails.error.handle/report.
5
+ # Report rescued errors yourself with Exceptbox.notify(exception).
6
+
7
+ Exceptbox.configure do |config|
8
+ # Your project's API key (Project settings in the Exceptbox dashboard).
9
+ config.api_key = ENV.fetch("EXCEPTBOX_API_KEY"<% if api_key %>, "<%= api_key %>"<% end %>)
10
+
11
+ # Stages that send errors. Others (development, test) are ignored.
12
+ config.enabled_release_stages = %w[production staging]
13
+
14
+ # The user attached to errors. `context` is the Rack env of the request.
15
+ # Exceptbox.set_user(current_user) in a before_action also works.
16
+ config.current_user = ->(env) { env["warden"]&.user } # Devise
17
+
18
+ # Never send these values (your filter_parameters are added automatically).
19
+ # config.filters += %w[iban national_id]
20
+
21
+ # Exceptions to never report.
22
+ # config.ignore_classes += %w[MyApp::ExpectedError]
23
+
24
+ # Change or drop events before they are sent.
25
+ # config.before_notify do |event|
26
+ # event.ignore! if event.exception.message.include?("Net::ReadTimeout")
27
+ # event.add_metadata(:account, plan: Current.account&.plan)
28
+ # end
29
+
30
+ # Deployed version, shown on each error. Auto-detected from common hosting
31
+ # env vars, a Capistrano REVISION file, or git.
32
+ # config.app_version = ENV["GIT_SHA"]
33
+ end
metadata ADDED
@@ -0,0 +1,67 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: exceptbox
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Inzamam Tahir
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Reports exceptions from Rails requests, ActiveJob and Sidekiq jobs, rake
13
+ tasks and Rails.error to Exceptbox, with stack traces, request details, users and
14
+ breadcrumbs. No runtime dependencies.
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - CHANGELOG.md
20
+ - LICENSE.txt
21
+ - README.md
22
+ - lib/exceptbox.rb
23
+ - lib/exceptbox/async_queue.rb
24
+ - lib/exceptbox/breadcrumbs.rb
25
+ - lib/exceptbox/cleaner.rb
26
+ - lib/exceptbox/configuration.rb
27
+ - lib/exceptbox/context.rb
28
+ - lib/exceptbox/delivery.rb
29
+ - lib/exceptbox/event.rb
30
+ - lib/exceptbox/integrations/active_job.rb
31
+ - lib/exceptbox/integrations/at_exit.rb
32
+ - lib/exceptbox/integrations/error_subscriber.rb
33
+ - lib/exceptbox/integrations/rack.rb
34
+ - lib/exceptbox/integrations/railtie.rb
35
+ - lib/exceptbox/integrations/sidekiq.rb
36
+ - lib/exceptbox/request_data.rb
37
+ - lib/exceptbox/stacktrace.rb
38
+ - lib/exceptbox/tasks/exceptbox.rake
39
+ - lib/exceptbox/version.rb
40
+ - lib/generators/exceptbox/install/install_generator.rb
41
+ - lib/generators/exceptbox/install/templates/exceptbox.rb.tt
42
+ homepage: https://exceptbox.com
43
+ licenses:
44
+ - MIT
45
+ metadata:
46
+ homepage_uri: https://exceptbox.com
47
+ source_code_uri: https://github.com/exceptbox/exceptbox-ruby
48
+ changelog_uri: https://github.com/exceptbox/exceptbox-ruby/blob/main/CHANGELOG.md
49
+ bug_tracker_uri: https://github.com/exceptbox/exceptbox-ruby/issues
50
+ rdoc_options: []
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '3.1'
58
+ required_rubygems_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '0'
63
+ requirements: []
64
+ rubygems_version: 3.6.9
65
+ specification_version: 4
66
+ summary: Error monitoring for Ruby and Rails apps, reported to Exceptbox.
67
+ test_files: []