prodbat 0.0.1

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ce4431af32a6a81e508411aab47bd9ba293dd88e745508bd1f3388e78684b733
4
+ data.tar.gz: a581f5b6150fef66ddad04893d36ef18dc9e0f030507e76e85174521791b8db4
5
+ SHA512:
6
+ metadata.gz: 8215298e36d31ce618600c2dac2dfc47276d00b294ea6c733aee90cb842be0d8f08f2402dd8eac6106cff342bab95d9d8310d12277634081cdff09e41676fd33
7
+ data.tar.gz: 43e54520ce58a12f047c9a9d044dbe15b726ceb24b8a8b0ff213829f860c2532238a13f10feb60e7702642b1ebe089aa020f04b7faa5bb231c598be6ba66afea
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Prodbat
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # prodbat (Ruby)
2
+
3
+ Monitoring for apps built with AI. This gem sends a Ruby app's server errors, log lines, scheduled-job check-ins, Sidekiq queue health and Stripe events to [Prodbat](https://github.com/prodbat/prodbat). It has no dependencies, never raises, and never holds a request up: reports go out from a background thread and are dropped if Prodbat can't be reached.
4
+
5
+ ## Install
6
+
7
+ ```ruby
8
+ # Gemfile
9
+ gem "prodbat"
10
+ ```
11
+
12
+ Set `PRODBAT_KEY` and `PRODBAT_URL` in the environment (`npx prodbat init` writes them to `.env`).
13
+
14
+ - **Rails**: nothing more. The gem adds its middleware just inside `ShowExceptions`, so every exception is reported with its backtrace and route (`POST /api/checkout/:id`), and failed Active Job jobs are reported too.
15
+ - **Sinatra, Hanami, Roda, any Rack app**: `use Prodbat::Middleware` in `config.ru`, before `run`.
16
+ - **Sidekiq**: in an initializer, `require "prodbat/sidekiq"` and `Prodbat::Sidekiq.watch`. Every minute it reports each queue's size and how long its oldest job has waited, plus Sidekiq's failed count; in the Sidekiq server it also reports each job's exception.
17
+
18
+ ## Also
19
+
20
+ ```ruby
21
+ Prodbat.log("refund issued", order: 1042) # a log line, with fields
22
+ Rails.logger.broadcast_to(Prodbat::Logger.new) # Rails 7.1+: send what the app already logs
23
+ Prodbat.ping("nightly-email", every: "24h") # at the end of a scheduled job, after it succeeded
24
+ Prodbat.stripe_event(event) # in the Stripe webhook, after the signature check
25
+ Prodbat.capture_exception(error, route: "POST /x") # report one yourself
26
+ ```
27
+
28
+ ## Tests
29
+
30
+ ```sh
31
+ for f in test/test_*.rb; do MT_NO_PLUGINS=1 ruby -Ilib "$f"; done # each file in its own process
32
+ ```
33
+
34
+ MIT licence.
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+
5
+ module Prodbat
6
+ # A Logger that sends what the app already logs. On Rails 7.1+:
7
+ # Rails.logger.broadcast_to(Prodbat::Logger.new(level: :info))
8
+ # Anywhere else, use it like any Logger.
9
+ class Logger < ::Logger
10
+ LEVELS = { ::Logger::DEBUG => "debug", ::Logger::INFO => "info", ::Logger::WARN => "warning",
11
+ ::Logger::ERROR => "error", ::Logger::FATAL => "error", ::Logger::UNKNOWN => "info" }.freeze
12
+
13
+ def initialize(level: :info)
14
+ super(nil, level: level)
15
+ end
16
+
17
+ def add(severity, message = nil, progname = nil)
18
+ severity ||= ::Logger::UNKNOWN
19
+ return true if severity < level
20
+
21
+ message = yield if message.nil? && block_given?
22
+ message = progname if message.nil?
23
+ text = message.is_a?(Exception) ? "#{message.class}: #{message.message}" : message.to_s
24
+ Prodbat.log(text, level: LEVELS.fetch(severity, "info")) unless text.strip.empty?
25
+ true
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prodbat
4
+ # Rack middleware: reports every unhandled exception with its cause, and every
5
+ # other 5xx answer. Rails gets it automatically; elsewhere, `use Prodbat::Middleware`.
6
+ class Middleware
7
+ def initialize(app)
8
+ @app = app
9
+ end
10
+
11
+ def call(env)
12
+ status, headers, body = @app.call(env)
13
+ Prodbat.capture_status(status, Prodbat.route_of(env)) if status.to_i >= 500 && !env["prodbat.reported"]
14
+ [status, headers, body]
15
+ rescue Exception => e # rubocop:disable Lint/RescueException -- reported, then raised again unchanged
16
+ env["prodbat.reported"] = true
17
+ Prodbat.capture_exception(e, route: Prodbat.route_of(env)) unless e.is_a?(SignalException) || e.is_a?(SystemExit)
18
+ raise
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prodbat
4
+ # Rails: the middleware goes just inside ShowExceptions, so it sees an exception
5
+ # with its backtrace before Rails turns it into a 500 page. Failed Active Job
6
+ # jobs are reported too.
7
+ class Railtie < ::Rails::Railtie
8
+ initializer "prodbat.middleware" do |app|
9
+ if defined?(::ActionDispatch::ShowExceptions)
10
+ app.middleware.insert_after ::ActionDispatch::ShowExceptions, Prodbat::Middleware
11
+ else
12
+ app.middleware.use Prodbat::Middleware
13
+ end
14
+ end
15
+
16
+ initializer "prodbat.active_job" do
17
+ ActiveSupport.on_load(:active_job) do
18
+ around_perform do |job, block|
19
+ block.call
20
+ rescue Exception => e # rubocop:disable Lint/RescueException -- reported, then raised again unchanged
21
+ Prodbat.capture_exception(e, route: "")
22
+ Prodbat.log("Job #{job.class.name} failed: #{e.class}", level: :error, job_id: job.job_id) rescue nil
23
+ raise
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prodbat"
4
+
5
+ module Prodbat
6
+ # Sidekiq: queues that back up or stop, and jobs that fail.
7
+ #
8
+ # # config/initializers/prodbat.rb
9
+ # require "prodbat/sidekiq"
10
+ # Prodbat::Sidekiq.watch
11
+ #
12
+ # Run it where Sidekiq's Redis is reachable; the web process is fine. It reports
13
+ # every queue's size and how long its oldest job has waited, once a minute, and
14
+ # Sidekiq's failed count across all queues. In the Sidekiq server it also
15
+ # reports each job's exception.
16
+ module Sidekiq
17
+ module_function
18
+
19
+ # Starts a background thread; returns it. `api` is for tests.
20
+ def watch(interval: 60, api: nil)
21
+ install_error_handler
22
+ last = nil
23
+ Thread.new do
24
+ Thread.current.name = "prodbat-sidekiq"
25
+ loop do
26
+ begin
27
+ last = report(api || default_api, last)
28
+ rescue StandardError
29
+ nil # Redis hiccup: try again next time
30
+ end
31
+ sleep interval
32
+ end
33
+ end
34
+ end
35
+
36
+ # One report. Returns the totals to compare with next time.
37
+ def report(api, last)
38
+ queues = api.queues.map do |queue|
39
+ { name: queue.name, waiting: queue.size, oldest_seconds: queue.latency.to_f.round(1), done: 0, failed: 0 }
40
+ end
41
+ totals = { processed: api.processed.to_i, failed: api.failed.to_i }
42
+ if last
43
+ # Sidekiq counts finished and failed jobs for all queues together.
44
+ queues << { name: "all queues", waiting: nil, oldest_seconds: nil,
45
+ done: [totals[:processed] - last[:processed], 0].max, failed: [totals[:failed] - last[:failed], 0].max }
46
+ end
47
+ Prodbat.report_queues("sidekiq", queues) unless queues.empty?
48
+ totals
49
+ end
50
+
51
+ def install_error_handler
52
+ return unless defined?(::Sidekiq) && ::Sidekiq.respond_to?(:configure_server)
53
+
54
+ ::Sidekiq.configure_server do |config|
55
+ config.error_handlers << proc do |error, context, *_|
56
+ job = context.is_a?(Hash) ? (context[:job] || context["job"] || {}) : {}
57
+ Prodbat.capture_exception(error, route: "")
58
+ Prodbat.log("Sidekiq job #{job['class']} failed: #{error.class}", level: :error, queue: job["queue"])
59
+ end
60
+ end
61
+ end
62
+
63
+ # Sidekiq's own API, in the shape `report` reads.
64
+ class DefaultApi
65
+ def queues
66
+ ::Sidekiq::Queue.all
67
+ end
68
+
69
+ def processed
70
+ stats.processed
71
+ end
72
+
73
+ def failed
74
+ stats.failed
75
+ end
76
+
77
+ private
78
+
79
+ def stats
80
+ ::Sidekiq::Stats.new
81
+ end
82
+ end
83
+
84
+ def default_api
85
+ require "sidekiq/api"
86
+ DefaultApi.new
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prodbat
4
+ VERSION = "0.0.1"
5
+ end
data/lib/prodbat.rb ADDED
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Prodbat for Ruby servers: errors with their cause, log lines, scheduled jobs,
4
+ # Sidekiq queues and Stripe events. No dependencies beyond the standard library.
5
+ #
6
+ # # Gemfile: gem "prodbat"
7
+ # # Rails: nothing more. The middleware and Active Job reporting are added by the gem.
8
+ # # Rack (Sinatra, Hanami, Roda): use Prodbat::Middleware (in config.ru)
9
+ # # Sidekiq: Prodbat::Sidekiq.watch (in an initializer)
10
+ #
11
+ # Prodbat.log("refund issued", order: 1042)
12
+ # Prodbat.ping("nightly-email", every: "24h") # at the end of a scheduled job
13
+ # Prodbat.stripe_event(event) # in the Stripe webhook, after the signature check
14
+ #
15
+ # Set PRODBAT_KEY and PRODBAT_URL in the environment. Nothing here ever raises or
16
+ # holds a request up: reports go out from a background thread and are dropped if
17
+ # Prodbat cannot be reached.
18
+
19
+ require "json"
20
+ require "net/http"
21
+ require "rbconfig"
22
+ require "uri"
23
+ require "prodbat/version"
24
+
25
+ module Prodbat
26
+ MAX_QUEUE = 200
27
+ MAX_LOGS = 2000
28
+ LIBRARY_DIRS = ([RbConfig::CONFIG["rubylibdir"], RbConfig::CONFIG["sitelibdir"]] +
29
+ (defined?(Gem) ? Gem.path : [])).compact.uniq.freeze
30
+
31
+ @config = { key: nil, url: nil }
32
+ @lock = Mutex.new
33
+ @queue = []
34
+ @logs = []
35
+ @thread = nil
36
+ @pid = nil
37
+ @busy = false
38
+ @runtime_sent = false
39
+
40
+ class << self
41
+ # Optional. Without it, PRODBAT_KEY and PRODBAT_URL are read from the environment.
42
+ def init(key: nil, url: nil)
43
+ @config = { key: key, url: url }
44
+ end
45
+
46
+ def settings
47
+ key = @config[:key] || ENV["PRODBAT_KEY"]
48
+ url = (@config[:url] || ENV["PRODBAT_URL"] || "").sub(%r{/+\z}, "")
49
+ [key, url.empty? ? nil : url]
50
+ end
51
+
52
+ # ---- sending ---------------------------------------------------------------
53
+
54
+ def deliver(method, path, payload)
55
+ key, url = settings
56
+ return unless key && url
57
+
58
+ uri = URI.parse(url + path)
59
+ http = Net::HTTP.new(uri.host, uri.port)
60
+ http.use_ssl = uri.scheme == "https"
61
+ http.open_timeout = http.read_timeout = http.write_timeout = 5
62
+ request = Net::HTTPGenericRequest.new(method, !payload.nil?, true, uri.request_uri)
63
+ request["Authorization"] = "Bearer #{key}"
64
+ request["Content-Type"] = "application/json"
65
+ request["User-Agent"] = "prodbat-ruby/#{VERSION}"
66
+ request.body = JSON.generate(payload) unless payload.nil?
67
+ http.request(request)
68
+ rescue StandardError
69
+ nil # reporting must never become the problem
70
+ end
71
+
72
+ def enqueue(method, path, payload = nil)
73
+ start
74
+ @lock.synchronize { @queue << [method, path, payload] if @queue.size < MAX_QUEUE }
75
+ rescue StandardError
76
+ nil
77
+ end
78
+
79
+ # Wait for everything queued to go out. Called when the process exits.
80
+ def flush(timeout = 2.0)
81
+ deadline = monotonic + timeout
82
+ sleep 0.02 while (pending? || @busy) && monotonic < deadline
83
+ end
84
+
85
+ # ---- errors ------------------------------------------------------------------
86
+
87
+ # Report an exception, with the deepest line of the app's own code it passed through.
88
+ def capture_exception(error, route: "")
89
+ trace = (["#{error.class}: #{error.message}"] + (error.backtrace || [])).join("\n")
90
+ enqueue("POST", "/api/errors", {
91
+ kind: error.class.name.to_s[0, 200],
92
+ message: error.message.to_s[0, 1000],
93
+ route: route.to_s[0, 300],
94
+ where: where(error)[0, 300],
95
+ trace: trace.length > 20_000 ? trace[-20_000..] : trace,
96
+ status: 500
97
+ })
98
+ rescue StandardError
99
+ nil
100
+ end
101
+
102
+ # Report a 5xx answer that did not come from an exception.
103
+ def capture_status(status, route = "")
104
+ return unless status.to_i >= 500
105
+
106
+ enqueue("POST", "/api/errors", { kind: "HTTP #{status.to_i}", status: status.to_i, route: route.to_s[0, 300] })
107
+ end
108
+
109
+ # "app/controllers/checkouts_controller.rb:88 in create"
110
+ def where(error)
111
+ frames = error.backtrace_locations || []
112
+ own = frames.reject { |f| f.path.nil? || LIBRARY_DIRS.any? { |dir| f.path.start_with?(dir) } || f.path.include?("/gems/") }
113
+ frame = own.first || frames.first
114
+ return "" unless frame
115
+
116
+ "#{frame.path.split('/').last(2).join('/')}:#{frame.lineno} in #{frame.label}"
117
+ end
118
+
119
+ # ---- logs --------------------------------------------------------------------
120
+
121
+ # Prodbat.log("refund issued", order: 1042) · Prodbat.log("card declined", level: :warn)
122
+ def log(message, level: :info, **fields)
123
+ @lock.synchronize do
124
+ if @logs.size < MAX_LOGS
125
+ @logs << { message: message.to_s[0, 4000], level: level.to_s.downcase, t: Time.now.to_f,
126
+ fields: fields.empty? ? nil : fields }
127
+ end
128
+ end
129
+ start
130
+ rescue StandardError
131
+ nil
132
+ end
133
+
134
+ # ---- jobs and payments -----------------------------------------------------------
135
+
136
+ # A scheduled job checks in, at the end, after the work has succeeded. every: "15m", "24h", "7d".
137
+ def ping(name, every: nil)
138
+ path = "/api/ping/#{URI.encode_www_form_component(name.to_s)}"
139
+ enqueue("POST", every ? "#{path}?every=#{URI.encode_www_form_component(every.to_s)}" : path)
140
+ end
141
+
142
+ # Forward a Stripe webhook event, after its signature has been checked.
143
+ def stripe_event(event)
144
+ payload = if event.is_a?(Hash) then event
145
+ elsif event.respond_to?(:to_hash) then event.to_hash
146
+ else JSON.parse(event.to_s)
147
+ end
148
+ enqueue("POST", "/api/stripe", payload)
149
+ rescue StandardError
150
+ nil
151
+ end
152
+
153
+ # One snapshot of some queues: [{ name:, waiting:, oldest_seconds:, done:, failed: }].
154
+ def report_queues(system, snapshots)
155
+ enqueue("POST", "/api/queues", { system: system.to_s, queues: snapshots })
156
+ end
157
+
158
+ # "POST /users/:id" on Rails 7.1+, otherwise the path.
159
+ def route_of(env)
160
+ pattern = env["action_dispatch.route_uri_pattern"].to_s.sub("(.:format)", "")
161
+ path = pattern.empty? ? env["PATH_INFO"].to_s : pattern
162
+ "#{env['REQUEST_METHOD']} #{path.empty? ? '/' : path}"
163
+ end
164
+
165
+ private
166
+
167
+ def monotonic
168
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
169
+ end
170
+
171
+ def pending?
172
+ @lock.synchronize { !@queue.empty? || !@logs.empty? }
173
+ end
174
+
175
+ # One worker thread per process. After a fork (Puma, Unicorn, Sidekiq) the
176
+ # child starts its own and does not inherit the parent's queue.
177
+ def start
178
+ first = false
179
+ @lock.synchronize do
180
+ if @pid != Process.pid
181
+ @queue = []
182
+ @logs = [] unless @pid.nil?
183
+ @thread = nil
184
+ first = @pid.nil? && !@runtime_sent
185
+ @runtime_sent = true
186
+ @pid = Process.pid
187
+ end
188
+ @thread = Thread.new { work } unless @thread&.alive?
189
+ end
190
+ @lock.synchronize { @queue.unshift(["PUT", "/api/runtime", { language: "ruby", version: RUBY_VERSION }]) } if first
191
+ end
192
+
193
+ def work
194
+ Thread.current.name = "prodbat"
195
+ last_logs = monotonic
196
+ loop do
197
+ item = @lock.synchronize { @queue.shift }
198
+ @busy = true
199
+ if item
200
+ deliver(*item)
201
+ elsif !@logs.empty? && (monotonic - last_logs >= 1.0 || @logs.size >= 500)
202
+ batch = @lock.synchronize { @logs.shift(500) }
203
+ deliver("POST", "/api/logs", { lines: batch })
204
+ last_logs = monotonic
205
+ end
206
+ @busy = false
207
+ sleep 0.05 unless item
208
+ end
209
+ rescue StandardError
210
+ @busy = false
211
+ retry
212
+ end
213
+ end
214
+ end
215
+
216
+ at_exit { Prodbat.flush }
217
+
218
+ require "prodbat/middleware"
219
+ require "prodbat/logger"
220
+ require "prodbat/railtie" if defined?(Rails::Railtie)
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: prodbat
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Prodbat
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-18 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Reports unhandled exceptions with their cause, other 5xx answers, log
14
+ lines, job check-ins, Sidekiq queue health and Stripe events to a Prodbat server.
15
+ Rails and Rack. No dependencies.
16
+ email:
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - LICENSE
22
+ - README.md
23
+ - lib/prodbat.rb
24
+ - lib/prodbat/logger.rb
25
+ - lib/prodbat/middleware.rb
26
+ - lib/prodbat/railtie.rb
27
+ - lib/prodbat/sidekiq.rb
28
+ - lib/prodbat/version.rb
29
+ homepage: https://github.com/prodbat/prodbat
30
+ licenses:
31
+ - MIT
32
+ metadata:
33
+ source_code_uri: https://github.com/prodbat/prodbat/tree/main/packages/ruby
34
+ rubygems_mfa_required: 'true'
35
+ post_install_message:
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '3.0'
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubygems_version: 3.3.7
51
+ signing_key:
52
+ specification_version: 4
53
+ summary: 'Monitoring for apps built with AI: server errors, logs, scheduled jobs and
54
+ Sidekiq queues, reported to Prodbat.'
55
+ test_files: []