good_job-async_executor 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.
@@ -0,0 +1,21 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module GoodJob
5
+ module AsyncExecutor
6
+ # Prepended to `GoodJob::LogSubscriber`, so the "started scheduler" line of a fiber pool shows its shape
7
+ # (`queues=io max_fibers=500 reactors=5`) instead of `max_threads=500`.
8
+ module LogSubscriberExtension
9
+ #: (ActiveSupport::Notifications::Event) -> void
10
+ def scheduler_create_pool(event)
11
+ payload = event.payload
12
+ return super unless payload[:reactors]
13
+
14
+ info(tags: [payload[:process_id]]) do
15
+ "GoodJob #{GoodJob::VERSION} started scheduler with queues=#{payload[:performer_name]} " \
16
+ "max_fibers=#{payload[:max_threads]} reactors=#{payload[:reactors]}."
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,92 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'delegate'
5
+ require 'good_job/async_executor/errors'
6
+ require 'good_job/async_executor/queue_segment'
7
+
8
+ module GoodJob
9
+ module AsyncExecutor
10
+ # Prepended to `GoodJob::MultiScheduler`'s singleton class. Reads each `;` segment's count as a `QueueShape`
11
+ # before GoodJob does, so `Mf` and `NxMf` become fiber pools instead of being read by `to_i` as thread counts.
12
+ #
13
+ # GoodJob still builds every scheduler itself, from the queue string with each fiber count replaced by its total
14
+ # (`io:5x100f` becomes `io:500`). Each fiber segment's shape reaches its `Scheduler.new` as `async_shape:`: GoodJob
15
+ # builds the schedulers in segment order, in this fiber, so they take the shapes in that order (see
16
+ # `SchedulerExtension#initialize`), each checked against its scheduler's queues.
17
+ module MultiSchedulerExtension
18
+ PENDING_SHAPES = :good_job_async_executor_pending_shapes
19
+
20
+ # The queue string GoodJob parses, with every fiber count replaced by its total.
21
+ class ShapedConfiguration < SimpleDelegator
22
+ #: (GoodJob::Configuration, String) -> void
23
+ def initialize(configuration, queue_string)
24
+ super(configuration)
25
+ @queue_string = queue_string
26
+ end
27
+
28
+ #: () -> String
29
+ def flattened_queue_string
30
+ @queue_string
31
+ end
32
+
33
+ #: String
34
+ attr_reader :queue_string
35
+ end
36
+
37
+ class << self
38
+ # Runs the block with one `[queue name, shape]` pair pending per segment (nil shape for thread segments), for
39
+ # the schedulers GoodJob builds in this fiber to take in order. Raises if any is left untaken. An outer call's
40
+ # pairs are put back afterwards.
41
+ #
42
+ #: [T] (Array[[String?, QueueShape?]]) { () -> T } -> T
43
+ def with_pending_shapes(pairs)
44
+ outer = Thread.current[PENDING_SHAPES]
45
+ Thread.current[PENDING_SHAPES] = pairs.dup
46
+ result = yield
47
+ left = Thread.current[PENDING_SHAPES]
48
+ if left.any?
49
+ raise Error, "GoodJob built no scheduler for queues=#{left.map(&:first).join(', ')}, so its fiber shape " \
50
+ 'was not applied'
51
+ end
52
+ result
53
+ ensure
54
+ Thread.current[PENDING_SHAPES] = outer
55
+ end
56
+
57
+ # The shape for the scheduler GoodJob is building for `queue_name`, while `with_pending_shapes` runs; nil
58
+ # otherwise. Raises if GoodJob builds its schedulers in any other order than the segments, rather than give a
59
+ # fiber shape to the wrong one (or none, silently running a fiber segment on threads).
60
+ #
61
+ #: (String?) -> QueueShape?
62
+ def take_pending_shape(queue_name)
63
+ pending = Thread.current[PENDING_SHAPES] or return
64
+
65
+ if pending.empty?
66
+ raise Error, "GoodJob built more schedulers than segments, the last for queues=#{queue_name}"
67
+ end
68
+
69
+ expected_queue_name, shape = pending.shift
70
+ unless expected_queue_name == queue_name
71
+ raise Error, "GoodJob built a scheduler for queues=#{queue_name.inspect} where " \
72
+ "queues=#{expected_queue_name.inspect} was expected, so fiber shapes would be misapplied"
73
+ end
74
+
75
+ shape
76
+ end
77
+ end
78
+
79
+ #: (GoodJob::Configuration, **untyped) -> GoodJob::MultiScheduler
80
+ def from_configuration(configuration, **)
81
+ segments = QueueSegment.all(configuration)
82
+ return super unless segments.any? { |segment| segment.shape.fibers? }
83
+
84
+ queue_string = segments.map(&:shaped).join(';')
85
+ pairs = segments.map { |segment| [segment.queue_name, (segment.shape if segment.shape.fibers?)] }
86
+ MultiSchedulerExtension.with_pending_shapes(pairs) do
87
+ super(ShapedConfiguration.new(configuration, queue_string), **)
88
+ end
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,61 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'active_support/core_ext/object/blank'
5
+ require 'good_job/async_executor/queue_shape'
6
+
7
+ module GoodJob
8
+ module AsyncExecutor
9
+ # One `;` segment of the queue string GoodJob builds this process's schedulers from, read as GoodJob reads it: the
10
+ # whole segment (`source`), its queue list before the first `:` (`queue_name`, as GoodJob names the scheduler's
11
+ # performer) and its count as a `QueueShape`.
12
+ #
13
+ # The one parser behind both `MultiSchedulerExtension` and the sizing helpers (`AsyncExecutor.worker_pools`), so
14
+ # what they report can never differ from what is built.
15
+ QueueSegment = Data.define(:source, :queue_name, :shape) do
16
+ class << self
17
+ # Every segment, in the order GoodJob builds their schedulers. Pipe-delimited subprocess pools are flattened,
18
+ # as GoodJob's `MultiScheduler` flattens them in-process.
19
+ #
20
+ #: (GoodJob::Configuration) -> Array[QueueSegment]
21
+ def all(configuration)
22
+ queue_string(configuration).split(';').map(&:strip).map { |segment| parse(segment, configuration) }
23
+ end
24
+
25
+ private
26
+
27
+ #: (GoodJob::Configuration) -> String
28
+ def queue_string(configuration)
29
+ if configuration.respond_to?(:flattened_queue_string)
30
+ configuration.flattened_queue_string
31
+ else
32
+ configuration.queue_string
33
+ end
34
+ end
35
+
36
+ #: (String, GoodJob::Configuration) -> QueueSegment
37
+ def parse(segment, configuration)
38
+ queue_name, count = segment.split(':').values_at(0, 1).map { |part| part&.strip.presence }
39
+ # `max_threads` exists in every supported GoodJob version (later ones alias it to `threads`).
40
+ default_threads = configuration.max_threads
41
+ begin
42
+ shape = QueueShape.parse(count, default_threads:)
43
+ rescue ArgumentError => error
44
+ raise ArgumentError, "Invalid queue segment #{segment.inspect}: #{error.message}"
45
+ end
46
+ new(source: segment, queue_name:, shape:)
47
+ end
48
+ end
49
+
50
+ # The segment as GoodJob should see it: a fiber count is replaced by its total (`io:5x100f` becomes `io:500`), so
51
+ # GoodJob sizes the scheduler for every fiber. Thread segments are unchanged.
52
+ #
53
+ #: () -> String
54
+ def shaped
55
+ return source unless shape.fibers?
56
+
57
+ "#{queue_name}:#{shape.max_concurrency}"
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,71 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'active_support/core_ext/object/blank'
5
+
6
+ module GoodJob
7
+ module AsyncExecutor
8
+ # How a queue group runs jobs: on plain threads, or as fibers across one or more reactor threads.
9
+ #
10
+ # Parsed from GoodJob's queue count string: `"5"` is five threads, `"500f"` is 500 fibers on one reactor and
11
+ # `"5x100f"` is 100 fibers on each of five reactors.
12
+ class QueueShape < Data.define(:threads, :reactors, :fibers_per_reactor)
13
+ # Case-insensitive, so `100F` is refused too rather than read by `to_i` as 100 threads.
14
+ FIBER_SUFFIX = /\A\s*(?:\d+x)?\d+f\s*\z/i
15
+ SHAPE = /\A(?:(?<threads>\d+)|(?:(?<reactors>\d+)x)?(?<fibers>\d+)f)\z/
16
+
17
+ class << self
18
+ #: (String?, default_threads: Integer) -> QueueShape
19
+ def parse(count_string, default_threads:)
20
+ return new(threads: default_threads, reactors: nil, fibers_per_reactor: nil) if count_string.blank?
21
+
22
+ match = SHAPE.match(count_string) or raise ArgumentError, "Invalid queue shape: #{count_string.inspect}"
23
+
24
+ build(match, count_string)
25
+ end
26
+
27
+ # Fiber suffixes only make sense in a queue string, so settings that take a plain number reject them.
28
+ #
29
+ #: (untyped, setting: String) -> nil
30
+ def reject_fiber_suffix!(value, setting:)
31
+ return unless FIBER_SUFFIX.match?(value.to_s)
32
+
33
+ raise ArgumentError, "#{setting} does not support fiber counts: #{value.inspect}"
34
+ end
35
+
36
+ private
37
+
38
+ #: (MatchData, String) -> QueueShape
39
+ def build(match, input)
40
+ if match[:threads]
41
+ threads = Integer(match[:threads], 10)
42
+ unless threads.positive?
43
+ raise ArgumentError,
44
+ "Invalid queue shape: #{input.inspect} (must be greater than zero)"
45
+ end
46
+
47
+ return new(threads:, reactors: nil, fibers_per_reactor: nil)
48
+ end
49
+
50
+ reactors = match[:reactors] ? Integer(match[:reactors], 10) : 1
51
+ fibers = Integer(match[:fibers], 10)
52
+ unless reactors.positive? && fibers.positive?
53
+ raise ArgumentError, "Invalid queue shape: #{input.inspect} (must be greater than zero)"
54
+ end
55
+
56
+ new(threads: nil, reactors:, fibers_per_reactor: fibers)
57
+ end
58
+ end
59
+
60
+ #: () -> bool
61
+ def fibers?
62
+ !reactors.nil?
63
+ end
64
+
65
+ #: () -> Integer
66
+ def max_concurrency
67
+ fibers? ? reactors * fibers_per_reactor : threads
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,173 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module GoodJob
5
+ module AsyncExecutor
6
+ class Reactor
7
+ # A reactor's side of development reloading (see `ReloadGate`): the reload lock it holds while tasks run, its
8
+ # drains, and handing it over to a replacement when a drain's task will not stop. Without a gate, only the task
9
+ # count is kept.
10
+ module Draining
11
+ # When the current drain for a reload started (monotonic seconds), or nil when not draining.
12
+ #
13
+ #: () -> Float?
14
+ def draining_since
15
+ @draining_since.get
16
+ end
17
+
18
+ # Starts draining for a reload, as the reactor does itself before starting a task, for a reactor that cannot
19
+ # check (its running task never yields). Returns when the current drain started.
20
+ #
21
+ #: () -> Float
22
+ def begin_drain
23
+ @draining_since.compare_and_set(nil, monotonic_now)
24
+ @draining_since.get
25
+ end
26
+
27
+ # Sends `Async::Stop` to every running task, if the drain that started at `since` is still going, and keeps
28
+ # the reactor running. A task receives the stop at its next yield.
29
+ #
30
+ #: (Float) -> void
31
+ def stop_draining_tasks(since)
32
+ @control << [:stop_draining_tasks, since]
33
+ end
34
+
35
+ # Readies the reactor to be killed and replaced, if the drain that started at `since` is still waiting on a
36
+ # running task: it starts nothing more, keeps the tasks it has not started for `take_queued` instead of dropping
37
+ # them, and stops its tasks as `stop_tasks` does. The stop matters even though the thread is about to be killed:
38
+ # a killed fiber whose `ensure` yields (eg. for a query) can swallow the kill, leaving the thread running the
39
+ # event loop with nothing to end it.
40
+ #
41
+ # False, changing nothing, once that drain's tasks have all finished, or while the reactor reloads: stopping or
42
+ # killing it then could cut a reload short in the middle of unloading.
43
+ #
44
+ #: (Float) -> bool
45
+ def hand_over_if_stuck!(since) # rubocop:disable Naming/PredicateMethod
46
+ @replacement_lock.synchronize do
47
+ return false if @reloading || !busy? || @draining_since.get != since
48
+
49
+ @handing_over.make_true
50
+ end
51
+ stop_tasks
52
+ true
53
+ end
54
+
55
+ # Whether the reactor is reloading right now.
56
+ #
57
+ #: () -> bool
58
+ def reloading?
59
+ @replacement_lock.synchronize { @reloading }
60
+ end
61
+
62
+ # Waits, for at most `timeout` seconds, while the reactor reloads. True once it is not reloading.
63
+ #
64
+ #: (Float | Integer) -> bool
65
+ def wait_while_reloading(timeout) # rubocop:disable Naming/PredicateMethod
66
+ deadline = monotonic_now + timeout
67
+ sleep 0.01 while reloading? && monotonic_now < deadline
68
+ !reloading?
69
+ end
70
+
71
+ private
72
+
73
+ #: () -> void
74
+ def initialize_draining
75
+ # When the current drain for a reload started (monotonic seconds), or nil.
76
+ @draining_since = Concurrent::AtomicReference.new
77
+ @handing_over = Concurrent::AtomicBoolean.new
78
+ # Held briefly to decide, atomically, between reloading and being handed over to a replacement.
79
+ @replacement_lock = Thread::Mutex.new
80
+ @reloading = false
81
+ # Set by `stop_tasks`: no reload starts after it.
82
+ @stopping = Concurrent::AtomicBoolean.new
83
+ end
84
+
85
+ # Starts nothing until every running task has finished (their `ensure` gives the reload lock back on the last
86
+ # one), then reloads. The executor stops tasks that take too long.
87
+ #
88
+ #: () -> void
89
+ def drain_and_reload
90
+ @draining_since.compare_and_set(nil, monotonic_now)
91
+ gate = @reload_gate
92
+ gate.draining do
93
+ begin
94
+ gate.instrument_drain(name) { wait_until { @active.value.zero? } }
95
+ rescue StandardError => error
96
+ # A failing subscriber must neither end the reactor nor cut the drain short.
97
+ report(error)
98
+ end
99
+ wait_until { @active.value.zero? }
100
+ reload_unless_leaving(gate)
101
+ end
102
+ ensure
103
+ @draining_since.set(nil)
104
+ end
105
+
106
+ # Reloads, unless the reactor is being handed over or stopped (decided atomically with them).
107
+ #
108
+ #: (untyped) -> void
109
+ def reload_unless_leaving(gate)
110
+ return unless @replacement_lock.synchronize { @reloading = !leaving? }
111
+
112
+ begin
113
+ gate.reload!
114
+ rescue StandardError => error
115
+ report(error)
116
+ ensure
117
+ @replacement_lock.synchronize { @reloading = false }
118
+ @reload_done.signal
119
+ end
120
+ end
121
+
122
+ # Whether the reactor is being handed over to a replacement or stopped for kill, so starts nothing more.
123
+ #
124
+ #: () -> bool
125
+ def leaving?
126
+ @handing_over.true? || @stopping.true?
127
+ end
128
+
129
+ # The gate's check for a pending reload. One that fails (eg. a file deleted while Rails' watcher scans) is
130
+ # reported and counts as nothing pending, so the reactor carries on.
131
+ #
132
+ #: () -> bool
133
+ def reload_pending?
134
+ @reload_gate.reload_pending?
135
+ rescue StandardError => error
136
+ report(error)
137
+ false
138
+ end
139
+
140
+ # Counts a task as running, taking the reload lock for the reactor thread if it is the first. Waits while
141
+ # another thread unloads.
142
+ #
143
+ #: () -> void
144
+ def take_reload_share
145
+ @reload_gate.start_running if @reload_gate && @active.value.zero?
146
+ @active.increment
147
+ end
148
+
149
+ # Counts a task as finished, giving the reload lock back if it was the last.
150
+ #
151
+ #: () -> void
152
+ def finish_task
153
+ @reload_gate.done_running if @active.decrement.zero? && @reload_gate
154
+ @finished&.signal
155
+ end
156
+
157
+ # Gives back whatever this thread still holds of the reload lock, however the reactor ended. Nothing else can.
158
+ #
159
+ #: () -> void
160
+ def release_reload_lock
161
+ @reload_gate&.release_thread
162
+ rescue Exception => error # rubocop:disable Lint/RescueException
163
+ report(error)
164
+ end
165
+
166
+ #: () -> Float
167
+ def monotonic_now
168
+ ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
169
+ end
170
+ end
171
+ end
172
+ end
173
+ end