railsgauge 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3dad91032ab59fc30181a29ef0bb8e18c7f97b084d0c04fe74e8162b43830250
4
+ data.tar.gz: cceeab3ff96661b284ff7c160e3e6d2f1db780f225bf2a4ec87d6be685a19ca6
5
+ SHA512:
6
+ metadata.gz: cd1378dd60b77188fa1825099a4aee1563c92851e395f0468bf5e6e521e732418b578978f206c8f276036f43bc12f25cddc77750135c79838f1080cc28e90834
7
+ data.tar.gz: 153240e5a1f1fb0ca7c250476dc8435624f420128a0054e92772fbf46c911bf59af2513e3031b92f120eb881f0abba63e4ff7ae2c18506b1ed3fe8e101796c25
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-12-05
9
+
10
+
11
+ ### Added
12
+
13
+ - scaffold shared Rails 8 Prometheus observability gem
14
+
15
+
16
+
17
+ ## [Unreleased]
18
+
19
+ ### Added
20
+
21
+ - Initial Rails 8 observability gem with shared `DirectFileStore` setup, bounded
22
+ `yabeda-rails` labels, Active Record SQL/pool/timeout collectors, unified
23
+ ActiveJob/GoodJob/Solid Queue collectors, Puma configuration helper, and
24
+ WEBrick-free job metrics listener.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ethos Link
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,125 @@
1
+ # Railsgauge
2
+
3
+ Low-boilerplate Prometheus metrics for Rails 8 applications running Puma behind
4
+ a reverse proxy (such as `kamal-proxy` or Thruster), with unified background job
5
+ telemetry for both **GoodJob** and **Solid Queue**.
6
+
7
+ ## What it provides
8
+
9
+ - **Boot-order-safe multi-worker store**: initializes `Prometheus::Client`'s
10
+ `DirectFileStore` before any metrics register — working identically whether
11
+ booted via `bin/rails server` or `bundle exec puma`, with master-only temp
12
+ directory cleanup on exit.
13
+ - **Bounded `yabeda-rails` labels**: keeps upstream `rails_*` controller metrics
14
+ while bounding client-controlled `format` and `method` labels and normalizing
15
+ `controller`.
16
+ - **Active Record diagnostics (`app_db_*`)**: uncached SQL query count and
17
+ duration, connection pool capacity/busy/waiting/freshness (in both single and
18
+ clustered Puma modes with a crash-resilient sampler), and unhandled
19
+ `ActiveRecord::ConnectionTimeoutError` counts.
20
+ - **Unified background job telemetry (`app_jobs_*`)**: ActiveJob execution
21
+ duration, queue wait latency, and completion counts, plus auto-detected queue
22
+ depth and worker gauges for **GoodJob** and **Solid Queue** under one shared
23
+ Prometheus schema.
24
+ - **One-line Puma & job listener setup**: `Railsgauge.configure_puma(self)` for
25
+ web containers and `Railsgauge.start_job_server!` (1-thread `Puma::Server`,
26
+ no WEBrick required) for dedicated job containers.
27
+ - **Zero overhead when disabled**: enabled automatically in `production` (or
28
+ explicitly via configuration); does not load Yabeda in development or test.
29
+
30
+ ## Installation
31
+
32
+ Add `railsgauge` to your application's `Gemfile`:
33
+
34
+ ```ruby
35
+ gem "railsgauge"
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ### 1. Configure queues (optional)
41
+
42
+ If your app only uses the `default` queue, no initializer is required.
43
+ Otherwise, create `config/initializers/railsgauge.rb`:
44
+
45
+ ```ruby
46
+ # frozen_string_literal: true
47
+
48
+ Railsgauge.configure do |config|
49
+ config.queues = %w[default maintenance insights]
50
+ end
51
+ ```
52
+
53
+ `job_backend` is auto-detected (`:good_job` or `:solid_queue`), and DB-wide
54
+ queue depth gauges are collected on web processes (`ENV["SERVICE"] != "job"`) by
55
+ default so dedicated job containers do not duplicate database queries.
56
+
57
+ ### 2. Wire Puma (`config/puma.rb`)
58
+
59
+ ```ruby
60
+ Railsgauge.configure_puma(self)
61
+ ```
62
+
63
+ In production, this binds the private `/metrics` endpoint to `0.0.0.0:9394`
64
+ (never exposed publicly unless you map the port). Outside production, it binds
65
+ to `127.0.0.1:9394` when explicitly enabled.
66
+
67
+ ### 3. Dedicated job container (`bin/jobs`, optional)
68
+
69
+ ```ruby
70
+ Railsgauge.start_job_server!
71
+ ```
72
+
73
+ ## Exported metrics
74
+
75
+ | Group | Metrics |
76
+ | --- | --- |
77
+ | `rails_*` | `requests_total`, `request_duration_seconds`, `view_runtime_seconds`, `db_runtime_seconds` (bounded `format`, `method`) |
78
+ | `puma_*` | `backlog`, `running`, `busy_threads`, `pool_capacity`, `max_threads`, `requests_count`, `workers`, `booted_workers`, `old_workers` |
79
+ | `app_db_*` | `queries_total`, `query_duration_seconds`, `pool_size`, `pool_busy`, `pool_waiting`, `pool_observed_at_seconds`, `connection_timeouts_total` |
80
+ | `app_jobs_*` | `execution_duration_seconds`, `queue_wait_seconds`, `executed_total`, `ready`, `oldest_ready_age_seconds`, `running`, `failed`, `scheduled`, `blocked` (Solid Queue), `paused`, `workers` |
81
+
82
+ Edge HTTP RED metrics (`requests`, `errors`, `duration`) are intentionally left
83
+ to your reverse proxy (`kamal-proxy`, nginx, Caddy, Envoy) instead of adding a
84
+ redundant Rack middleware.
85
+
86
+ ## Configuration options
87
+
88
+ | Option | Default | Description |
89
+ | --- | --- | --- |
90
+ | `enabled` | `Rails.env.production?` | Boolean or callable enabling instrumentation |
91
+ | `port` | `9394` | TCP port for the private `/metrics` server |
92
+ | `bind` | `"0.0.0.0"` in production, `"127.0.0.1"` otherwise | Bind host for `/metrics` |
93
+ | `queues` | `["default"]` | Allowlisted queue names for `app_jobs_*` |
94
+ | `job_backend` | `:auto` | `:auto`, `:good_job`, `:solid_queue`, or `:none` |
95
+ | `collect_queue_gauges` | `ENV["SERVICE"] != "job"` | Boolean or callable controlling DB-wide queue gauges |
96
+ | `pool_sample_interval` | `15` | Seconds between clustered worker DB pool samples |
97
+ | `allowed_formats` | `%w[html json xml text js turbo_stream */*]` | Bounded values for `rails_*` `format` label |
98
+ | `allowed_methods` | `%w[get head post put patch delete options trace connect]` | Bounded values for `rails_*` `method` label |
99
+
100
+ ## Development
101
+
102
+ ```sh
103
+ bundle install
104
+ bundle exec rake tools:install
105
+ bundle exec rake verify
106
+ ```
107
+
108
+ Shared development tooling and release automation are provided by
109
+ [ethos-gemkit](https://github.com/ethos-link/ethos-gemkit).
110
+
111
+ ## License
112
+
113
+ MIT. See [LICENSE.txt](LICENSE.txt).
114
+
115
+ ## About Ethos Link
116
+
117
+ [Ethos Link](https://www.ethos-link.com) is a software company founded by
118
+ [Paulo Fidalgo](https://www.fidalgo.pt). This gem is part of the open-source
119
+ tooling we publish alongside our business products:
120
+
121
+ - [Reviato](https://www.reviato.com): collect private customer feedback and analyse public reviews.
122
+ - [Nuntio](https://www.nuntiohq.com): prepare, review and schedule social posts.
123
+ - [EthosPlaces](https://www.ethos.place): find places, opening hours and contact details.
124
+
125
+ Explore our [open-source projects](https://www.ethos-link.com/opensource).
data/UPGRADE.md ADDED
@@ -0,0 +1,33 @@
1
+ # Upgrading Railsgauge
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release.
6
+
7
+ ### Migrating from per-app `Observability*` boilerplate
8
+
9
+ 1. Replace `yabeda-rails`, `yabeda-prometheus`, and `yabeda-puma-plugin` in
10
+ `Gemfile` with `gem "railsgauge"`.
11
+ 2. Remove `config/observability.rb`, `config/puma-observability.rb`,
12
+ `config/initializers/observability*.rb`, `lib/observability_*.rb`, and the
13
+ manual `config/application.rb` `Observability` requires/middleware.
14
+ 3. Add `config/initializers/railsgauge.rb` if your app uses custom queue names:
15
+
16
+ ```ruby
17
+ Railsgauge.configure do |config|
18
+ config.queues = %w[default maintenance]
19
+ end
20
+ ```
21
+
22
+ 4. In `config/puma.rb`, replace the `instance_eval` block with:
23
+
24
+ ```ruby
25
+ Railsgauge.configure_puma(self)
26
+ ```
27
+
28
+ 5. In `bin/jobs` (for dedicated job containers), replace the metrics server call
29
+ with:
30
+
31
+ ```ruby
32
+ Railsgauge.start_job_server!
33
+ ```
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/notifications"
4
+
5
+ module Railsgauge
6
+ module Collectors
7
+ module ActiveJob
8
+ DURATION_BUCKETS = [0.01, 0.1, 0.5, 1, 5, 15, 60, 300, 1800, 3600].freeze
9
+
10
+ class << self
11
+ def install!
12
+ return if @installed
13
+
14
+ @subscriptions = []
15
+
16
+ Yabeda.configure do
17
+ group :app_jobs do
18
+ histogram :execution_duration, unit: :seconds, tags: %i[queue backend], buckets: DURATION_BUCKETS, comment: "ActiveJob execution duration"
19
+ histogram :queue_wait, unit: :seconds, tags: %i[queue backend], buckets: DURATION_BUCKETS, comment: "Delay after the job became eligible"
20
+ counter :executed_total, tags: %i[queue backend result], comment: "Completed ActiveJob attempts"
21
+ end
22
+ end
23
+
24
+ @subscriptions << ActiveSupport::Notifications.subscribe("perform.active_job") do |*args|
25
+ record_execution(ActiveSupport::Notifications::Event.new(*args))
26
+ end
27
+
28
+ @subscriptions << ActiveSupport::Notifications.subscribe("perform_start.active_job") do |*args|
29
+ record_queue_wait(ActiveSupport::Notifications::Event.new(*args))
30
+ end
31
+
32
+ @installed = true
33
+ end
34
+
35
+ def uninstall!
36
+ Array(@subscriptions).each { |subscriber| ActiveSupport::Notifications.unsubscribe(subscriber) }
37
+ @subscriptions = []
38
+ @installed = false
39
+ end
40
+
41
+ private
42
+
43
+ def record_execution(event)
44
+ job = event.payload[:job]
45
+ return unless job
46
+
47
+ config = Railsgauge.configuration
48
+ queue = job.queue_name.to_s
49
+ return unless config.queues.include?(queue)
50
+
51
+ backend = backend_label(config)
52
+ labels = {queue: queue, backend: backend}
53
+ Yabeda.app_jobs.execution_duration.measure(labels, event.duration / 1000.0)
54
+ Yabeda.app_jobs.executed_total.increment(labels.merge(result: event.payload[:exception] ? "error" : "success"))
55
+ end
56
+
57
+ def record_queue_wait(event)
58
+ job = event.payload[:job]
59
+ return unless job&.respond_to?(:enqueued_at) && job.enqueued_at
60
+
61
+ config = Railsgauge.configuration
62
+ queue = job.queue_name.to_s
63
+ return unless config.queues.include?(queue)
64
+
65
+ scheduled_at = job.respond_to?(:scheduled_at) ? job.scheduled_at : nil
66
+ eligible = [job.enqueued_at, scheduled_at].compact.max
67
+ age = current_time - eligible
68
+ return if age.negative?
69
+
70
+ Yabeda.app_jobs.queue_wait.measure({queue: queue, backend: backend_label(config)}, age)
71
+ end
72
+
73
+ def backend_label(config)
74
+ backend = config.resolved_job_backend
75
+ (backend == :none) ? "active_job" : backend.to_s
76
+ end
77
+
78
+ def current_time
79
+ Time.respond_to?(:current) ? Time.current : Time.now.utc
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/notifications"
4
+
5
+ module Railsgauge
6
+ module Collectors
7
+ module Database
8
+ QUERY_BUCKETS = [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 5, 30].freeze
9
+ TIMEOUT_EVENTS = {
10
+ "process_action.action_controller" => "request",
11
+ "perform.active_job" => "job"
12
+ }.freeze
13
+
14
+ class << self
15
+ def install!
16
+ return if @installed
17
+
18
+ @subscriptions = []
19
+
20
+ Yabeda.configure do
21
+ group :app_db do
22
+ counter :queries_total, tags: %i[config], comment: "Uncached SQL calls"
23
+ histogram :query_duration, tags: %i[config], unit: :seconds, buckets: QUERY_BUCKETS, comment: "Uncached SQL call duration"
24
+ gauge :pool_size, tags: %i[config worker], aggregation: :most_recent, comment: "Configured database pool capacity"
25
+ gauge :pool_busy, tags: %i[config worker], aggregation: :most_recent, comment: "Connections checked out"
26
+ gauge :pool_waiting, tags: %i[config worker], aggregation: :most_recent, comment: "Threads waiting for a connection"
27
+ gauge :pool_observed_at, unit: :seconds, tags: %i[config worker], aggregation: :most_recent, comment: "Unix time when pool was sampled"
28
+ counter :connection_timeouts_total, tags: %i[context], comment: "Unhandled connection timeout exceptions observed by Rails"
29
+ end
30
+
31
+ collect do
32
+ Railsgauge::Pools.sample("single") unless Railsgauge.clustered?
33
+ end
34
+ end
35
+
36
+ @subscriptions << ActiveSupport::Notifications.subscribe("sql.active_record") do |*args|
37
+ record_sql(ActiveSupport::Notifications::Event.new(*args))
38
+ end
39
+
40
+ TIMEOUT_EVENTS.each do |event_name, context|
41
+ @subscriptions << ActiveSupport::Notifications.subscribe(event_name) do |*args|
42
+ record_timeout(ActiveSupport::Notifications::Event.new(*args), context)
43
+ end
44
+ end
45
+
46
+ @installed = true
47
+ end
48
+
49
+ def uninstall!
50
+ Array(@subscriptions).each { |subscriber| ActiveSupport::Notifications.unsubscribe(subscriber) }
51
+ @subscriptions = []
52
+ @installed = false
53
+ end
54
+
55
+ private
56
+
57
+ def record_sql(event)
58
+ return if event.payload[:cached] || event.payload[:name] == "SCHEMA"
59
+
60
+ pool = event.payload[:connection]&.pool
61
+ return unless pool.respond_to?(:db_config)
62
+
63
+ labels = {config: pool.db_config.name}
64
+ Yabeda.app_db.queries_total.increment(labels)
65
+ Yabeda.app_db.query_duration.measure(labels, event.duration / 1000.0)
66
+ end
67
+
68
+ def record_timeout(event, context)
69
+ return unless defined?(ActiveRecord::ConnectionTimeoutError)
70
+ return unless event.payload[:exception_object].is_a?(ActiveRecord::ConnectionTimeoutError)
71
+
72
+ Yabeda.app_db.connection_timeouts_total.increment({context: context})
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railsgauge
4
+ module Collectors
5
+ module GoodJob
6
+ class << self
7
+ def install!
8
+ return if @installed
9
+
10
+ Yabeda.configure do
11
+ group :app_jobs do
12
+ gauge :ready, tags: %i[queue backend], aggregation: :most_recent, comment: "Unclaimed eligible jobs"
13
+ gauge :oldest_ready_age, unit: :seconds, tags: %i[queue backend], aggregation: :most_recent, comment: "Age of oldest eligible job"
14
+ gauge :running, tags: %i[queue backend], aggregation: :most_recent, comment: "Jobs recorded as performing"
15
+ gauge :failed, tags: %i[queue backend], aggregation: :most_recent, comment: "Discarded jobs"
16
+ gauge :scheduled, tags: %i[queue backend], aggregation: :most_recent, comment: "Future scheduled or retry jobs"
17
+ gauge :paused, tags: %i[queue backend], aggregation: :most_recent, comment: "Due jobs excluded by GoodJob pause settings"
18
+ gauge :workers, tags: %i[backend], aggregation: :most_recent, comment: "Active GoodJob processes"
19
+ end
20
+
21
+ collect do
22
+ Railsgauge::Collectors::GoodJob.collect!
23
+ end
24
+ end
25
+
26
+ @installed = true
27
+ end
28
+
29
+ def collect!
30
+ with_executor do
31
+ queues = Railsgauge.configuration.queues
32
+ now = Time.respond_to?(:current) ? Time.current : Time.now.utc
33
+ jobs = ::GoodJob::Job.where(queue_name: queues)
34
+ due = jobs.queued.where(locked_by_id: nil)
35
+ eligible = due.exclude_paused
36
+ ready = eligible.group(:queue_name).count
37
+ oldest = eligible.group(:queue_name).minimum(:scheduled_at)
38
+ running = jobs.running.group(:queue_name).count
39
+ failed = jobs.discarded.group(:queue_name).count
40
+ scheduled = jobs.unfinished.where("scheduled_at > ?", now).group(:queue_name).count
41
+ paused = due.group(:queue_name).count
42
+ workers = ::GoodJob::Process.active.count
43
+
44
+ queues.each do |queue|
45
+ labels = {queue: queue, backend: "good_job"}
46
+ age = oldest[queue] ? [now - oldest[queue], 0].max : 0
47
+ Yabeda.app_jobs.ready.set(labels, ready.fetch(queue, 0))
48
+ Yabeda.app_jobs.oldest_ready_age.set(labels, age)
49
+ Yabeda.app_jobs.running.set(labels, running.fetch(queue, 0))
50
+ Yabeda.app_jobs.failed.set(labels, failed.fetch(queue, 0))
51
+ Yabeda.app_jobs.scheduled.set(labels, scheduled.fetch(queue, 0))
52
+ Yabeda.app_jobs.paused.set(labels, [paused.fetch(queue, 0) - ready.fetch(queue, 0), 0].max)
53
+ end
54
+ Yabeda.app_jobs.workers.set({backend: "good_job"}, workers)
55
+ end
56
+ end
57
+
58
+ def uninstall!
59
+ @installed = false
60
+ end
61
+
62
+ private
63
+
64
+ def with_executor(&block)
65
+ if defined?(Rails) && Rails.respond_to?(:application) && Rails.application&.respond_to?(:executor)
66
+ Rails.application.executor.wrap(&block)
67
+ else
68
+ yield
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railsgauge
4
+ module Collectors
5
+ module SolidQueue
6
+ class << self
7
+ def install!
8
+ return if @installed
9
+
10
+ Yabeda.configure do
11
+ group :app_jobs do
12
+ gauge :ready, tags: %i[queue backend], aggregation: :most_recent, comment: "Ready jobs in unpaused queues"
13
+ gauge :oldest_ready_age, unit: :seconds, tags: %i[queue backend], aggregation: :most_recent, comment: "Age of oldest ready execution"
14
+ gauge :running, tags: %i[queue backend], aggregation: :most_recent, comment: "Claimed jobs"
15
+ gauge :failed, tags: %i[queue backend], aggregation: :most_recent, comment: "Failed executions"
16
+ gauge :scheduled, tags: %i[queue backend], aggregation: :most_recent, comment: "Scheduled executions"
17
+ gauge :blocked, tags: %i[queue backend], aggregation: :most_recent, comment: "Concurrency-blocked executions"
18
+ gauge :paused, tags: %i[queue backend], aggregation: :most_recent, comment: "Ready jobs in paused queues"
19
+ gauge :workers, tags: %i[backend], aggregation: :most_recent, comment: "Solid Queue workers with a current heartbeat"
20
+ end
21
+
22
+ collect do
23
+ Railsgauge::Collectors::SolidQueue.collect!
24
+ end
25
+ end
26
+
27
+ @installed = true
28
+ end
29
+
30
+ def collect!
31
+ with_executor do
32
+ queues = Railsgauge.configuration.queues
33
+ now = Time.respond_to?(:current) ? Time.current : Time.now.utc
34
+ paused_queues = ::SolidQueue::Pause.where(queue_name: queues).pluck(:queue_name)
35
+ ready_scope = ::SolidQueue::ReadyExecution.where(queue_name: queues)
36
+ eligible = ready_scope.where.not(queue_name: paused_queues)
37
+ ready = eligible.group(:queue_name).count
38
+ oldest = eligible.group(:queue_name).minimum(:created_at)
39
+ running = ::SolidQueue::ClaimedExecution.joins(:job).where(solid_queue_jobs: {queue_name: queues}).group("solid_queue_jobs.queue_name").count
40
+ failed = ::SolidQueue::FailedExecution.joins(:job).where(solid_queue_jobs: {queue_name: queues}).group("solid_queue_jobs.queue_name").count
41
+ scheduled = ::SolidQueue::ScheduledExecution.where(queue_name: queues).group(:queue_name).count
42
+ blocked = ::SolidQueue::BlockedExecution.where(queue_name: queues).group(:queue_name).count
43
+ paused = ready_scope.where(queue_name: paused_queues).group(:queue_name).count
44
+ workers = ::SolidQueue::Process.where(kind: "Worker").where("last_heartbeat_at > ?", ::SolidQueue.process_alive_threshold.ago).count
45
+
46
+ queues.each do |queue|
47
+ labels = {queue: queue, backend: "solid_queue"}
48
+ age = oldest[queue] ? [now - oldest[queue], 0].max : 0
49
+ Yabeda.app_jobs.ready.set(labels, ready.fetch(queue, 0))
50
+ Yabeda.app_jobs.oldest_ready_age.set(labels, age)
51
+ Yabeda.app_jobs.running.set(labels, running.fetch(queue, 0))
52
+ Yabeda.app_jobs.failed.set(labels, failed.fetch(queue, 0))
53
+ Yabeda.app_jobs.scheduled.set(labels, scheduled.fetch(queue, 0))
54
+ Yabeda.app_jobs.blocked.set(labels, blocked.fetch(queue, 0))
55
+ Yabeda.app_jobs.paused.set(labels, paused.fetch(queue, 0))
56
+ end
57
+ Yabeda.app_jobs.workers.set({backend: "solid_queue"}, workers)
58
+ end
59
+ end
60
+
61
+ def uninstall!
62
+ @installed = false
63
+ end
64
+
65
+ private
66
+
67
+ def with_executor(&block)
68
+ if defined?(Rails) && Rails.respond_to?(:application) && Rails.application&.respond_to?(:executor)
69
+ Rails.application.executor.wrap(&block)
70
+ else
71
+ yield
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railsgauge
4
+ class Configuration
5
+ DEFAULT_PORT = 9394
6
+ DEFAULT_POOL_SAMPLE_INTERVAL = 15
7
+ DEFAULT_FORMATS = %w[html json xml text js turbo_stream */*].freeze
8
+ DEFAULT_METHODS = %w[get head post put patch delete options trace connect].freeze
9
+ VALID_BACKENDS = %i[auto good_job solid_queue none].freeze
10
+
11
+ attr_accessor :enabled, :bind, :collect_queue_gauges, :store_directory,
12
+ :install_rails_metrics, :allowed_formats, :allowed_methods
13
+ attr_reader :port, :queues, :job_backend, :pool_sample_interval
14
+
15
+ def initialize
16
+ @enabled = nil
17
+ @port = DEFAULT_PORT
18
+ @bind = nil
19
+ @queues = ["default"].freeze
20
+ @job_backend = :auto
21
+ @collect_queue_gauges = nil
22
+ @pool_sample_interval = DEFAULT_POOL_SAMPLE_INTERVAL
23
+ @store_directory = nil
24
+ @install_rails_metrics = nil
25
+ @allowed_formats = DEFAULT_FORMATS.dup
26
+ @allowed_methods = DEFAULT_METHODS.dup
27
+ end
28
+
29
+ def port=(value)
30
+ parsed = Integer(value)
31
+ raise ArgumentError, "port must be between 1 and 65535" unless parsed.between?(1, 65535)
32
+
33
+ @port = parsed
34
+ end
35
+
36
+ def queues=(values)
37
+ normalized = Array(values).map(&:to_s).reject(&:empty?).uniq
38
+ raise ArgumentError, "queues must contain at least one queue name" if normalized.empty?
39
+
40
+ @queues = normalized.freeze
41
+ end
42
+
43
+ def job_backend=(value)
44
+ backend = value.to_sym
45
+ raise ArgumentError, "unsupported job_backend: #{value.inspect}" unless VALID_BACKENDS.include?(backend)
46
+
47
+ @job_backend = backend
48
+ end
49
+
50
+ def pool_sample_interval=(value)
51
+ interval = Float(value)
52
+ raise ArgumentError, "pool_sample_interval must be positive" unless interval.positive?
53
+
54
+ @pool_sample_interval = interval
55
+ end
56
+
57
+ def enabled?
58
+ return @enabled.call == true if @enabled.respond_to?(:call)
59
+ return @enabled == true unless @enabled.nil?
60
+
61
+ production?
62
+ end
63
+
64
+ def bind_address
65
+ return @bind.to_s unless @bind.nil? || @bind.to_s.empty?
66
+
67
+ production? ? "0.0.0.0" : "127.0.0.1"
68
+ end
69
+
70
+ def resolved_job_backend
71
+ return @job_backend unless @job_backend == :auto
72
+
73
+ if Object.const_defined?("GoodJob::Job")
74
+ :good_job
75
+ elsif Object.const_defined?("SolidQueue::ReadyExecution")
76
+ :solid_queue
77
+ else
78
+ :none
79
+ end
80
+ end
81
+
82
+ def collect_queue_gauges?
83
+ return @collect_queue_gauges.call == true if @collect_queue_gauges.respond_to?(:call)
84
+ return @collect_queue_gauges == true unless @collect_queue_gauges.nil?
85
+
86
+ ENV["SERVICE"] != "job"
87
+ end
88
+
89
+ def production?
90
+ defined?(Rails) && Rails.respond_to?(:env) && Rails.env&.production? == true
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Railsgauge
4
+ module Pools
5
+ class << self
6
+ def sample(worker)
7
+ return unless defined?(ActiveRecord::Base)
8
+
9
+ pools = ActiveRecord::Base.connection_handler.connection_pool_list(:all).group_by { |pool| pool.db_config.name }
10
+ observed_at = Time.now.to_f
11
+ pools.each do |config_name, connections|
12
+ stats = connections.map(&:stat)
13
+ labels = {config: config_name, worker: worker.to_s}
14
+ Yabeda.app_db.pool_size.set(labels, stats.sum { |stat| stat.fetch(:size) })
15
+ Yabeda.app_db.pool_busy.set(labels, stats.sum { |stat| stat.fetch(:busy) })
16
+ Yabeda.app_db.pool_waiting.set(labels, stats.sum { |stat| stat.fetch(:waiting) })
17
+ Yabeda.app_db.pool_observed_at.set(labels, observed_at)
18
+ end
19
+ end
20
+
21
+ def start(worker, interval: Railsgauge.configuration.pool_sample_interval)
22
+ stop
23
+ @stop_queue = Thread::Queue.new
24
+ @thread = Thread.new do
25
+ Thread.current.name = "railsgauge-pools-#{worker}"
26
+ loop do
27
+ sample_safely(worker)
28
+ break if @stop_queue.pop(timeout: interval) == :stop
29
+ end
30
+ end
31
+ end
32
+
33
+ def stop
34
+ return unless @thread
35
+
36
+ @stop_queue&.push(:stop)
37
+ @thread.join(2)
38
+ @thread.kill if @thread.alive?
39
+ ensure
40
+ @thread = nil
41
+ @stop_queue = nil
42
+ end
43
+
44
+ private
45
+
46
+ def sample_safely(worker)
47
+ if defined?(Rails) && Rails.respond_to?(:application) && Rails.application&.respond_to?(:executor)
48
+ Rails.application.executor.wrap { sample(worker) }
49
+ else
50
+ sample(worker)
51
+ end
52
+ rescue => error
53
+ if defined?(Rails) && Rails.respond_to?(:error) && Rails.error
54
+ Rails.error.report(error, handled: true, context: {component: "railsgauge"})
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end