Class: RailsPodKit::Supervisor

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_pod_kit/supervisor.rb

Overview

Keeps a background worker alive on a process that must not lose it.

Both schedulers the gem hosts (SolidQueue's, and sidekiq-cron's) run on their own thread inside an always-on process, and both share the same failure mode: the thread dies, the host process notices nothing, and the schedule stops silently. This is that supervision, once — a timer that rebuilds the worker as soon as it stops being alive.

The three things that genuinely differ between workers are injected: how to build and start one, how to ask whether it is still alive, and how to wind it down. Everything else — the immediate first tick, the stop latch that keeps a shutdown from being undone by a tick already in flight, reporting instead of dying — is identical and lives here.

Deliberately free of Rails: the sidekiq-cron scheduler runs in a Rails-free process, and ErrorReporter degrades to a warning where there is no Rails error reporter to hand the failure to.

Constant Summary collapse

DEFAULT_INTERVAL =
30

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source:, start:, alive:, stop: nil, interval: DEFAULT_INTERVAL) ⇒ Supervisor

start: is a callable returning the started worker. alive: and stop: take either a method name to send to that worker or a callable receiving it, so the common case stays declarative and a liveness check the worker does not expose itself is still expressible. stop: is optional — a worker with no teardown is simply dropped.



35
36
37
38
39
40
41
42
# File 'lib/rails_pod_kit/supervisor.rb', line 35

def initialize(source:, start:, alive:, stop: nil, interval: DEFAULT_INTERVAL)
  @source = source
  @start = start
  @alive = alive
  @stop = stop
  @interval = interval
  @stopping = false
end

Instance Attribute Details

#subjectObject (readonly)

Returns the value of attribute subject.



28
29
30
# File 'lib/rails_pod_kit/supervisor.rb', line 28

def subject
  @subject
end

Instance Method Details

#running?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/rails_pod_kit/supervisor.rb', line 63

def running?
  !!@subject && invoke(@alive, @subject)
end

#startObject

Starts the timer, which starts the worker on its first (immediate) tick, and returns without blocking.



46
47
48
49
50
51
# File 'lib/rails_pod_kit/supervisor.rb', line 46

def start
  @stopping = false
  @timer = ::Concurrent::TimerTask.new(execution_interval: @interval, run_now: true) { supervise }
  @timer.execute
  self
end

#stopObject

Graceful stop: drop the timer first so it cannot resurrect the worker, then wind the worker down rather than leaving it to be cut off.



55
56
57
58
59
60
61
# File 'lib/rails_pod_kit/supervisor.rb', line 55

def stop
  @stopping = true
  @timer&.shutdown
  @timer = nil
  invoke(@stop, @subject) if @subject && @stop
  @subject = nil
end