upstate-rails 0.1.0 → 0.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4783aff7c6640fdf83df97d8c490f32dfa6269dd242628a8d8a177986b229116
4
- data.tar.gz: b2684f1698caa10a91248c4950e30ccd38a33ec6002b8bcda4b68104477b7a8f
3
+ metadata.gz: 9daa36dc978c28d7dc1bba397cc07566184c20dc682ee8c00b28e8a3836858d3
4
+ data.tar.gz: 047d1db6c3e0b8b586abed9c69fda37a137e7babcca644df64e8eac42d20c273
5
5
  SHA512:
6
- metadata.gz: b1b8c3b7dbc87385211de8fd8736aa96d145ee13c7dc937ac7c219f36fbea7a7e38bdec69e5dede781d46b9a89d0ada46d5de3f7a7a87a0a0fae4a32ed2cd3b7
7
- data.tar.gz: 8c371fa288593ebae53746217b318bf393fd5c0144d6a558982dbad760ee793b82f0686924b6ea4a088cb50f7790e0bbd65ab5cabf3858c554dab01920c48bb5
6
+ metadata.gz: 6b863838c88ded9db1364173f7d778de273c7dc56fe8d536f14ff5de33da35a1788bf61d600cd9c26d9ede9864a920db3ee0d2610cabf1ecc0a09e0c134987cf
7
+ data.tar.gz: f475fd351d17f8eaba474f84bc59fc9c2aab10a54b07493bee2011815cba12dc0266ac7b606bdf86ace9fde16787beebd2f0fdc6ae6332bbbcd1d92d8a631b92
data/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ - Solid Queue: report the app's recurring jobs in a new `recurring` section so Upstate can
6
+ propose a check-in for each one:
7
+ - `tasks`: `{key, class_name, schedule, interval_seconds}` for each entry of
8
+ `config/recurring.yml` (or `SOLID_QUEUE_RECURRING_SCHEDULE`) under the current Rails
9
+ environment key. `interval_seconds` is the longest gap between the next runs, from Fugit
10
+ when it is loaded. Job arguments, `command:` and queue names are never read.
11
+ - `runs`: for those jobs, the last 24 hours (newest 10 finished runs per job, plus every run still going at any age; running jobs are read independently of the row limits; finished and failed runs are the newest by end time) as `{key, run_id,
12
+ started_at, finished_at, result}` with `result` of `success`, `fail` or `running`,
13
+ read from Solid Queue's own tables so any container reports them. `run_id` is
14
+ `sq-<job id>`. Solid Queue keeps no start time once a job finishes, so `started_at` is
15
+ only present while a run is going.
16
+ - The section is left out when there is no readable schedule or another job adapter is
17
+ in use (sidekiq-cron and GoodJob cron are not read yet; `Upstate::Rails::Recurring::SOURCES`
18
+ is the seam). The schema stays 1 and the section is additive: servers that predate it
19
+ ignore it, and this gem keeps working against them.
20
+
21
+ ## 0.2.0
22
+
23
+ - Report database health in the `database` section, for the primary connection on
24
+ PostgreSQL:
25
+ - `size_bytes`: `pg_database_size(current_database())` (this database only, not WAL or
26
+ other databases on the server);
27
+ - `connections`: `{in_use, max}` (client connections and `max_connections`);
28
+ - `oldest_transaction_age_seconds` (0 when none is open) and `idle_in_transaction`, for
29
+ sessions the app's role can see;
30
+ - `xid_age`: `age(datfrozenxid)` (transaction ID wraparound headroom used);
31
+ - `replication`: replica replay lag, or the replica count and largest `replay_lag` on a
32
+ primary where visible; left out otherwise;
33
+ - `largest_tables`: the 5 largest tables with total size and estimated live/dead rows.
34
+ Table names and numbers only, never row data.
35
+ - One transaction with a 250ms `SET LOCAL statement_timeout` and a savepoint per query.
36
+ Anything that fails, or another adapter, is left out; it never changes `database.ok` or
37
+ the status. The schema stays 1 (all fields are additive); Upstate servers that predate
38
+ them ignore them.
39
+
3
40
  ## 0.1.0
4
41
 
5
42
  - First release: `GET /upstate/health` (schema 1) with boot facts, migrations, DB pool, Puma,
data/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # upstate-rails
2
2
 
3
- Rails app health for [Upstate](https://upstate.cloud): boot facts, migrations, Puma, jobs, and the slowest actions. Counts only.
3
+ Rails app health for [Upstate](https://upstate.cloud): boot facts, migrations, database health, Puma, jobs, and the slowest actions. Counts only.
4
4
 
5
5
  The gem adds one endpoint, `GET /upstate/health`. Upstate's host observer reads it from inside your server, over your private Docker network, every minute. Nothing else is installed, and nothing is sent anywhere by the gem itself.
6
6
 
@@ -8,15 +8,17 @@ The gem adds one endpoint, `GET /upstate/health`. Upstate's host observer reads
8
8
 
9
9
  - App version (`APP_VERSION`, else `KAMAL_VERSION`, else `unknown`), Rails and Ruby versions, whether YJIT is on, when the process booted.
10
10
  - Whether the database answers, and whether migrations are pending.
11
+ - Database health for the primary connection (PostgreSQL only): its size in bytes (`pg_database_size`, this database only, not WAL or other databases), connections in use and `max_connections`, the oldest open transaction's age and the number of sessions idle in transaction (as visible to the app's role), `age(datfrozenxid)` (wraparound headroom), replication lag where this connection can see it, and the 5 largest tables with their total size and estimated live and dead rows. Table names are sent; row data never is. One transaction with a 250ms statement timeout and a savepoint per query; anything that fails, or MySQL/SQLite, is left out.
11
12
  - Active Record pool size, busy and waiting connections.
12
13
  - Puma workers, threads, backlog and spare capacity.
13
14
  - Job numbers for Solid Queue, Sidekiq or GoodJob: queue depth, oldest queued age, worker count, jobs processed and failed in the last 5 minutes, and when something last ran.
15
+ - Solid Queue only: your recurring jobs from `config/recurring.yml` (or `SOLID_QUEUE_RECURRING_SCHEDULE`), under the current Rails environment. For each, the key, the class name and the schedule text, and for its recent runs (last 24 hours, newest 10 finished runs per job, plus any still running) an id, when it started or finished and whether it succeeded, failed or is running. Upstate turns these into check-in suggestions; nothing is monitored until you accept. A job's arguments and `command:` are never read.
14
16
  - Whether your cache (Solid Cache or Redis) answers.
15
17
  - For the last 15 minutes, the 10 slowest `Controller#action` names per minute, with request count, error count, a 12-bucket timing histogram, and total database time.
16
18
 
17
19
  ## What is never sent
18
20
 
19
- No params, URLs or paths, SQL, IP addresses, user agents, headers, cookies, job arguments, exception classes or messages, logs, or traces. An error is only a count (a 5xx response or an unhandled exception). Job queue names and job class names are not read either.
21
+ No params, URLs or paths, SQL, row data, IP addresses, user agents, headers, cookies, job arguments, exception classes or messages, logs, or traces. An error is only a count (a 5xx response or an unhandled exception). Queue names are not read. Job class names are read only for the recurring jobs listed in `config/recurring.yml`, and never for other jobs.
20
22
 
21
23
  ## Install
22
24
 
@@ -33,6 +33,8 @@ module Upstate
33
33
  actions: section { actions }
34
34
  }
35
35
  body[:solid_queue] = solid_queue if solid_queue
36
+ recurring = section { Recurring.call(now: @now) }
37
+ body[:recurring] = recurring if recurring
36
38
 
37
39
  status = database && database[:ok] == false ? 503 : 200
38
40
  [status, body]
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require "erb"
5
+ require "pathname"
6
+
7
+ module Upstate
8
+ module Rails
9
+ module Recurring
10
+ # Solid Queue: tasks come from config/recurring.yml (or SOLID_QUEUE_RECURRING_SCHEDULE),
11
+ # under the current Rails environment key when the file has one, the same way Solid Queue
12
+ # reads it. Runs come from solid_queue_recurring_executions and the job rows they point
13
+ # at, so they are visible from any container, not only the worker's.
14
+ module SolidQueueSource
15
+ WINDOW = 24 * 3600
16
+ RUNS_PER_TASK = 10
17
+ MAX_RUNNING = 100
18
+ MAX_TASKS = 100
19
+
20
+ module_function
21
+
22
+ def call(now: Time.now)
23
+ list = tasks
24
+ return {adapter: "solid_queue", tasks: nil, runs: []} if list.nil?
25
+
26
+ {adapter: "solid_queue", tasks: list, runs: runs(list.map { |t| t[:key] }, now)}
27
+ end
28
+
29
+ def schedule_path
30
+ configured = ENV["SOLID_QUEUE_RECURRING_SCHEDULE"].to_s.strip
31
+ root = ::Rails.root || Pathname(Dir.pwd)
32
+ root.join(configured.empty? ? "config/recurring.yml" : configured)
33
+ end
34
+
35
+ # => [{key:, class_name:, schedule:, interval_seconds:}] or nil when unreadable.
36
+ def tasks(path: schedule_path, env: ::Rails.env.to_s)
37
+ return nil unless File.file?(path)
38
+
39
+ data = YAML.safe_load(ERB.new(File.read(path)).result, aliases: true, permitted_classes: [Symbol])
40
+ return nil unless data.is_a?(Hash)
41
+
42
+ scoped = data[env].is_a?(Hash) ? data[env] : nil
43
+ entries = scoped || data
44
+ list = entries.filter_map { |key, entry| task(key, entry) }.first(MAX_TASKS)
45
+ # A file with only other environments' sections is not a schedule for this one.
46
+ return nil if scoped.nil? && list.empty? && !entries.empty?
47
+
48
+ list
49
+ rescue StandardError, Psych::Exception, ScriptError
50
+ nil
51
+ end
52
+
53
+ # Only key, class and schedule are read from an entry; args and command never are.
54
+ def task(key, entry)
55
+ return unless entry.is_a?(Hash)
56
+
57
+ schedule = entry["schedule"]
58
+ return unless schedule.is_a?(String) && !schedule.strip.empty?
59
+
60
+ class_name = entry["class"]
61
+ {
62
+ key: key.to_s,
63
+ class_name: class_name.is_a?(String) ? class_name : nil,
64
+ schedule: schedule.strip,
65
+ interval_seconds: interval_seconds(schedule.strip)
66
+ }
67
+ end
68
+
69
+ # Longest gap over the next runs, via Fugit (a Solid Queue dependency) when present.
70
+ def interval_seconds(schedule, from: Time.now)
71
+ return unless defined?(::Fugit)
72
+
73
+ parsed = ::Fugit.parse(schedule)
74
+ if parsed.respond_to?(:next_time)
75
+ times = [from]
76
+ 12.times { times << parsed.next_time(times.last).to_t }
77
+ times.each_cons(2).map { |a, b| (b - a).to_i }.max
78
+ elsif parsed.respond_to?(:to_sec)
79
+ parsed.to_sec.to_i
80
+ end
81
+ rescue StandardError
82
+ nil
83
+ end
84
+
85
+ # Recent runs of the given recurring tasks. Per task, three independent bounded reads,
86
+ # none of which depends on the order executions were enqueued in:
87
+ # * runs still going: every claimed execution of the task (bounded by what is
88
+ # actually executing, capped at MAX_RUNNING), at any age;
89
+ # * finished jobs, newest RUNS_PER_TASK by finish time inside WINDOW;
90
+ # * failed jobs, newest RUNS_PER_TASK by failure time inside WINDOW.
91
+ # The finished and failed reads are merged and cut to RUNS_PER_TASK by end time.
92
+ def runs(keys, now)
93
+ return [] if keys.empty? || !defined?(::SolidQueue::RecurringExecution)
94
+
95
+ since = now - WINDOW
96
+ keys.flat_map { |key| task_runs(key, since) }
97
+ rescue StandardError
98
+ []
99
+ end
100
+
101
+ def task_runs(key, since)
102
+ job_ids = ::SolidQueue::RecurringExecution.where(task_key: key).select(:job_id)
103
+
104
+ running = ::SolidQueue::ClaimedExecution.where(job_id: job_ids)
105
+ .order(created_at: :desc).limit(MAX_RUNNING).pluck(:job_id, :created_at)
106
+ done = ::SolidQueue::Job.where(id: job_ids).where(finished_at: since..)
107
+ .order(finished_at: :desc).limit(RUNS_PER_TASK).pluck(:id, :finished_at)
108
+ failed = ::SolidQueue::FailedExecution.where(job_id: job_ids).where(created_at: since..)
109
+ .order(created_at: :desc).limit(RUNS_PER_TASK).pluck(:job_id, :created_at)
110
+
111
+ ended = failed.map { |id, at| run(key, id, nil, at, nil) } +
112
+ done.map { |id, at| run(key, id, at, nil, nil) }
113
+ ended = ended.compact.uniq { |r| r[:run_id] }.sort_by { |r| r[:finished_at] }.reverse
114
+ going = running.filter_map { |id, at| run(key, id, nil, nil, at) }
115
+
116
+ going + ended.reject { |r| going.any? { |g| g[:run_id] == r[:run_id] } }.first(RUNS_PER_TASK)
117
+ end
118
+
119
+ # failed -> fail (at the failure), finished -> success, claimed -> running (since the
120
+ # claim). A job still waiting to be claimed has not started and is not reported.
121
+ # Solid Queue keeps no start time once a job finishes, so only a running job has one.
122
+ def run(key, job_id, finished_at, failed_at, claimed_at)
123
+ base = {key: key, run_id: "sq-#{job_id}", started_at: nil, finished_at: nil}
124
+ if failed_at
125
+ base.merge(finished_at: iso(failed_at), result: "fail")
126
+ elsif finished_at
127
+ base.merge(finished_at: iso(finished_at), result: "success")
128
+ elsif claimed_at
129
+ base.merge(started_at: iso(claimed_at), result: "running")
130
+ end
131
+ end
132
+
133
+ def iso(time)
134
+ time.utc.iso8601
135
+ end
136
+ end
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Upstate
4
+ module Rails
5
+ # The `recurring` section: the app's own recurring-job schedule and recent runs of those
6
+ # jobs, so Upstate can propose a check-in for each one. Sent: job key, class name,
7
+ # schedule text and, per run, an id, start, end and result. Never job arguments, never a
8
+ # `command:` string, never queue names or error text.
9
+ #
10
+ # Each source answers `call(now:)` with
11
+ # {adapter: "...", tasks: [{key:, class_name:, schedule:, interval_seconds:}] | nil,
12
+ # runs: [{key:, run_id:, started_at:, finished_at:, result:}]}
13
+ # `tasks: nil` means the schedule could not be read (the server then changes nothing).
14
+ # To add sidekiq-cron or GoodJob cron, add a source here that returns the same shape and
15
+ # register it under the adapter name; the server allowlist gains the adapter name too.
16
+ module Recurring
17
+ SOURCES = {"solid_queue" => :SolidQueueSource}.freeze
18
+
19
+ module_function
20
+
21
+ # => section hash, or nil when the adapter has no source or finds no schedule file.
22
+ def call(now: Time.now)
23
+ source = SOURCES[Jobs.adapter_name]
24
+ return unless source
25
+
26
+ section = const_get(source).call(now: now)
27
+ section if section && !section[:tasks].nil?
28
+ end
29
+ end
30
+ end
31
+ end
@@ -16,7 +16,124 @@ module Upstate
16
16
  end
17
17
  return {ok: false, pending_migrations: nil} unless ok
18
18
 
19
- {ok: true, pending_migrations: pending_migrations}
19
+ {ok: true, pending_migrations: pending_migrations}.merge(database_stats)
20
+ end
21
+
22
+ STATEMENT_TIMEOUT_MS = 250
23
+
24
+ SUMMARY_SQL = <<~SQL
25
+ SELECT
26
+ pg_database_size(current_database()),
27
+ (SELECT count(*) FROM pg_stat_activity WHERE backend_type = 'client backend'),
28
+ current_setting('max_connections')::int,
29
+ COALESCE((SELECT floor(extract(epoch FROM now() - min(xact_start)))::bigint
30
+ FROM pg_stat_activity
31
+ WHERE datname = current_database() AND xact_start IS NOT NULL
32
+ AND pid <> pg_backend_pid() AND backend_type = 'client backend'), 0),
33
+ (SELECT count(*) FROM pg_stat_activity
34
+ WHERE datname = current_database()
35
+ AND state IN ('idle in transaction', 'idle in transaction (aborted)')),
36
+ (SELECT age(datfrozenxid) FROM pg_database WHERE datname = current_database()),
37
+ pg_is_in_recovery(),
38
+ CASE WHEN pg_is_in_recovery()
39
+ THEN floor(extract(epoch FROM now() - pg_last_xact_replay_timestamp()))::bigint END
40
+ SQL
41
+
42
+ TABLES_SQL = <<~SQL
43
+ SELECT quote_ident(schemaname) || '.' || quote_ident(relname), pg_total_relation_size(relid), n_live_tup, n_dead_tup
44
+ FROM pg_stat_user_tables
45
+ ORDER BY pg_total_relation_size(relid) DESC
46
+ LIMIT 5
47
+ SQL
48
+
49
+ REPLICAS_SQL = <<~SQL
50
+ SELECT count(*), floor(extract(epoch FROM max(replay_lag)))::bigint FROM pg_stat_replication
51
+ SQL
52
+
53
+ # Cheap, aggregate, read-only PostgreSQL health numbers for the primary connection:
54
+ # size (this database only, not WAL or other databases), connections vs
55
+ # max_connections, the oldest open transaction and sessions idle in transaction (as
56
+ # visible to the app's role), age(datfrozenxid), replication lag where visible, and
57
+ # the 5 largest tables with estimated live/dead rows (names and numbers, no row data;
58
+ # each name part is quote_ident-ed so distinct tables never share a schema.table name).
59
+ # One transaction with a transaction-local statement timeout and a savepoint per query,
60
+ # so a failing query drops only its fields. Other adapters or any error return {}.
61
+ def database_stats
62
+ ::ActiveRecord::Base.connection_pool.with_connection do |connection|
63
+ next {} unless connection.adapter_name.to_s.match?(/postg/i)
64
+
65
+ connection.transaction(requires_new: true) do
66
+ connection.execute("SET LOCAL statement_timeout = #{STATEMENT_TIMEOUT_MS}")
67
+ summary = guarded_rows(connection, SUMMARY_SQL)&.first
68
+ tables = guarded_rows(connection, TABLES_SQL)
69
+ replicas = guarded_rows(connection, REPLICAS_SQL)&.first if primary?(summary)
70
+
71
+ stats = summary_stats(summary)
72
+ table_list = table_stats(tables)
73
+ stats[:largest_tables] = table_list if table_list
74
+ replica_stats = replicas_stats(replicas)
75
+ stats[:replication] = replica_stats if replica_stats
76
+ stats
77
+ end
78
+ end
79
+ rescue StandardError
80
+ {}
81
+ end
82
+
83
+ # Runs one query behind a savepoint; a failure rolls back to it and returns nil.
84
+ def guarded_rows(connection, sql)
85
+ connection.transaction(requires_new: true) { connection.select_rows(sql) }
86
+ rescue StandardError
87
+ nil
88
+ end
89
+
90
+ def primary?(summary)
91
+ summary.is_a?(Array) && [false, "f"].include?(summary[6])
92
+ end
93
+
94
+ def summary_stats(row)
95
+ return {} unless row.is_a?(Array) && row.size == 8
96
+
97
+ size, in_use, max, oldest, idle, xid_age, recovery, lag = row
98
+ stats = {}
99
+ put(stats, :size_bytes, count(size))
100
+ in_use = count(in_use)
101
+ max = count(max)
102
+ stats[:connections] = {in_use: in_use, max: max} if in_use && max&.positive?
103
+ put(stats, :oldest_transaction_age_seconds, count(oldest))
104
+ put(stats, :idle_in_transaction, count(idle))
105
+ put(stats, :xid_age, count(xid_age))
106
+ stats[:replication] = {role: "replica", lag_seconds: count(lag)} if [true, "t"].include?(recovery)
107
+ stats
108
+ end
109
+
110
+ def table_stats(rows)
111
+ return nil unless rows.is_a?(Array) && !rows.empty?
112
+
113
+ tables = rows.first(5).filter_map do |name, total, live, dead|
114
+ next unless name.is_a?(String)
115
+
116
+ {name: name, total_bytes: count(total), live_rows: count(live), dead_rows: count(dead)}
117
+ end
118
+ tables.empty? ? nil : tables
119
+ end
120
+
121
+ def replicas_stats(row)
122
+ return nil unless row.is_a?(Array)
123
+
124
+ replicas = count(row[0])
125
+ return nil unless replicas&.positive?
126
+
127
+ {role: "primary", replicas: replicas, lag_seconds: count(row[1])}
128
+ end
129
+
130
+ def count(value)
131
+ number = Integer(value, exception: false) if value.is_a?(Integer) || value.is_a?(String)
132
+ number if number && number >= 0
133
+ end
134
+
135
+ def put(hash, key, value)
136
+ hash[key] = value unless value.nil?
20
137
  end
21
138
 
22
139
  # ConnectionPool#migration_context exists on 7.1+; older shapes fall back to the connection.
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Upstate
4
4
  module Rails
5
- VERSION = "0.1.0"
5
+ VERSION = "0.3.0"
6
6
  end
7
7
  end
data/lib/upstate/rails.rb CHANGED
@@ -62,6 +62,8 @@ require_relative "rails/jobs/solid_queue"
62
62
  require_relative "rails/jobs/sidekiq"
63
63
  require_relative "rails/jobs/good_job"
64
64
  require_relative "rails/jobs"
65
+ require_relative "rails/recurring/solid_queue_source"
66
+ require_relative "rails/recurring"
65
67
  require_relative "rails/sections"
66
68
  require_relative "rails/health"
67
69
  require_relative "rails/endpoint"
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: upstate-rails
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Upstate
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-10-21 00:00:00.000000000 Z
11
+ date: 2026-11-13 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: railties
@@ -74,6 +74,8 @@ files:
74
74
  - lib/upstate/rails/jobs/sidekiq.rb
75
75
  - lib/upstate/rails/jobs/solid_queue.rb
76
76
  - lib/upstate/rails/railtie.rb
77
+ - lib/upstate/rails/recurring.rb
78
+ - lib/upstate/rails/recurring/solid_queue_source.rb
77
79
  - lib/upstate/rails/sections.rb
78
80
  - lib/upstate/rails/version.rb
79
81
  homepage: https://github.com/Upstate-run/upstate-rails