solid_queue_board 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.
Files changed (40) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +22 -0
  3. data/LICENSE.txt +21 -0
  4. data/README.md +131 -0
  5. data/app/controllers/solid_queue_board/application_controller.rb +42 -0
  6. data/app/controllers/solid_queue_board/jobs_controller.rb +60 -0
  7. data/app/controllers/solid_queue_board/processes_controller.rb +12 -0
  8. data/app/controllers/solid_queue_board/queues_controller.rb +21 -0
  9. data/app/controllers/solid_queue_board/recurring_tasks_controller.rb +23 -0
  10. data/app/helpers/solid_queue_board/application_helper.rb +162 -0
  11. data/app/models/solid_queue_board/job_record.rb +13 -0
  12. data/app/models/solid_queue_board/jobs_query.rb +101 -0
  13. data/app/views/layouts/solid_queue_board/application.html.erb +53 -0
  14. data/app/views/layouts/solid_queue_board/partial.html.erb +3 -0
  15. data/app/views/solid_queue_board/jobs/_empty.html.erb +1 -0
  16. data/app/views/solid_queue_board/jobs/_pager.html.erb +11 -0
  17. data/app/views/solid_queue_board/jobs/_row.html.erb +53 -0
  18. data/app/views/solid_queue_board/jobs/_toolbar.html.erb +25 -0
  19. data/app/views/solid_queue_board/jobs/index.html.erb +23 -0
  20. data/app/views/solid_queue_board/processes/index.html.erb +85 -0
  21. data/app/views/solid_queue_board/queues/index.html.erb +34 -0
  22. data/app/views/solid_queue_board/recurring_tasks/index.html.erb +50 -0
  23. data/app/views/solid_queue_board/shared/_flash.html.erb +6 -0
  24. data/app/views/solid_queue_board/shared/_nav.html.erb +14 -0
  25. data/config/locales/de.yml +149 -0
  26. data/config/locales/en.yml +149 -0
  27. data/config/locales/es.yml +149 -0
  28. data/config/locales/fr.yml +149 -0
  29. data/config/locales/it.yml +149 -0
  30. data/config/locales/ja.yml +149 -0
  31. data/config/locales/ko.yml +149 -0
  32. data/config/locales/pt.yml +149 -0
  33. data/config/locales/zh-CN.yml +149 -0
  34. data/config/routes.rb +30 -0
  35. data/lib/solid_queue_board/engine.rb +24 -0
  36. data/lib/solid_queue_board/version.rb +5 -0
  37. data/lib/solid_queue_board/web/board.css +258 -0
  38. data/lib/solid_queue_board/web/board.js +358 -0
  39. data/lib/solid_queue_board.rb +51 -0
  40. metadata +159 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 1e6bbd0527825f79a0a89f0aec0672273351435bf56a4d7cea73afc373177830
4
+ data.tar.gz: c317e7d21a97e66932d5dc895e9532d99a36d8a2e9d3e37967255748d8c8682e
5
+ SHA512:
6
+ metadata.gz: aacc6d3fff579ade0218e10e511cf4c1a5ba130338b3e3960e2d28017d87678dca2785cf15a56cf418fb2d7c3b12917625a5a41155486597183e63810820df37
7
+ data.tar.gz: 900fd2d86d66a84630f9508c573c78edadd2602c4c8c80acc1c18f857829e4afcfb693cceb0f2b8d3eb86b1180fea6e7cb1eadf24c0464e4ff89424f47355aaf
data/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ - First version: jobs by state (ready, running, scheduled, blocked, failed, finished), search and queue filter,
6
+ failed job retry/discard and "retry all", queues pause/resume, recurring tasks with "run now", processes and heartbeats.
7
+ - Auto-refresh by polling (3, 6, 12, 24 s or paused; default 6 s), paused while the tab is hidden or the user is typing.
8
+ Rows are updated in place (new, changed and removed rows only), so open rows, hover and animations survive a refresh.
9
+ The jobs page refreshes through JSON with one HTML fragment per row; new rows slide in and the rows below move down.
10
+ - New jobs that appear on a refresh get one long green pulse (about 4 seconds); jobs that change state keep a short flash.
11
+ - Compact top bar: one live button (click cycles the refresh interval and refreshes) and one theme button.
12
+ - Jobs table in five columns with a status stripe; retry and discard sit on the row, "retry all" only on the Failed tab.
13
+ Below 600px each job becomes a card, without horizontal scrolling.
14
+ - Processes expand on click like jobs: ID, start time and uptime, supervisor, supervised processes,
15
+ full metadata and the jobs the process is running (each linked to the jobs list). Below 600px each process
16
+ becomes a card, like the jobs.
17
+ - Jobs: filter by job class (menu in the toolbar) and sort by job, queue or time by clicking the column header.
18
+ Built on Ransack, now a dependency; a read-only `SolidQueueBoard::JobRecord` model holds the Ransack allowlist,
19
+ so the app's `SolidQueue::Job` is not changed.
20
+ - Fix: below 600px the job details were always open, and the card background and status stripe had gaps.
21
+ - Light and dark theme (system, light, dark), Bootstrap 3 look with square corners.
22
+ - English, Italian, German, Spanish, French, Portuguese, Simplified Chinese, Japanese and Korean translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Riccardo Zanotelli
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,131 @@
1
+ # Solid Queue Board
2
+
3
+ A small, self-contained dashboard for [Solid Queue](https://github.com/rails/solid_queue): see what your jobs are doing, retry or discard them, pause queues and check that workers are alive. Mount it in your Rails app; nothing to build or import.
4
+
5
+ ![Expanding a failed job, sorting by time, filtering by job class and switching to the dark theme](docs/gifs/tour.gif)
6
+
7
+ ## Features
8
+
9
+ ### Jobs
10
+
11
+ - One menu row with every job state (all, ready, running, scheduled, blocked, failed, finished) and its live count, then queues, recurring tasks and processes.
12
+ - Click a job to expand it: error and backtrace, arguments, Active Job ID, priority, enqueue, schedule and finish times.
13
+ - Filter by job class, search by class or ID, sort by job, queue or time by clicking a column header. Filters and sorting use [Ransack](https://github.com/activerecord-hackery/ransack).
14
+ - Retry or discard a failed job, retry all failed jobs at once, discard ready, scheduled or blocked jobs.
15
+
16
+ ### Live updates
17
+
18
+ ![A new job appears on refresh: it slides in, turns from ready to finished and pulses green](docs/gifs/live-refresh.gif)
19
+
20
+ - The page refreshes itself every 3, 6, 12 or 24 seconds, or stays paused (6 by default). One button in the top bar cycles the interval.
21
+ - Only new, changed and removed rows are touched: new jobs slide in with a green pulse, jobs that change state flash, expanded rows stay open.
22
+ - Refreshing pauses while the tab is hidden, while you type in a field and while you select text.
23
+
24
+ ### Queues, recurring tasks and processes
25
+
26
+ - Queues with size and latency; pause and resume a queue.
27
+ - Recurring tasks with schedule, next and last run; run one now.
28
+ - Processes with heartbeat status. Click one to see its supervisor, the processes it supervises, its full metadata and the jobs it is running.
29
+
30
+ ### Mobile and dark theme
31
+
32
+ ![On a phone jobs and processes become cards; tapping one expands it](docs/gifs/mobile.gif)
33
+
34
+ - Below 600px jobs and processes become cards, without horizontal scrolling.
35
+ - Light and dark theme: follows the system, or pick one with the button in the top bar. Bootstrap 3 look with square corners.
36
+
37
+ ### Small footprint
38
+
39
+ - No front-end dependencies to install or import: CSS and JavaScript ship inside the gem and are inlined in the page. No asset pipeline, no CDN, no web fonts. Works with Sprockets, Propshaft or neither.
40
+ - English, Italian, German, Spanish, French, Portuguese, Simplified Chinese, Japanese and Korean translations.
41
+
42
+ ## Requirements
43
+
44
+ - Ruby 3.2+
45
+ - Rails 7.1+
46
+ - Solid Queue 1.0+
47
+ - Ransack 4.0+ (installed with the gem)
48
+
49
+ ## Installation
50
+
51
+ ```ruby
52
+ # Gemfile
53
+ gem "solid_queue_board"
54
+ ```
55
+
56
+ ```ruby
57
+ # config/routes.rb
58
+ mount SolidQueueBoard::Engine, at: "/jobs"
59
+ ```
60
+
61
+ ## Access control
62
+
63
+ The dashboard is **closed outside development and test** until you configure it. Create an initializer:
64
+
65
+ ```ruby
66
+ # config/initializers/solid_queue_board.rb
67
+ SolidQueueBoard.configure do |config|
68
+ # Inherit from your controller to reuse its authentication (before_actions, current_user, ...).
69
+ config.base_controller_class = "ApplicationController"
70
+
71
+ # Called with the controller before every action. Return true to allow access.
72
+ config.authorize = ->(controller) { controller.current_user&.admin? }
73
+ end
74
+ ```
75
+
76
+ With Devise you can also protect the mount point itself:
77
+
78
+ ```ruby
79
+ authenticate :user, ->(user) { user.admin? } do
80
+ mount SolidQueueBoard::Engine, at: "/jobs"
81
+ end
82
+ ```
83
+
84
+ If you protect the route this way, `config.authorize = ->(_) { true }` is enough.
85
+
86
+ ## Configuration
87
+
88
+ | Option | Default | Description |
89
+ |---|---|---|
90
+ | `base_controller_class` | `"ActionController::Base"` | Controller the dashboard inherits from. |
91
+ | `authorize` | open in development and test only | Lambda receiving the controller, returns true to allow access. |
92
+ | `title` | host app name | Name shown in the top bar and in the page title. |
93
+ | `back_url` | `"/"` | Link back to the host app in the top bar. `nil` hides it. |
94
+ | `per_page` | `50` | Rows per page in the jobs table. |
95
+ | `poll_intervals` | `[3, 6, 12, 24, 0]` | Refresh choices in seconds, in click order. `0` means paused. |
96
+ | `default_poll_interval` | `6` | Refresh interval used until the user picks another one. |
97
+
98
+ The chosen theme and refresh interval are stored per browser in `localStorage`.
99
+
100
+ ## How auto-refresh works
101
+
102
+ The page polls its own URL with the `X-SQB-Partial` header. The server then renders only the menu and the content, without the layout, and the script swaps them in. Expanded job and process rows stay open across refreshes. Rows whose state changed are briefly highlighted. If the session expires, the refresh stops with an error message instead of loading the login page inside the dashboard.
103
+
104
+ Each refresh runs a handful of `COUNT` queries (one per job state plus queues, recurring tasks and processes) and one page of jobs. The jobs page also loads the list of job classes for the filter menu (`SELECT DISTINCT class_name`, served by Solid Queue's index on that column).
105
+
106
+ ## Content Security Policy
107
+
108
+ Inline `<style>` and `<script>` tags carry the request nonce when your app configures one (`content_security_policy_nonce`). No inline event handlers or `style` attributes are used.
109
+
110
+ ## Translations
111
+
112
+ English, Italian, German, Spanish, French, Portuguese, Simplified Chinese, Japanese and Korean are included (`en`, `it`, `de`, `es`, `fr`, `pt`, `zh-CN`, `ja`, `ko`). The page follows `I18n.locale`; if your app sets `config.i18n.available_locales`, add the ones you want there. To add a language, copy `config/locales/en.yml` into your app as `config/locales/solid_queue_board.<locale>.yml` and translate the `solid_queue_board` keys.
113
+
114
+ ## Development
115
+
116
+ ```bash
117
+ bundle install
118
+ bundle exec rake test
119
+ ```
120
+
121
+ Tests run against an in-memory SQLite database with the Solid Queue schema loaded.
122
+
123
+ To try the dashboard on a demo app (SQLite, an in-process worker and a recurring job every 15 seconds):
124
+
125
+ ```bash
126
+ bundle exec rake demo # http://localhost:3000/jobs, PORT=4000 to change
127
+ ```
128
+
129
+ ## License
130
+
131
+ MIT, see [LICENSE.txt](LICENSE.txt).
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ class ApplicationController < SolidQueueBoard.base_controller_class.constantize
5
+ PARTIAL_HEADER = "X-SQB-Partial"
6
+
7
+ layout :board_layout
8
+ helper SolidQueueBoard::ApplicationHelper
9
+
10
+ before_action :authorize_board!
11
+ before_action :load_navigation
12
+
13
+ private
14
+ def authorize_board!
15
+ return if SolidQueueBoard.authorize.call(self)
16
+
17
+ render plain: I18n.t("solid_queue_board.forbidden"), status: :forbidden, layout: false
18
+ end
19
+
20
+ def load_navigation
21
+ @job_counts = JobsQuery.counts
22
+ @section_counts = {
23
+ "queues" => SolidQueue::Queue.all.size,
24
+ "recurring_tasks" => SolidQueue::RecurringTask.count,
25
+ "processes" => SolidQueue::Process.count
26
+ }
27
+ end
28
+
29
+ # Auto-refresh requests get only the live region (menu + content), not the full page.
30
+ def partial_request?
31
+ request.headers[PARTIAL_HEADER].present?
32
+ end
33
+
34
+ def board_layout
35
+ partial_request? ? "solid_queue_board/partial" : "solid_queue_board/application"
36
+ end
37
+
38
+ def back_to_board(fallback, **flash_message)
39
+ redirect_back fallback_location: fallback, allow_other_host: false, **flash_message
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ class JobsController < ApplicationController
5
+ before_action :set_job, only: %i[retry discard]
6
+
7
+ def index
8
+ @query = JobsQuery.new(status: params[:status], search: params[:q], queue: params[:queue], filters: params[:f],
9
+ page: params[:page])
10
+ render json: live_payload if request.format.json?
11
+ end
12
+
13
+ def retry
14
+ if @job.failed_execution
15
+ @job.retry
16
+ back_to_board jobs_path, notice: t("solid_queue_board.flash.retried", id: @job.id)
17
+ else
18
+ back_to_board jobs_path, alert: t("solid_queue_board.flash.not_failed", id: @job.id)
19
+ end
20
+ end
21
+
22
+ def discard
23
+ execution = @job.failed_execution || @job.ready_execution || @job.scheduled_execution || @job.blocked_execution
24
+ if execution
25
+ execution.discard
26
+ back_to_board jobs_path, notice: t("solid_queue_board.flash.discarded", id: @job.id)
27
+ else
28
+ back_to_board jobs_path, alert: t("solid_queue_board.flash.not_discardable", id: @job.id)
29
+ end
30
+ end
31
+
32
+ def retry_all
33
+ failed = SolidQueue::Job.where(id: SolidQueue::FailedExecution.select(:job_id))
34
+ count = failed.count
35
+ SolidQueue::FailedExecution.retry_all(failed) if count.positive?
36
+ back_to_board jobs_path, notice: t("solid_queue_board.flash.retried_all", count: count)
37
+ end
38
+
39
+ private
40
+ # Auto-refresh of the jobs page: one HTML fragment per job row, keyed by id, so the page
41
+ # can insert, update and remove rows one by one (and animate them). Markup stays in ERB.
42
+ def live_payload
43
+ fragment = ->(partial, **locals) { render_to_string(partial: partial, formats: [ :html ], locals: locals) }
44
+ {
45
+ nav: fragment.call("solid_queue_board/shared/nav"),
46
+ toolbar: fragment.call("solid_queue_board/jobs/toolbar"),
47
+ pager: fragment.call("solid_queue_board/jobs/pager"),
48
+ empty: (fragment.call("solid_queue_board/jobs/empty") if @query.rows.empty?),
49
+ rows: @query.rows.map do |job|
50
+ { id: job.id.to_s, sig: helpers.sqb_job_status(job), html: fragment.call("solid_queue_board/jobs/row", job: job) }
51
+ end
52
+ }
53
+ end
54
+
55
+ def set_job
56
+ @job = SolidQueue::Job.find_by(id: params[:id])
57
+ back_to_board jobs_path, alert: t("solid_queue_board.flash.not_found", id: params[:id]) unless @job
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ class ProcessesController < ApplicationController
5
+ def index
6
+ @processes = SolidQueue::Process.order(:hostname, :kind, :id).to_a
7
+ @by_id = @processes.index_by(&:id)
8
+ @supervised = @processes.group_by(&:supervisor_id)
9
+ @claimed = SolidQueue::ClaimedExecution.includes(:job).order(:id).group_by(&:process_id)
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ class QueuesController < ApplicationController
5
+ def index
6
+ paused = SolidQueue::Pause.pluck(:queue_name)
7
+ names = (SolidQueue::Queue.all.map(&:name) + paused).uniq.sort
8
+ @queues = names.map { |name| SolidQueue::Queue.find_by_name(name) }
9
+ end
10
+
11
+ def pause
12
+ SolidQueue::Queue.find_by_name(params[:name]).pause
13
+ back_to_board queues_path, notice: t("solid_queue_board.flash.paused", name: params[:name])
14
+ end
15
+
16
+ def resume
17
+ SolidQueue::Queue.find_by_name(params[:name]).resume
18
+ back_to_board queues_path, notice: t("solid_queue_board.flash.resumed", name: params[:name])
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ class RecurringTasksController < ApplicationController
5
+ def index
6
+ @tasks = SolidQueue::RecurringTask.order(:key).to_a
7
+ @last_runs = @tasks.to_h do |task|
8
+ execution = SolidQueue::RecurringExecution.where(task_key: task.key).order(run_at: :desc).first
9
+ job = execution && SolidQueue::Job.includes(:failed_execution, :claimed_execution, :ready_execution).find_by(id: execution.job_id)
10
+ [ task.key, { at: execution&.run_at, job: job } ]
11
+ end
12
+ end
13
+
14
+ def run
15
+ task = SolidQueue::RecurringTask.find_by(key: params[:key])
16
+ if task && task.enqueue(at: Time.current)
17
+ back_to_board recurring_tasks_path, notice: t("solid_queue_board.flash.enqueued", key: task.key)
18
+ else
19
+ back_to_board recurring_tasks_path, alert: t("solid_queue_board.flash.not_enqueued", key: params[:key])
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,162 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ module ApplicationHelper
5
+ STATUS_TONES = {
6
+ "ready" => "primary", "claimed" => "info", "scheduled" => "default",
7
+ "blocked" => "warning", "failed" => "danger", "finished" => "success"
8
+ }.freeze
9
+
10
+ NAV_TONES = { "ready" => "warning", "claimed" => "info", "blocked" => "warning", "failed" => "danger" }.freeze
11
+
12
+ def sqb_t(key, **options)
13
+ t("solid_queue_board.#{key}", **options)
14
+ end
15
+
16
+ # ---- layout ----
17
+
18
+ def sqb_inline_css
19
+ tag.style(SolidQueueBoard::Web.css.html_safe, nonce: content_security_policy_nonce)
20
+ end
21
+
22
+ def sqb_inline_js
23
+ tag.script(SolidQueueBoard::Web.js.html_safe, nonce: content_security_policy_nonce)
24
+ end
25
+
26
+ def sqb_nav_tab(label, url, count:, active:, tone: nil)
27
+ badge = tag.span(count, class: [ "badge", (tone if count.to_i.positive?) ])
28
+ link_to(safe_join([ label, badge ], " "), url, class: "tab", "aria-current": (active ? "page" : nil))
29
+ end
30
+
31
+ # ---- jobs ----
32
+
33
+ def sqb_job_status(job)
34
+ return "finished" if job.finished?
35
+ return "failed" if job.failed_execution
36
+ return "claimed" if job.claimed_execution
37
+ return "ready" if job.ready_execution
38
+ return "scheduled" if job.scheduled_execution
39
+ return "blocked" if job.blocked_execution
40
+
41
+ "unknown"
42
+ end
43
+
44
+ def sqb_status_label(status, text = nil)
45
+ tag.span(text || sqb_t("status.#{status}"), class: "label label-#{STATUS_TONES.fetch(status.to_s, 'default')}")
46
+ end
47
+
48
+ def sqb_job_time(job, status)
49
+ case status
50
+ when "finished" then job.finished_at
51
+ when "failed" then job.failed_execution.created_at
52
+ when "claimed" then job.claimed_execution.created_at
53
+ when "scheduled" then job.scheduled_at
54
+ else job.created_at
55
+ end
56
+ end
57
+
58
+ def sqb_job_detail(job, status)
59
+ case status
60
+ when "finished"
61
+ sqb_duration(job.finished_at - job.created_at) if job.finished_at && job.created_at
62
+ when "failed"
63
+ tag.span(job.failed_execution.exception_class, class: "err-msg")
64
+ when "claimed"
65
+ tag.span(sqb_t("jobs.running_for", time: sqb_duration(Time.current - job.claimed_execution.created_at)), class: "muted")
66
+ when "blocked"
67
+ tag.span(sqb_t("jobs.blocked_by", key: job.concurrency_key), class: "muted")
68
+ end
69
+ end
70
+
71
+ def sqb_payload(job)
72
+ job.arguments.is_a?(Hash) ? job.arguments : { "arguments" => job.arguments }
73
+ end
74
+
75
+ def sqb_arguments(job, limit: 120)
76
+ args = sqb_simplify(sqb_payload(job)["arguments"] || [])
77
+ text = args.is_a?(String) ? args : JSON.generate(args)
78
+ text.length > limit ? "#{text[0, limit]}…" : text
79
+ rescue StandardError
80
+ ""
81
+ end
82
+
83
+ def sqb_arguments_pretty(job)
84
+ JSON.pretty_generate(sqb_simplify(sqb_payload(job)["arguments"] || []))
85
+ rescue StandardError
86
+ sqb_payload(job)["arguments"].inspect
87
+ end
88
+
89
+ def sqb_executions(job)
90
+ sqb_payload(job)["executions"]
91
+ end
92
+
93
+ # Column header that sorts the jobs by attribute: first click descending (newest, Z-A), then toggles.
94
+ def sqb_sort_header(label, attribute)
95
+ current = @query.sort_attribute == attribute ? @query.sort_direction : nil
96
+ next_direction = current == "desc" ? "asc" : "desc"
97
+ arrow = { "asc" => "\u25B2", "desc" => "\u25BC" }[current]
98
+ link = link_to(jobs_path(@query.url_params(sort: "#{attribute} #{next_direction}")), class: "sort",
99
+ title: sqb_t("jobs.sort_by", column: label)) do
100
+ safe_join([ label, (tag.span(arrow, class: "sort-dir", "aria-hidden": true) if arrow) ].compact, " ")
101
+ end
102
+ tag.th(link, "aria-sort": { "asc" => "ascending", "desc" => "descending" }.fetch(current, "none"))
103
+ end
104
+
105
+ def sqb_discardable?(status)
106
+ %w[failed ready scheduled blocked].include?(status)
107
+ end
108
+
109
+ # ---- formatting ----
110
+
111
+ def sqb_time(time)
112
+ return tag.span("—", class: "muted") unless time
113
+
114
+ time = time.in_time_zone
115
+ format = time.to_date == Time.zone.today ? "%H:%M:%S" : sqb_t("formats.datetime")
116
+ tag.time(datetime: time.iso8601, title: time.strftime(sqb_t("formats.full"))) do
117
+ safe_join([ time.strftime(format), " ", tag.span("(#{sqb_ago(time)})", class: "muted") ])
118
+ end
119
+ end
120
+
121
+ def sqb_ago(time)
122
+ seconds = (Time.current - time).round
123
+ amount = sqb_amount(seconds.abs)
124
+ seconds >= 0 ? sqb_t("time.ago", time: amount) : sqb_t("time.in", time: amount)
125
+ end
126
+
127
+ def sqb_amount(seconds)
128
+ if seconds < 60 then sqb_t("time.seconds", count: seconds)
129
+ elsif seconds < 3600 then sqb_t("time.minutes", count: seconds / 60)
130
+ elsif seconds < 86_400 then sqb_t("time.hours", count: seconds / 3600, minutes: (seconds % 3600) / 60)
131
+ else sqb_t("time.days", count: seconds / 86_400)
132
+ end
133
+ end
134
+
135
+ def sqb_duration(seconds)
136
+ seconds = seconds.to_f
137
+ return "#{(seconds * 1000).round} ms" if seconds < 1
138
+ return "#{seconds.round(1)} s" if seconds < 60
139
+
140
+ sqb_amount(seconds.round)
141
+ end
142
+
143
+ def sqb_metadata(metadata)
144
+ return "" if metadata.blank?
145
+
146
+ metadata.map { |key, value| "#{key}: #{value.is_a?(Array) ? value.join(', ') : value}" }.join(" · ")
147
+ end
148
+
149
+ private
150
+ # Shows ActiveJob GlobalID arguments as their gid string instead of the wrapper hash.
151
+ def sqb_simplify(value)
152
+ case value
153
+ when Array then value.map { |item| sqb_simplify(item) }
154
+ when Hash
155
+ return value["_aj_globalid"] if value.key?("_aj_globalid")
156
+
157
+ value.except("_aj_symbol_keys", "_aj_ruby2_keywords", "_aj_serialized").transform_values { |item| sqb_simplify(item) }
158
+ else value
159
+ end
160
+ end
161
+ end
162
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ # Read model for the jobs table: SolidQueue::Job plus the Ransack allowlist, so the host app's
5
+ # model is not touched. Same table, no STI column, so it loads every job.
6
+ class JobRecord < SolidQueue::Job
7
+ RANSACKABLE = %w[id class_name queue_name priority created_at scheduled_at finished_at].freeze
8
+
9
+ def self.ransackable_attributes(_auth_object = nil) = RANSACKABLE
10
+ def self.ransackable_associations(_auth_object = nil) = []
11
+ def self.ransackable_scopes(_auth_object = nil) = []
12
+ end
13
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueueBoard
4
+ # Filters, searches and paginates SolidQueue::Job rows for the jobs table.
5
+ class JobsQuery
6
+ STATUSES = %w[all ready claimed scheduled blocked failed finished].freeze
7
+
8
+ EXECUTIONS = {
9
+ "ready" => SolidQueue::ReadyExecution,
10
+ "claimed" => SolidQueue::ClaimedExecution,
11
+ "scheduled" => SolidQueue::ScheduledExecution,
12
+ "blocked" => SolidQueue::BlockedExecution,
13
+ "failed" => SolidQueue::FailedExecution
14
+ }.freeze
15
+
16
+ SORTABLE = %w[id class_name queue_name created_at scheduled_at finished_at].freeze
17
+ DIRECTIONS = %w[asc desc].freeze
18
+
19
+ attr_reader :status, :search, :queue, :job_class, :sort_attribute, :sort_direction, :page, :per_page
20
+
21
+ def self.counts
22
+ EXECUTIONS.transform_values(&:count).merge(
23
+ "all" => SolidQueue::Job.count,
24
+ "finished" => SolidQueue::Job.finished.count
25
+ )
26
+ end
27
+
28
+ # filters: the Ransack params (param "f"). Only the job class filter and the sort are read.
29
+ def initialize(status: nil, search: nil, queue: nil, filters: nil, page: nil, per_page: SolidQueueBoard.per_page)
30
+ @status = STATUSES.include?(status.to_s) ? status.to_s : "all"
31
+ @search = search.to_s.strip.presence
32
+ @queue = queue.to_s.strip.presence
33
+ filters = filters.to_unsafe_h if filters.respond_to?(:to_unsafe_h)
34
+ filters = filters.is_a?(Hash) ? filters.with_indifferent_access : {}
35
+ @job_class = filters["class_name_eq"].to_s.strip.presence
36
+ @sort_attribute, @sort_direction = filters["s"].to_s.split
37
+ @sort_attribute = @sort_direction = nil unless SORTABLE.include?(@sort_attribute) && DIRECTIONS.include?(@sort_direction)
38
+ @page = [ page.to_i, 1 ].max
39
+ @per_page = per_page
40
+ end
41
+
42
+ # Loads one extra row to know whether a next page exists.
43
+ def jobs
44
+ @jobs ||= scope
45
+ .includes(:ready_execution, :claimed_execution, :failed_execution, :scheduled_execution, :blocked_execution)
46
+ .order(id: :desc) # after the Ransack sort: newest first, and a stable order for paging
47
+ .offset((page - 1) * per_page)
48
+ .limit(per_page + 1)
49
+ .to_a
50
+ end
51
+
52
+ def rows = jobs.first(per_page)
53
+ def next_page? = jobs.size > per_page
54
+ def prev_page? = page > 1
55
+ def filtered? = !!(search || queue || job_class)
56
+
57
+ # Job classes for the filter menu (solid_queue_jobs has an index on class_name).
58
+ def job_classes
59
+ @job_classes ||= JobRecord.distinct.order(:class_name).pluck(:class_name)
60
+ end
61
+
62
+ # The time shown in the "When" column, as a sortable attribute.
63
+ def time_attribute
64
+ { "finished" => "finished_at", "scheduled" => "scheduled_at" }.fetch(status, "created_at")
65
+ end
66
+
67
+ def sort = ("#{sort_attribute} #{sort_direction}" if sort_attribute)
68
+
69
+ # Query string for links on the jobs page; overrides replace or (with nil) drop a value.
70
+ def url_params(**overrides)
71
+ params = { status: (status == "all" ? nil : status), q: search, queue: queue, class_name: job_class, sort: sort, page: nil }
72
+ .merge(overrides)
73
+ filters = { class_name_eq: params.delete(:class_name), s: params.delete(:sort) }.compact
74
+ params.merge(f: filters.presence).compact
75
+ end
76
+
77
+ private
78
+ def scope
79
+ relation = by_status(JobRecord.all)
80
+ relation = relation.where(queue_name: queue) if queue
81
+ relation = by_search(relation) if search
82
+ relation.ransack({ "class_name_eq" => job_class, "s" => sort }.compact).result
83
+ end
84
+
85
+ def by_status(relation)
86
+ case status
87
+ when "finished" then relation.finished
88
+ when "all" then relation
89
+ else relation.where(id: EXECUTIONS.fetch(status).select(:job_id))
90
+ end
91
+ end
92
+
93
+ def by_search(relation)
94
+ table = SolidQueue::Job.arel_table
95
+ pattern = "%#{ActiveRecord::Base.sanitize_sql_like(search)}%"
96
+ condition = table[:class_name].matches(pattern).or(table[:active_job_id].eq(search))
97
+ condition = condition.or(table[:id].eq(search.to_i)) if search.match?(/\A\d+\z/)
98
+ relation.where(condition)
99
+ end
100
+ end
101
+ end