job_control 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: 471ad803e3da5149baf5f1c03e526172c37b1f07574cac5063120df02c616b3f
4
+ data.tar.gz: c8d34d1f600761b38c9ee8397f9b64250a2a32a7c604833a5db8265f49b0f28a
5
+ SHA512:
6
+ metadata.gz: 48e55f1c39310b76af6064fc4af4f21db5f333dd509ae8b0d1d7148a0f0787fc65f6579356adb5ec4648511ca80b97167cd7fe24ca7f5b5ca38382b6a2d2b793
7
+ data.tar.gz: 2d03b15f54f199081c4a13cc8923649f1a133eb60d0f101ba92c644fc9aff713486ce3749bd5cf60006f875c8fdc4077469d246eba7391b6262b7e84f24074ae
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ The first public release adds cooperative cancellation, heartbeats, lifecycle notifications, Solid Queue cleanup, and Mission Control Jobs integration. It requires Rails 8.1+ and does not ship RBS declarations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Manh Kha
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,158 @@
1
+ # JobControl
2
+
3
+ [JobControl](https://github.com/kha-wogi/job_control) gives long-running Active Job jobs a small, practical control surface: a heartbeat and a safe way to ask a job to stop.
4
+
5
+ Cancellation is cooperative. JobControl never kills a worker thread or interrupts a database transaction. Your job finishes the unit it is working on, notices the request at its next checkpoint, and exits cleanly. It works best when the job can divide its work into small, idempotent units.
6
+
7
+ ## What it supports
8
+
9
+ JobControl requires Ruby 3.2+ and Rails 8.1–8.x.
10
+
11
+ | Feature | Availability |
12
+ | --- | --- |
13
+ | Lifecycle, heartbeats, checkpoints, and cooperative cancellation | Any Active Job adapter |
14
+ | Cleanup after a permanent discard | Solid Queue 1.4–1.7 with the optional adapter |
15
+ | Job detail UI and cancellation button | mission_control-jobs 1.3.x with the optional integration |
16
+ | Cleanup after Sidekiq or GoodJob discard | Not included yet |
17
+
18
+ The core behavior lives at the Active Job layer, so it works with any adapter. Permanent discard is different: every queue exposes that operation differently, so it needs a queue-specific adapter.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ bundle add job_control
24
+ bin/rails generate job_control:install
25
+ bin/rails db:migrate
26
+ ```
27
+
28
+ Run the generator again when upgrading JobControl. It skips migrations that are already present and copies any new ones.
29
+
30
+ ## Your first controlled job
31
+
32
+ Include `JobControl::Job` in jobs that need cooperative cancellation. Add checkpoints between units that are safe to finish independently.
33
+
34
+ ```ruby
35
+ class ExampleJob < ApplicationJob
36
+ include JobControl::Job
37
+
38
+ def perform
39
+ 100.times do
40
+ perform_one_unit_of_work
41
+ checkpoint!
42
+ end
43
+ end
44
+
45
+ private
46
+
47
+ def perform_one_unit_of_work
48
+ end
49
+ end
50
+ ```
51
+
52
+ ```ruby
53
+ job = ExampleJob.perform_later
54
+ JobControl.cancel(job.job_id)
55
+ ```
56
+
57
+ `checkpoint!` updates the heartbeat and raises `JobControl::Cancelled` if cancellation was requested. Put it after a blocking wait and between batches or loop iterations. It does not interrupt code already running.
58
+
59
+ A checkpoint performs one database reload and one timestamp update. In practice, checkpoint once per batch or every few seconds of work—not once per record—unless near-instant cancellation matters more than the extra writes.
60
+
61
+ ## Lifecycle
62
+
63
+ A `job_controls` row is created when a controlled job is enqueued and becomes `running` when execution begins.
64
+
65
+ | What happens | What JobControl does |
66
+ | --- | --- |
67
+ | The job succeeds | Publishes `job_control.succeeded` and deletes the row immediately. |
68
+ | The job sees a cancellation request at a checkpoint | Publishes `job_control.cancelled` and deletes the row immediately. |
69
+ | The job fails without a cancellation request | Publishes `job_control.failed` and deletes the row. A retry gets a fresh active control with the same job ID. |
70
+ | A cancellation request is followed by an error | Leaves the row as `cancel_requested`, so a retry stops before doing work. |
71
+ | Solid Queue permanently discards the job | The Solid Queue adapter deletes any remaining row after the queue transaction commits. |
72
+
73
+ There is no retention window and no cleanup cron. For an unsupported queue, a cancelled attempt that fails and is never retried cannot be detected through generic Active Job callbacks; add a queue-specific adapter before relying on permanent-discard cleanup.
74
+
75
+ ## Runtime API
76
+
77
+ ```ruby
78
+ control = JobControl.find(job.job_id)
79
+
80
+ control.status
81
+ control.cancellable?
82
+ control.cancel_requested?
83
+ control.heartbeat_at
84
+ control.last_checkpoint_at
85
+
86
+ control.cancel!
87
+ ```
88
+
89
+ Within a controlled job, call `checkpoint!` directly or pass `cancellation` to a service with its own loop:
90
+
91
+ ```ruby
92
+ SomeService.call(cancellation: cancellation)
93
+ ```
94
+
95
+ ## Observability
96
+
97
+ A control is stale after five minutes without a heartbeat by default:
98
+
99
+ ```ruby
100
+ JobControl.configure do |config|
101
+ config.stale_after = 15.minutes
102
+ end
103
+ ```
104
+
105
+ JobControl publishes Active Support notifications with `control:` in the payload:
106
+
107
+ - `job_control.started`
108
+ - `job_control.checkpoint`
109
+ - `job_control.cancel_requested`
110
+ - `job_control.cancelled`
111
+ - `job_control.succeeded`
112
+ - `job_control.failed`
113
+
114
+ ## Solid Queue
115
+
116
+ The optional adapter supports Solid Queue 1.4–1.7 and removes controls after direct and batched discard operations.
117
+
118
+ ```ruby
119
+ require "job_control/adapters/solid_queue"
120
+
121
+ Rails.application.config.to_prepare do
122
+ JobControl::Adapters::SolidQueue::Adapter.install!
123
+ end
124
+ ```
125
+
126
+ ## Mission Control Jobs
127
+
128
+ With mission_control-jobs 1.3.x, JobControl adds a **Job control** section to the existing job detail page. It uses Mission Control's own styles and controller authentication.
129
+
130
+ ```ruby
131
+ require "job_control/integrations/mission_control_jobs"
132
+
133
+ Rails.application.config.to_prepare do
134
+ JobControl::Integrations::MissionControlJobs.install!
135
+ end
136
+ ```
137
+
138
+ Mission Control is assumed to be mounted at `/admin/jobs`. For another location:
139
+
140
+ ```ruby
141
+ JobControl::Integrations::MissionControlJobs.install!(mount_path: "/operations/jobs")
142
+ ```
143
+
144
+ The endpoint, client code, controller, and translations come from JobControl. There is no application view override, custom controller, or hand-written route to maintain. Restart the web process after enabling it.
145
+
146
+ ## Development
147
+
148
+ ```bash
149
+ bundle exec rake
150
+ ```
151
+
152
+ ## Out of scope
153
+
154
+ JobControl does not provide hard process termination, transaction rollback, progress tracking, pause/resume, cursor recovery, throttling, batch cancellation, or an administrative adapter for every queue backend.
155
+
156
+ ## Contributing
157
+
158
+ Issues and pull requests are welcome at [kha-wogi/job_control](https://github.com/kha-wogi/job_control).
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ # Supplies control state and cancellation to the Mission Control client.
5
+ class MissionControlJobsController < ::MissionControl::Jobs.base_controller_class.constantize
6
+ def show
7
+ control = JobControl::Control.find_by(job_id: params[:job_id])
8
+ return head :not_found unless control
9
+
10
+ render json: control_payload(control)
11
+ end
12
+
13
+ def cancel
14
+ control = JobControl::Control.find_by(job_id: params[:job_id])
15
+
16
+ if control&.cancellable?
17
+ control.cancel!
18
+ flash[:notice] = t("job_control.mission_control.cancellation_requested")
19
+ elsif control
20
+ flash[:alert] = t("job_control.mission_control.not_cancellable")
21
+ else
22
+ flash[:alert] = t("job_control.mission_control.not_found")
23
+ end
24
+
25
+ redirect_back fallback_location: JobControl::Integrations::MissionControlJobs.mount_path
26
+ end
27
+
28
+ private
29
+
30
+ def control_payload(control)
31
+ {
32
+ status: control.status,
33
+ cancel_requested: control.cancel_requested?,
34
+ cancellable: control.cancellable?,
35
+ heartbeat_at: control.heartbeat_at&.iso8601,
36
+ last_checkpoint_at: control.last_checkpoint_at&.iso8601
37
+ }
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,6 @@
1
+ en:
2
+ job_control:
3
+ mission_control:
4
+ cancellation_requested: "Cancellation requested."
5
+ not_cancellable: "This job can no longer be cancelled."
6
+ not_found: "Job control was not found."
@@ -0,0 +1,17 @@
1
+ class CreateJobControls < ActiveRecord::Migration[8.1]
2
+ def change
3
+ create_table :job_controls do |t|
4
+ t.string :job_id, null: false
5
+ t.string :status, null: false, default: "queued"
6
+ t.datetime :cancel_requested_at
7
+ t.datetime :started_at
8
+ t.datetime :finished_at
9
+ t.datetime :last_checkpoint_at
10
+ t.datetime :heartbeat_at
11
+ t.json :metadata, null: false, default: {}
12
+ t.timestamps
13
+ end
14
+
15
+ add_index :job_controls, :job_id, unique: true
16
+ end
17
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+ require "rails/generators/active_record"
5
+
6
+ module JobControl
7
+ module Generators
8
+ # Installs JobControl database migrations into the host application.
9
+ class InstallGenerator < Rails::Generators::Base
10
+ include Rails::Generators::Migration
11
+
12
+ source_root File.expand_path("../../../../db/migrate", __dir__)
13
+
14
+ def copy_migrations
15
+ migration_directory = File.join(destination_root, "db/migrate")
16
+
17
+ Dir.glob(File.join(self.class.source_root, "*.rb")).each do |path|
18
+ filename = File.basename(path)
19
+ migration_name = filename.sub(/\A\d+_/, "").delete_suffix(".rb")
20
+ next if self.class.migration_exists?(migration_directory, migration_name)
21
+
22
+ migration_template filename, "db/migrate/#{migration_name}.rb"
23
+ end
24
+ end
25
+
26
+ def self.next_migration_number(dirname)
27
+ ActiveRecord::Generators::Base.next_migration_number(dirname)
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ module Adapters
5
+ # Removes controls when Solid Queue permanently discards jobs.
6
+ module SolidQueue
7
+ # Internal instance hook for one discarded execution.
8
+ module ExecutionMethods
9
+ def discard
10
+ active_job_id = job.active_job_id
11
+ super.tap { Adapter.delete_control(active_job_id) }
12
+ end
13
+ end
14
+
15
+ # Internal class hooks for batch discard operations.
16
+ module ExecutionClassMethods
17
+ def discard_all_in_batches(batch_size: 500)
18
+ pending = count
19
+ discarded = 0
20
+
21
+ ::SolidQueue.instrument(:discard_all, batch_size: batch_size, status: type, batches: 0, size: 0) do |payload|
22
+ loop do
23
+ discarded, active_job_ids = discard_batch(batch_size, payload)
24
+ pending -= discarded
25
+ Adapter.delete_controls(active_job_ids)
26
+
27
+ break if pending <= 0 || discarded.zero?
28
+ end
29
+ end
30
+ end
31
+
32
+ def discard_all_from_jobs(jobs)
33
+ active_job_ids = []
34
+
35
+ ::SolidQueue.instrument(:discard_all, jobs_size: jobs.size, status: type) do |payload|
36
+ transaction do
37
+ job_ids = send(:lock_all_from_jobs, jobs)
38
+ active_job_ids = ::SolidQueue::Job.where(id: job_ids).pluck(:active_job_id)
39
+ payload[:size] = send(:discard_jobs, job_ids)
40
+ where(job_id: job_ids).delete_all
41
+ end
42
+ end
43
+ Adapter.delete_controls(active_job_ids)
44
+ end
45
+
46
+ private
47
+
48
+ def discard_batch(batch_size, payload)
49
+ active_job_ids = []
50
+ discarded = 0
51
+
52
+ transaction do
53
+ job_ids = limit(batch_size).order(:job_id).lock.pluck(:job_id)
54
+ active_job_ids = ::SolidQueue::Job.where(id: job_ids).pluck(:active_job_id)
55
+ discarded = send(:discard_jobs, job_ids)
56
+ where(job_id: job_ids).delete_all
57
+ payload[:size] += discarded
58
+ payload[:batches] += 1
59
+ end
60
+
61
+ [discarded, active_job_ids]
62
+ end
63
+ end
64
+
65
+ # Public installer and cross-database cleanup boundary.
66
+ module Adapter
67
+ SUPPORTED_VERSIONS = Gem::Requirement.new(">= 1.4", "< 1.8").freeze
68
+
69
+ module_function
70
+
71
+ def install!
72
+ verify_dependency!
73
+ ::SolidQueue::Execution.prepend(ExecutionMethods) unless ::SolidQueue::Execution < ExecutionMethods
74
+ singleton_class = ::SolidQueue::Execution.singleton_class
75
+ singleton_class.prepend(ExecutionClassMethods) unless singleton_class < ExecutionClassMethods
76
+ end
77
+
78
+ def delete_control(active_job_id)
79
+ delete_controls([active_job_id])
80
+ end
81
+
82
+ def delete_controls(active_job_ids)
83
+ ids = active_job_ids.compact
84
+ return if ids.empty?
85
+
86
+ JobControl::Control.where(job_id: ids).delete_all
87
+ end
88
+
89
+ def verify_dependency!
90
+ unless defined?(::SolidQueue::Execution) && defined?(::SolidQueue::Job)
91
+ raise LoadError, "JobControl Solid Queue adapter requires the solid_queue gem to be loaded"
92
+ end
93
+
94
+ version = Gem.loaded_specs.fetch("solid_queue").version
95
+ return if SUPPORTED_VERSIONS.satisfied_by?(version)
96
+
97
+ raise ConfigurationError, "JobControl Solid Queue adapter supports solid_queue #{SUPPORTED_VERSIONS}"
98
+ end
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ # A small cancellation token suitable for passing into application services.
5
+ class Cancellation
6
+ def initialize(control)
7
+ @control = control
8
+ end
9
+
10
+ def requested? = @control.reload.cancel_requested?
11
+ def checkpoint! = @control.checkpoint!
12
+ end
13
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ # Internal control-flow exception, deliberately not treated as job failure.
5
+ class Cancelled < StandardError; end
6
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ # Process-wide settings for the control runtime.
5
+ class Configuration
6
+ attr_accessor :stale_after
7
+
8
+ def initialize
9
+ @stale_after = 5.minutes
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ # Independent from a host application's base model and default scopes.
5
+ class Control < ActiveRecord::Base
6
+ self.table_name = "job_controls"
7
+
8
+ STATUSES = %w[queued running cancel_requested cancelled succeeded failed].freeze
9
+ COMPLETED_STATUSES = %w[cancelled succeeded].freeze
10
+
11
+ validates :job_id, presence: true
12
+ validates :status, inclusion: { in: STATUSES }
13
+
14
+ def controlled? = true
15
+ def cancellable? = status.in?(%w[queued running])
16
+ def cancel_requested? = cancel_requested_at.present?
17
+
18
+ def stale?
19
+ heartbeat_at.present? && heartbeat_at < JobControl.configuration.stale_after.ago
20
+ end
21
+
22
+ alias stalled? stale?
23
+
24
+ def cancel!
25
+ with_lock do
26
+ return self unless cancellable?
27
+
28
+ update!(cancel_requested_at: Time.current, status: "cancel_requested")
29
+ end
30
+ JobControl.instrument(:cancel_requested, self)
31
+ self
32
+ end
33
+
34
+ def mark_running!
35
+ return self if COMPLETED_STATUSES.include?(status)
36
+
37
+ update!(status: cancel_requested? ? "cancel_requested" : "running", started_at: started_at || Time.current)
38
+ JobControl.instrument(:started, self)
39
+ self
40
+ end
41
+
42
+ def mark_succeeded! = finish!("succeeded", :succeeded)
43
+ def mark_cancelled! = finish!("cancelled", :cancelled)
44
+ def mark_failed! = finish!("failed", :failed)
45
+
46
+ def checkpoint!
47
+ reload
48
+ now = Time.current
49
+ update_columns(last_checkpoint_at: now, heartbeat_at: now, updated_at: now)
50
+ JobControl.instrument(:checkpoint, self)
51
+ raise Cancelled if cancel_requested?
52
+
53
+ self
54
+ end
55
+
56
+ private
57
+
58
+ def finish!(next_status, event)
59
+ update!(status: next_status, finished_at: Time.current)
60
+ JobControl.instrument(event, self)
61
+ delete
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ # Registers the gem as a Rails engine; installation is performed by its generator.
5
+ class Engine < ::Rails::Engine
6
+ end
7
+ end
@@ -0,0 +1,125 @@
1
+ (() => {
2
+ const configuration = window.JobControlMissionControl;
3
+ const sectionId = "job-control-mission-control-panel";
4
+ const jobPath = /\/jobs\/([^/]+)\/?$/;
5
+
6
+ const statusPresentation = {
7
+ queued: ["Queued", "is-light"],
8
+ running: ["Running", "is-primary"]
9
+ };
10
+
11
+ const createElement = (name, { className, text } = {}) => {
12
+ const element = document.createElement(name);
13
+ if (className) element.className = className;
14
+ if (text) element.textContent = text;
15
+ return element;
16
+ };
17
+
18
+ const currentJobId = () => window.location.pathname.match(jobPath)?.[1];
19
+
20
+ const detailContainer = () => document.querySelector("main") || document.querySelector("[role=main]") || document.body;
21
+
22
+ const controlEndpoint = (jobId) => `${configuration.endpoint_prefix}/${encodeURIComponent(jobId)}`;
23
+
24
+ const requestControl = async (endpoint) => {
25
+ const response = await fetch(endpoint, {
26
+ headers: { Accept: "application/json" },
27
+ credentials: "same-origin"
28
+ });
29
+
30
+ return response.ok ? response.json() : null;
31
+ };
32
+
33
+ const statusTag = (control) => {
34
+ const [label, className] = control.cancel_requested ?
35
+ ["Cancellation requested", "is-warning"] :
36
+ (statusPresentation[control.status] || [control.status, "is-light"]);
37
+
38
+ return createElement("span", { className: `tag ${className}`, text: label });
39
+ };
40
+
41
+ const addTableRow = (body, label, value) => {
42
+ const row = document.createElement("tr");
43
+ const heading = createElement("th", { text: label });
44
+ const detail = document.createElement("td");
45
+ if (typeof value === "string") detail.textContent = value;
46
+ else detail.appendChild(value);
47
+ row.append(heading, detail);
48
+ body.appendChild(row);
49
+ };
50
+
51
+ const cancellationForm = (endpoint) => {
52
+ const form = document.createElement("form");
53
+ form.method = "post";
54
+ form.action = `${endpoint}/cancel`;
55
+
56
+ const csrfToken = document.querySelector("meta[name=csrf-token]")?.content;
57
+ if (csrfToken) {
58
+ const input = document.createElement("input");
59
+ input.type = "hidden";
60
+ input.name = "authenticity_token";
61
+ input.value = csrfToken;
62
+ form.appendChild(input);
63
+ }
64
+
65
+ const button = createElement("button", {
66
+ className: "button is-warning is-light",
67
+ text: "Request cancellation"
68
+ });
69
+ button.type = "submit";
70
+ button.addEventListener("click", (event) => {
71
+ if (!window.confirm("Request cooperative cancellation for this job?")) event.preventDefault();
72
+ });
73
+ form.appendChild(button);
74
+ return form;
75
+ };
76
+
77
+ const cancellationAction = (endpoint) => {
78
+ const action = createElement("div", { className: "is-flex is-align-items-center is-flex-wrap-wrap" });
79
+ const hint = createElement("span", {
80
+ className: "has-text-grey is-size-7 ml-3",
81
+ text: "Takes effect at the next checkpoint."
82
+ });
83
+ action.append(cancellationForm(endpoint), hint);
84
+ return action;
85
+ };
86
+
87
+ const controlSection = (control, endpoint) => {
88
+ const section = document.createElement("section");
89
+ section.id = sectionId;
90
+
91
+ const title = createElement("h2", { className: "subtitle", text: "Job control" });
92
+ const table = createElement("table", { className: "table" });
93
+ const body = document.createElement("tbody");
94
+
95
+ addTableRow(body, "Control status", statusTag(control));
96
+ addTableRow(body, "Heartbeat", control.heartbeat_at || "Not reported");
97
+ addTableRow(body, "Last checkpoint", control.last_checkpoint_at || "Not reported");
98
+ if (control.cancellable) addTableRow(body, "Actions", cancellationAction(endpoint));
99
+
100
+ table.appendChild(body);
101
+ section.append(title, table);
102
+ return section;
103
+ };
104
+
105
+ const render = async () => {
106
+ if (document.getElementById(sectionId)) return;
107
+
108
+ const jobId = currentJobId();
109
+ const container = detailContainer();
110
+ const generalInformation = container.querySelector("table.table");
111
+ if (!jobId || !generalInformation) return;
112
+
113
+ try {
114
+ const endpoint = controlEndpoint(jobId);
115
+ const control = await requestControl(endpoint);
116
+ if (control && !document.getElementById(sectionId)) {
117
+ generalInformation.insertAdjacentElement("afterend", controlSection(control, endpoint));
118
+ }
119
+ } catch (_error) {
120
+ }
121
+ };
122
+
123
+ document.addEventListener("DOMContentLoaded", render);
124
+ document.addEventListener("turbo:load", render);
125
+ })();
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ module Integrations
5
+ module MissionControlJobs
6
+ # Loads the browser client injected into Mission Control responses.
7
+ module ClientScript
8
+ module_function
9
+
10
+ def source
11
+ File.read(File.join(__dir__, "client.js"))
12
+ end
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ require_relative "client_script"
6
+
7
+ module JobControl
8
+ module Integrations
9
+ module MissionControlJobs
10
+ # Adds the JobControl client without replacing Mission Control templates.
11
+ class Middleware
12
+ def initialize(app)
13
+ @app = app
14
+ end
15
+
16
+ def call(environment)
17
+ status, headers, body = @app.call(environment)
18
+ return [status, headers, body] unless inject?(status, headers)
19
+
20
+ response = +""
21
+ body.each { |chunk| response << chunk }
22
+ body.close if body.respond_to?(:close)
23
+ headers.delete("content-length")
24
+ [status, headers, [inject(response, environment)]]
25
+ end
26
+
27
+ private
28
+
29
+ def inject?(status, headers)
30
+ status == 200 && headers.fetch("content-type", "").start_with?("text/html")
31
+ end
32
+
33
+ def inject(response, environment)
34
+ configuration = JSON.generate(endpoint_prefix: MissionControlJobs.endpoint_prefix)
35
+ nonce = nonce_attribute(environment)
36
+ scripts = [
37
+ "<script#{nonce}>window.JobControlMissionControl=#{configuration};</script>",
38
+ "<script#{nonce}>#{ClientScript.source}</script>"
39
+ ].join
40
+ response.sub(%r{</head>}i, "#{scripts}</head>")
41
+ end
42
+
43
+ def nonce_attribute(environment)
44
+ nonce = environment["action_dispatch.content_security_policy_nonce"]
45
+ nonce ? " nonce=\"#{ERB::Util.html_escape(nonce)}\"" : ""
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "mission_control_jobs/middleware"
4
+
5
+ module JobControl
6
+ module Integrations
7
+ # Optional UI and cancellation endpoint for Mission Control Jobs 1.x.
8
+ module MissionControlJobs
9
+ ROUTE_NAME = :job_control_mission_control_cancel
10
+ SUPPORTED_VERSIONS = Gem::Requirement.new(">= 1.3", "< 2.0").freeze
11
+
12
+ class << self
13
+ attr_reader :mount_path
14
+
15
+ def install!(mount_path: "/admin/jobs")
16
+ verify_dependency!
17
+ requested_mount_path = normalize_mount_path(mount_path)
18
+
19
+ if @route_installed && @mount_path != requested_mount_path
20
+ raise ConfigurationError, "Mission Control integration is already installed at #{@mount_path}"
21
+ end
22
+
23
+ @mount_path = requested_mount_path
24
+ install_middleware!
25
+ install_routes!
26
+ end
27
+
28
+ def endpoint_prefix = "#{mount_path}/job_controls"
29
+
30
+ private
31
+
32
+ def install_middleware!
33
+ return if @middleware_installed
34
+
35
+ ::MissionControl::Jobs::Engine.middleware.use Middleware
36
+ @middleware_installed = true
37
+ end
38
+
39
+ def install_routes!
40
+ return if @route_installed
41
+
42
+ Rails.application.routes.append do
43
+ get "#{JobControl::Integrations::MissionControlJobs.endpoint_prefix}/:job_id",
44
+ to: "job_control/mission_control_jobs#show", as: :job_control_mission_control
45
+ post "#{JobControl::Integrations::MissionControlJobs.endpoint_prefix}/:job_id/cancel",
46
+ to: "job_control/mission_control_jobs#cancel", as: ROUTE_NAME
47
+ end
48
+ @route_installed = true
49
+ end
50
+
51
+ def normalize_mount_path(path)
52
+ value = path.to_s.sub(%r{/\z}, "")
53
+ raise ArgumentError, "mount_path must not be empty" if value.empty?
54
+
55
+ value.start_with?("/") ? value : "/#{value}"
56
+ end
57
+
58
+ def verify_dependency!
59
+ unless defined?(::MissionControl::Jobs::Engine)
60
+ raise LoadError, "JobControl Mission Control integration requires the mission_control-jobs gem to be loaded"
61
+ end
62
+
63
+ return if SUPPORTED_VERSIONS.satisfied_by?(Gem::Version.new(::MissionControl::Jobs::VERSION))
64
+
65
+ raise ConfigurationError,
66
+ "JobControl Mission Control integration supports mission_control-jobs #{SUPPORTED_VERSIONS}"
67
+ end
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+
5
+ module JobControl
6
+ # Active Job lifecycle callbacks and runtime primitives.
7
+ module Job
8
+ extend ActiveSupport::Concern
9
+
10
+ included do
11
+ before_enqueue { |job| JobControl.register(job.job_id) }
12
+
13
+ around_perform do |job, perform|
14
+ control = JobControl.register(job.job_id)
15
+ control.mark_running!
16
+
17
+ begin
18
+ control.checkpoint!
19
+ perform.call
20
+ control.reload.mark_succeeded!
21
+ rescue Cancelled
22
+ control.reload.mark_cancelled!
23
+ rescue StandardError
24
+ safely_mark_failed(control)
25
+ raise
26
+ end
27
+ end
28
+ end
29
+
30
+ def control = (@control ||= JobControl.find(job_id))
31
+ def checkpoint! = control.checkpoint!
32
+ def cancellation = (@cancellation ||= Cancellation.new(control))
33
+
34
+ private
35
+
36
+ def safely_mark_failed(control)
37
+ control.reload
38
+ return if control.cancel_requested?
39
+
40
+ control.mark_failed!
41
+ rescue ActiveRecord::ActiveRecordError
42
+ # Preserve the application's exception when state persistence is unavailable.
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module JobControl
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/notifications"
5
+ require "active_support/core_ext/numeric/time"
6
+ require "active_record"
7
+ require "active_job"
8
+
9
+ require_relative "job_control/version"
10
+ require_relative "job_control/cancelled"
11
+ require_relative "job_control/configuration"
12
+ require_relative "job_control/cancellation"
13
+ require_relative "job_control/control"
14
+ require_relative "job_control/job"
15
+ require_relative "job_control/engine" if defined?(Rails::Engine)
16
+
17
+ # Runtime controls for long-running Active Job jobs.
18
+ module JobControl
19
+ class Error < StandardError; end
20
+ class ConfigurationError < Error; end
21
+
22
+ class << self
23
+ def configuration
24
+ @configuration ||= Configuration.new
25
+ end
26
+
27
+ def configure
28
+ yield(configuration)
29
+ configuration
30
+ end
31
+
32
+ def find(job_id) = Control.find_by!(job_id: job_id)
33
+ def cancel(job_id) = find(job_id).cancel!
34
+ def register(job_id) = Control.create_or_find_by!(job_id: job_id)
35
+
36
+ def instrument(event, control)
37
+ ActiveSupport::Notifications.instrument("job_control.#{event}", control: control)
38
+ end
39
+ end
40
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: job_control
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Manh Kha
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: activejob
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '8.1'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9.0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '8.1'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9.0'
32
+ - !ruby/object:Gem::Dependency
33
+ name: activerecord
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: '8.1'
39
+ - - "<"
40
+ - !ruby/object:Gem::Version
41
+ version: '9.0'
42
+ type: :runtime
43
+ prerelease: false
44
+ version_requirements: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '8.1'
49
+ - - "<"
50
+ - !ruby/object:Gem::Version
51
+ version: '9.0'
52
+ description: Cancellation, progress, checkpoints, heartbeats, and lifecycle tracking
53
+ for Active Job.
54
+ email:
55
+ - kha.manhthai@wogi.biz
56
+ executables: []
57
+ extensions: []
58
+ extra_rdoc_files: []
59
+ files:
60
+ - CHANGELOG.md
61
+ - LICENSE.txt
62
+ - README.md
63
+ - app/controllers/job_control/mission_control_jobs_controller.rb
64
+ - config/locales/job_control.en.yml
65
+ - db/migrate/20260924000000_create_job_controls.rb
66
+ - lib/generators/job_control/install/install_generator.rb
67
+ - lib/job_control.rb
68
+ - lib/job_control/adapters/solid_queue.rb
69
+ - lib/job_control/cancellation.rb
70
+ - lib/job_control/cancelled.rb
71
+ - lib/job_control/configuration.rb
72
+ - lib/job_control/control.rb
73
+ - lib/job_control/engine.rb
74
+ - lib/job_control/integrations/mission_control_jobs.rb
75
+ - lib/job_control/integrations/mission_control_jobs/client.js
76
+ - lib/job_control/integrations/mission_control_jobs/client_script.rb
77
+ - lib/job_control/integrations/mission_control_jobs/middleware.rb
78
+ - lib/job_control/job.rb
79
+ - lib/job_control/version.rb
80
+ homepage: https://github.com/kha-wogi/job_control
81
+ licenses:
82
+ - MIT
83
+ metadata:
84
+ source_code_uri: https://github.com/kha-wogi/job_control
85
+ changelog_uri: https://github.com/kha-wogi/job_control/blob/main/CHANGELOG.md
86
+ rubygems_mfa_required: 'true'
87
+ rdoc_options: []
88
+ require_paths:
89
+ - lib
90
+ required_ruby_version: !ruby/object:Gem::Requirement
91
+ requirements:
92
+ - - ">="
93
+ - !ruby/object:Gem::Version
94
+ version: 3.2.0
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: '0'
100
+ requirements: []
101
+ rubygems_version: 4.0.6
102
+ specification_version: 4
103
+ summary: Cooperative runtime control for long-running Active Job jobs
104
+ test_files: []