Class: RubynCode::Background::Worker
- Inherits:
-
Object
- Object
- RubynCode::Background::Worker
- Defined in:
- lib/rubyn_code/background/worker.rb
Overview
Runs shell commands in background threads with configurable timeouts. Thread-safe job tracking with a hard cap on concurrency.
Constant Summary collapse
- MAX_CONCURRENT =
5
Instance Method Summary collapse
-
#active_count ⇒ Integer
Returns the number of currently running jobs.
-
#drain_notifications ⇒ Array
Delegates to the notifier to drain all pending notifications.
-
#initialize(project_root:, notifier: Notifier.new) ⇒ Worker
constructor
A new instance of Worker.
-
#run(command, timeout: 120) ⇒ String
Spawns a background thread to run the given command.
-
#shutdown!(timeout: 30) ⇒ void
Waits for all running threads to finish.
-
#status(job_id) ⇒ Job?
Returns the current state of a job.
Constructor Details
#initialize(project_root:, notifier: Notifier.new) ⇒ Worker
Returns a new instance of Worker.
18 19 20 21 22 23 24 |
# File 'lib/rubyn_code/background/worker.rb', line 18 def initialize(project_root:, notifier: Notifier.new) @project_root = File.(project_root) @notifier = notifier @jobs = {} @threads = {} @mutex = Mutex.new end |
Instance Method Details
#active_count ⇒ Integer
Returns the number of currently running jobs.
78 79 80 81 82 |
# File 'lib/rubyn_code/background/worker.rb', line 78 def active_count @mutex.synchronize do @jobs.count { |_, j| j.running? } end end |
#drain_notifications ⇒ Array
Delegates to the notifier to drain all pending notifications.
71 72 73 |
# File 'lib/rubyn_code/background/worker.rb', line 71 def drain_notifications @notifier.drain end |
#run(command, timeout: 120) ⇒ String
Spawns a background thread to run the given command.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/rubyn_code/background/worker.rb', line 32 def run(command, timeout: 120) job_id = SecureRandom.uuid @mutex.synchronize do running = @jobs.count { |_, j| j.running? } if running >= MAX_CONCURRENT raise "Concurrency limit reached (#{MAX_CONCURRENT} jobs running). Wait for a job to finish." end job = Job.new( id: job_id, command: command, status: :running, result: nil, started_at: Time.now, completed_at: nil ) @jobs[job_id] = job end thread = Thread.new { execute_job(job_id, command, timeout) } thread.abort_on_exception = false @mutex.synchronize { @threads[job_id] = thread } job_id end |
#shutdown!(timeout: 30) ⇒ void
This method returns an undefined value.
Waits for all running threads to finish. Intended for graceful shutdown.
88 89 90 91 |
# File 'lib/rubyn_code/background/worker.rb', line 88 def shutdown!(timeout: 30) threads = @mutex.synchronize { @threads.values.dup } threads.each { |t| t.join(timeout) } end |
#status(job_id) ⇒ Job?
Returns the current state of a job.
64 65 66 |
# File 'lib/rubyn_code/background/worker.rb', line 64 def status(job_id) @mutex.synchronize { @jobs[job_id] } end |