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,319 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'async'
5
+ require 'async/condition'
6
+ require 'concurrent'
7
+ require 'good_job/async_executor/reactor/draining'
8
+
9
+ module GoodJob
10
+ module AsyncExecutor
11
+ # One thread running a `Sync` reactor that takes tasks from a thread-safe queue and runs each as an Async task,
12
+ # with at most `size` running at once.
13
+ #
14
+ # A task counts against the reactor's slots from `enqueue` until it finishes, so a queued task and a running task
15
+ # are never counted twice and never missed in between.
16
+ #
17
+ # It ends in up to three steps, as the executor needs: `stop` drains it, `stop_tasks` interrupts its tasks at their
18
+ # next yield, and `abandon` kills its thread for tasks that never yield.
19
+ #
20
+ # With a `reload_gate` (development code reloading, see `ReloadGate`), the reactor thread holds the reload lock in
21
+ # shared mode while it has a task running. Before starting each task it checks for a pending reload; if there is
22
+ # one, it starts nothing more until its running tasks have finished, gives the lock back, and reloads. Without a
23
+ # gate it never touches the reload lock.
24
+ class Reactor
25
+ include Draining
26
+
27
+ # Pushed onto the queue by `stop`: the reactor starts nothing after it and exits once its tasks finish.
28
+ STOP = Object.new.freeze
29
+
30
+ # Set on every reactor thread, so code running there (eg. `ConnectionCleanup`) can tell it apart.
31
+ THREAD_VARIABLE = :good_job_async_executor_reactor
32
+
33
+ #: String
34
+ attr_reader :name
35
+
36
+ # `on_crash` is called with the reactor, from its dying thread, once it has exited because its loop failed (not
37
+ # when stopped, stopped for kill, handed over or abandoned).
38
+ #
39
+ # @rbs name: String
40
+ # @rbs size: Integer
41
+ # @rbs on_error: ^(Exception) -> void
42
+ # @rbs reload_gate: untyped
43
+ # @rbs on_crash: (^(Reactor) -> void)?
44
+ # @rbs return: void
45
+ def initialize(name:, size:, on_error:, reload_gate: nil, on_crash: nil)
46
+ @name = name
47
+ @size = size
48
+ @on_error = on_error
49
+ @on_crash = on_crash
50
+ @reload_gate = reload_gate
51
+ @queue = Thread::Queue.new
52
+ @in_flight = Concurrent::AtomicFixnum.new(0)
53
+ # Tasks started and not yet finished. Only the reactor thread changes it.
54
+ @active = Concurrent::AtomicFixnum.new(0)
55
+ @control = Thread::Queue.new
56
+ @running = [] #: Array[Fiber]
57
+ @running_lock = Thread::Mutex.new
58
+ @tasks = Set.new #: Set[Async::Task]
59
+ # The task taken off the queue and not started yet.
60
+ @pending = nil #: [Proc, Array[untyped]]?
61
+ initialize_draining
62
+ @abandoning = Concurrent::AtomicBoolean.new
63
+ # Set once the reactor counts as exited: when `run` ends, or, for an abandoned reactor, once its hook is done.
64
+ @exited = Concurrent::Event.new
65
+ # The process the thread runs in. A forked child has none of its threads, so there the reactor counts as exited.
66
+ @pid = ::Process.pid
67
+ @thread = Thread.new { run(name) }
68
+ end
69
+
70
+ # Slots not taken by a running or queued task. Negative when more tasks are queued than the reactor can start.
71
+ #
72
+ #: () -> Integer
73
+ def free_slots
74
+ @size - @in_flight.value
75
+ end
76
+
77
+ # Whether the reactor already has as many tasks waiting as it can run, on top of a full set running. Like
78
+ # GoodJob's thread pool (`max_queue` = `max_threads`, discard on overflow), a full reactor takes no more tasks.
79
+ #
80
+ #: () -> bool
81
+ def full?
82
+ @in_flight.value >= @size * 2
83
+ end
84
+
85
+ # Whether a task is running.
86
+ #
87
+ #: () -> bool
88
+ def busy?
89
+ @active.value.positive?
90
+ end
91
+
92
+ # Whether a task is waiting to start.
93
+ #
94
+ #: () -> bool
95
+ def queued?
96
+ @in_flight.value > @active.value
97
+ end
98
+
99
+ # Queues a task to run on this reactor. Never blocks, so it is safe to call from a fiber on any reactor.
100
+ #
101
+ #: (Proc, Array[untyped]) -> void
102
+ def enqueue(task, args)
103
+ @in_flight.increment
104
+ @queue << [task, args]
105
+ end
106
+
107
+ # Starts nothing queued after this call, and lets the thread exit once every earlier task has finished.
108
+ #
109
+ #: () -> void
110
+ def stop
111
+ @queue << STOP
112
+ end
113
+
114
+ # Sends `Async::Stop` to every running task and starts nothing more, dropping queued tasks. A task receives the
115
+ # stop at its next yield, so one that never yields keeps the reactor alive until `abandon`. A reload in progress
116
+ # is never cut short: the stop waits for it, and no reload starts after this.
117
+ #
118
+ #: () -> void
119
+ def stop_tasks
120
+ @stopping.make_true
121
+ @control << [:stop_tasks]
122
+ end
123
+
124
+ # The tasks a reactor handed over had not started, oldest first. Only for a reactor that is no longer running.
125
+ #
126
+ #: () -> Array[[Proc, Array[untyped]]]
127
+ def take_queued
128
+ jobs = [@pending].compact
129
+ until (job = @queue.pop(timeout: 0)).nil?
130
+ jobs << job unless job.equal?(STOP)
131
+ end
132
+ @pending = nil
133
+ jobs
134
+ end
135
+
136
+ # The fibers currently running a task.
137
+ #
138
+ #: () -> Array[Fiber]
139
+ def running_fibers
140
+ return [] if forked?
141
+
142
+ @running_lock.synchronize { @running.dup }
143
+ end
144
+
145
+ # Kills the thread, waits up to `grace` seconds for it to die, then yields the fibers that were running a task.
146
+ #
147
+ # The fibers are snapshotted first, since each removes itself as it unwinds. Killing the thread still runs their
148
+ # `ensure` blocks, with a working scheduler, so they may do IO and even resume other fibers; yielding only after
149
+ # the thread is dead means nothing uses what they hold while the block releases it. A thread stuck in a call
150
+ # that ignores `Thread#kill` is given up on after `grace`, so this never hangs. Only the first call does
151
+ # anything; the reactor counts as exited once the block returns.
152
+ #
153
+ #: (Float | Integer) { (Array[Fiber]) -> void } -> void
154
+ def abandon(grace)
155
+ return unless @abandoning.make_true
156
+
157
+ begin
158
+ fibers = running_fibers
159
+ @thread.kill
160
+ @thread.join(grace)
161
+ yield fibers
162
+ ensure
163
+ @exited.set
164
+ end
165
+ end
166
+
167
+ #: () -> bool
168
+ def alive?
169
+ !@exited.set? && !forked?
170
+ end
171
+
172
+ # Whether this is a forked child of the process the reactor ran in, where its thread does not exist.
173
+ #
174
+ #: () -> bool
175
+ def forked?
176
+ @pid != ::Process.pid
177
+ end
178
+
179
+ # Waits for the reactor to exit, for at most `timeout` seconds (forever when nil). Nil if it is still running. An
180
+ # abandoned reactor exits once its fibers are handed over, even if its thread never dies. In a forked child it has
181
+ # exited already.
182
+ #
183
+ #: (Float | Integer | nil) -> Thread?
184
+ def join(timeout)
185
+ @thread if forked? || @exited.wait(timeout)
186
+ end
187
+
188
+ private
189
+
190
+ # A reactor that fails reports why and exits, then calls `on_crash` so the executor can replace it.
191
+ #
192
+ #: (String) -> void
193
+ def run(name)
194
+ Thread.current.name = name
195
+ Thread.current.thread_variable_set(THREAD_VARIABLE, true)
196
+
197
+ Sync do |root|
198
+ # Signalled whenever a task finishes.
199
+ @finished = Async::Condition.new
200
+ # Signalled whenever a reload ends.
201
+ @reload_done = Async::Condition.new
202
+ # Transient, so it never keeps a drained reactor from exiting.
203
+ root.async(transient: true) { control(root) }
204
+
205
+ until @handing_over.true? || (job = @queue.pop).equal?(STOP)
206
+ start(root, *job)
207
+ end
208
+ end
209
+ rescue Exception => error # rubocop:disable Lint/RescueException
210
+ @crashed = true
211
+ report(error)
212
+ ensure
213
+ drop_queued unless @handing_over.true?
214
+ release_reload_lock
215
+ # An abandoned reactor exits only once its fibers have been handed over.
216
+ @exited.set unless @abandoning.true?
217
+ crashed if @crashed
218
+ end
219
+
220
+ # Tasks still queued when `stop_tasks` ends the loop never run. The executor refuses new tasks before it stops a
221
+ # reactor, so nothing is enqueued after this. A reactor being replaced keeps them for its successor instead.
222
+ #
223
+ #: () -> void
224
+ def drop_queued
225
+ until @queue.empty?
226
+ job = @queue.pop
227
+ @in_flight.decrement unless job.equal?(STOP)
228
+ end
229
+ end
230
+
231
+ # Tells the executor the loop failed, unless the reactor was being handed over or abandoned meanwhile.
232
+ #
233
+ #: () -> void
234
+ def crashed
235
+ return if @on_crash.nil? || @handing_over.true? || @abandoning.true?
236
+
237
+ @on_crash.call(self)
238
+ rescue Exception => error # rubocop:disable Lint/RescueException
239
+ report(error)
240
+ end
241
+
242
+ # Runs commands from other threads. Stopping the root stops every task and the loop, wherever each is waiting.
243
+ #
244
+ #: (Async::Task) -> void
245
+ def control(root)
246
+ loop do
247
+ command, since = @control.pop
248
+ case command
249
+ when :stop_tasks
250
+ @reload_done.wait while reloading?
251
+ return root.stop
252
+ when :stop_draining_tasks
253
+ @tasks.to_a.each(&:stop) if since == @draining_since.get
254
+ end
255
+ end
256
+ end
257
+
258
+ # Waits for a free slot (and, when a reload is pending, for every running task to finish and the reload), then
259
+ # starts the task in its own fiber. The slot taken at `enqueue` is released exactly once: by the task when it
260
+ # finishes, or here if the task never started.
261
+ #
262
+ #: (Async::Task, Proc, Array[untyped]) -> void
263
+ def start(root, task, args)
264
+ @pending = [task, args]
265
+ started = false
266
+ wait_until { @active.value < @size }
267
+ drain_and_reload if @reload_gate && (@draining_since.get || reload_pending?)
268
+ # A reactor being replaced leaves the task to its successor; one being stopped drops it.
269
+ return if leaving?
270
+
271
+ take_reload_share
272
+ begin
273
+ root.async do
274
+ started = true
275
+ @pending = nil
276
+ perform(task, args)
277
+ end
278
+ ensure
279
+ finish_task unless started
280
+ end
281
+ ensure
282
+ @pending = nil unless @handing_over.true?
283
+ @in_flight.decrement unless started
284
+ end
285
+
286
+ #: () { () -> bool } -> void
287
+ def wait_until
288
+ @finished.wait until yield
289
+ end
290
+
291
+ #: (Proc, Array[untyped]) -> void
292
+ def perform(task, args)
293
+ @running_lock.synchronize { @running << Fiber.current }
294
+ @tasks << Async::Task.current
295
+ task.call(*args)
296
+ rescue Async::Stop
297
+ raise
298
+ rescue Exception => error # rubocop:disable Lint/RescueException
299
+ # An escaping error must never take the reactor down with it. concurrent-ruby's wrappers rescue only
300
+ # StandardError, so anything else lands here. Rescuing every Exception, SystemExit and Interrupt included,
301
+ # mirrors concurrent-ruby's own `Worker#run_task`.
302
+ report(error)
303
+ ensure
304
+ @tasks.delete(Async::Task.current)
305
+ @running_lock.synchronize { @running.delete(Fiber.current) }
306
+ @in_flight.decrement
307
+ finish_task
308
+ end
309
+
310
+ #: (Exception) -> void
311
+ def report(task_error)
312
+ @on_error.call(task_error)
313
+ rescue Exception => error # rubocop:disable Lint/RescueException
314
+ # A handler that raises, even a non-StandardError, must not take the reactor down either.
315
+ warn("#{self.class}: error handler raised #{error.class}: #{error.message}")
316
+ end
317
+ end
318
+ end
319
+ end
@@ -0,0 +1,168 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'concurrent'
5
+
6
+ module GoodJob
7
+ module AsyncExecutor
8
+ # Development code reloading for fiber pools.
9
+ #
10
+ # Rails' reload lock (`ActiveSupport::Dependencies.interlock`, a `ShareLock`) tracks its holders by thread. GoodJob
11
+ # wraps each job in `Rails.application.reloader.wrap`, which under fibers would take the lock, and reload, from one
12
+ # job's fiber while other jobs on the same reactor thread are mid-perform. So a fiber pool's jobs run inside
13
+ # `Rails.application.executor.wrap` instead, and each reactor holds the lock in shared mode, on its own thread,
14
+ # while it has any task running. Before starting a task it checks for a pending reload, and if there is one it
15
+ # starts nothing more until its running tasks have finished, then lets the reload happen (see `Reactor`).
16
+ #
17
+ # Only used when `config.enable_reloading` is on; otherwise the executor never calls anything here.
18
+ module ReloadGate
19
+ # Instrumented around a reactor's drain: from when it stops starting tasks until its last task finished.
20
+ DRAIN_EVENT = 'reload_drain.good_job'
21
+
22
+ # Stands in for the reloader instance Rails keeps for a fiber in a reloader's wrap. Rails only checks that one is
23
+ # there, or calls `complete!` on it when resetting a lost one.
24
+ ACTIVE_RELOADER = Object.new.tap { |marker| marker.define_singleton_method(:complete!) { nil } }.freeze
25
+
26
+ # Reactors, across every fiber pool in the process, draining or reloading right now, and the process counted. A
27
+ # forked child has none of its parent's reactor threads, so it starts counting again from zero.
28
+ @draining = Concurrent::AtomicFixnum.new(0)
29
+ @draining_pid = ::Process.pid
30
+ @fork_lock = Thread::Mutex.new
31
+
32
+ class << self
33
+ # Whether the app reloads code, and so fiber pools take the reload lock.
34
+ #
35
+ #: () -> bool
36
+ def enabled?
37
+ return false unless defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application
38
+
39
+ ::Rails.application.config.enable_reloading == true
40
+ end
41
+
42
+ # Whether code has changed and is waiting to be reloaded, by Rails' own check, the one a web request makes.
43
+ #
44
+ # A thread waiting to unload went through the same check first, so this covers it too. Once true it stays true
45
+ # until someone reloads. `ShareLock` exposes no supported way to see its waiters (only the debugging-only
46
+ # `raw_state`), so this is the only signal used.
47
+ #
48
+ #: () -> bool
49
+ def reload_pending?
50
+ ::Rails.application.reloader.check! ? true : false
51
+ end
52
+
53
+ # Reloads, as a web request does, if it is still pending: whoever got the unload lock first may already have.
54
+ # Waits for every other holder of the reload lock to release it.
55
+ #
56
+ #: () -> void
57
+ def reload!
58
+ ::Rails.application.reloader.wrap { nil }
59
+ end
60
+
61
+ # Runs a job's task within Rails' executor, but not its reloader: the reactor holds the reload lock instead, and
62
+ # only the reactor reloads.
63
+ #
64
+ # Active Job wraps every `execute` in `Rails.application.reloader.wrap` too, which would check for changes and
65
+ # unload right here, on the reactor thread. That thread already holds the only share, so unloading would not
66
+ # wait for the other jobs on it. So the reloader is marked active for this fiber, which makes every
67
+ # `reloader.wrap` inside it run its block directly, as it does when nested in a reloader's own wrap.
68
+ # `active_key` is `:nodoc:` in Rails 8.1, but it is how `Reloader.active?` (and so `wrap`) decides.
69
+ #
70
+ #: [T] () { () -> T } -> T
71
+ def wrap(&block)
72
+ ::Rails.application.executor.wrap { within_reloader(&block) }
73
+ end
74
+
75
+ # Takes the reload lock in shared mode for the current thread, waiting while anyone unloads.
76
+ #
77
+ #: () -> void
78
+ def start_running
79
+ interlock.start_running
80
+ end
81
+
82
+ # Gives back one share of the reload lock the current thread took.
83
+ #
84
+ #: () -> void
85
+ def done_running
86
+ interlock.done_running
87
+ end
88
+
89
+ # Gives back every share of the reload lock the current thread still holds. Run as a reactor thread ends,
90
+ # however it ends, since only the thread that took a share can give it back, and a share left on a dead
91
+ # thread would keep every reload waiting forever. Shares can be left over when a killed reactor's fibers had
92
+ # their `ensure` blocks (and with them `executor.wrap`'s) cut short.
93
+ #
94
+ # `ShareLock` keeps no public count per thread, so it is read from its `raw_state`.
95
+ #
96
+ #: () -> void
97
+ def release_thread
98
+ held = interlock.raw_state { |threads| threads.dig(Thread.current, :sharing) }.to_i
99
+ held.times { interlock.done_running }
100
+ end
101
+
102
+ # Counts a reactor as draining (see `draining?`) for the length of the block.
103
+ #
104
+ #: [T] () { () -> T } -> T
105
+ def draining
106
+ counter = draining_counter
107
+ counter.increment
108
+ begin
109
+ yield
110
+ ensure
111
+ counter.decrement
112
+ end
113
+ end
114
+
115
+ # Whether any reactor in the process is draining for a reload, or reloading. A reactor reloading waits for
116
+ # every other holder of the reload lock, so a busy reactor drains too, even with no task waiting.
117
+ #
118
+ #: () -> bool
119
+ def draining?
120
+ draining_counter.value.positive?
121
+ end
122
+
123
+ # The count of draining reactors in this process.
124
+ #
125
+ #: () -> Concurrent::AtomicFixnum
126
+ def draining_counter
127
+ return @draining if @draining_pid == ::Process.pid
128
+
129
+ @fork_lock.synchronize do
130
+ unless @draining_pid == ::Process.pid
131
+ @draining = Concurrent::AtomicFixnum.new(0)
132
+ @draining_pid = ::Process.pid
133
+ end
134
+ @draining
135
+ end
136
+ end
137
+
138
+ # Instruments a reactor's drain.
139
+ #
140
+ #: [T] (String) { () -> T } -> T
141
+ def instrument_drain(reactor_name, &block)
142
+ ActiveSupport::Notifications.instrument(DRAIN_EVENT, reactor: reactor_name, &block)
143
+ end
144
+
145
+ # Runs the block with the app's reloader counted as active for the current fiber, unless it already is.
146
+ #
147
+ #: [T] () { () -> T } -> T
148
+ def within_reloader
149
+ state = ActiveSupport::IsolatedExecutionState
150
+ key = ::Rails.application.reloader.active_key
151
+ return yield if state.key?(key)
152
+
153
+ state[key] = ACTIVE_RELOADER
154
+ begin
155
+ yield
156
+ ensure
157
+ state.delete(key)
158
+ end
159
+ end
160
+
161
+ #: () -> untyped
162
+ def interlock
163
+ ActiveSupport::Dependencies.interlock
164
+ end
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,164 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'good_job/async_executor/claim_release'
5
+ require 'good_job/async_executor/connection_cleanup'
6
+ require 'good_job/async_executor/errors'
7
+ require 'good_job/async_executor/executor'
8
+ require 'good_job/async_executor/multi_scheduler_extension'
9
+ require 'good_job/async_executor/reload_gate'
10
+
11
+ module GoodJob
12
+ module AsyncExecutor
13
+ # Prepended to `GoodJob::Scheduler`. A scheduler given a fiber `async_shape:` runs its tasks on an `Executor`
14
+ # instead of GoodJob's thread pool; everything else about it (polling, caching, task blocks, shutdown) is GoodJob's.
15
+ # Without a fiber shape, nothing changes.
16
+ #
17
+ # While code reloading is enabled, a fiber scheduler's jobs run inside `Rails.application.executor.wrap` rather
18
+ # than GoodJob's `reloader.wrap`, and each reactor holds the reload lock for them (see `ReloadGate`).
19
+ module SchedulerExtension
20
+ LOCK_STRATEGIES_HOLDING_SESSIONS = %i[advisory hybrid].freeze
21
+
22
+ #: QueueShape?
23
+ attr_reader :async_shape
24
+
25
+ # `async_shape:` is a `QueueShape`. When omitted, the shape `MultiScheduler.from_configuration` parsed for this
26
+ # scheduler's segment, if any, is used.
27
+ #
28
+ #: (untyped, ?async_shape: QueueShape?, **untyped) -> void
29
+ def initialize(performer, async_shape: nil, **options)
30
+ async_shape ||= MultiSchedulerExtension.take_pending_shape(performer.respond_to?(:name) ? performer.name : nil)
31
+ @async_shape = async_shape&.fibers? ? async_shape : nil
32
+ options[:max_threads] = @async_shape.max_concurrency if @async_shape
33
+ super(performer, **options)
34
+ end
35
+
36
+ # Whether this scheduler runs its jobs as fibers.
37
+ #
38
+ #: () -> bool
39
+ def fiber_pool?
40
+ !@async_shape.nil?
41
+ end
42
+
43
+ # GoodJob's stats, counting fibers as threads, plus `reactors` and `fibers_per_reactor`.
44
+ #
45
+ #: () -> Hash[Symbol, untyped]
46
+ def stats
47
+ fiber_pool? ? super.merge!(executor.stats_extras) : super
48
+ end
49
+
50
+ private
51
+
52
+ # For a fiber shape, mirrors GoodJob's `create_executor` with the fiber executor in place of the thread pool.
53
+ # It runs again on every restart.
54
+ #
55
+ #: () -> void
56
+ def create_executor
57
+ return super unless fiber_pool?
58
+
59
+ shape = @async_shape #: as !nil
60
+ @name = "GoodJob::Scheduler(queues=#{performer.name} max_fibers=#{shape.max_concurrency} " \
61
+ "reactors=#{shape.reactors})"
62
+ @executor_options[:name] = @name
63
+ check_isolation!
64
+ warn_about_lock_strategy
65
+ # The pool gem may have loaded after this gem; it has by the time a fiber pool starts.
66
+ ConnectionCleanup.install_raw_pool_guard
67
+
68
+ register_instance
69
+ payload = { performer_name: performer.name, max_threads: shape.max_concurrency, reactors: shape.reactors,
70
+ fibers_per_reactor: shape.fibers_per_reactor, }
71
+ instrument('scheduler_create_pool', payload) do
72
+ @timer_set = GoodJob::Scheduler::TimerSet.new
73
+ @executor = build_fiber_executor(shape)
74
+ end
75
+ end
76
+
77
+ # Kill and drain graces follow the capsule's own `shutdown_timeout` (and `AsyncExecutor.hard_stop_timeout`). A
78
+ # reactor killed and replaced for a reload has its jobs' claims released (see `ClaimRelease`). An invalid
79
+ # `GOOD_JOB_ASYNC_EXECUTOR_HARD_STOP_TIMEOUT` raises ArgumentError here, not at the first kill.
80
+ #
81
+ #: (QueueShape) -> Executor
82
+ def build_fiber_executor(shape)
83
+ AsyncExecutor.validate_hard_stop_timeout_variable!
84
+ Executor.new(shape:, name: @name,
85
+ shutdown_timeout: -> { capsule_configuration.shutdown_timeout },
86
+ on_abandon: ConnectionCleanup.method(:release),
87
+ on_replace: -> (fibers) { ClaimRelease.prepare(fibers, scheduler: self) },
88
+ reload_gate: (ReloadGate if ReloadGate.enabled?))
89
+ end
90
+
91
+ # GoodJob's `create_task` (unchanged since 4.20), with `Rails.application.executor.wrap` in place of
92
+ # `reloader.wrap` for a fiber shape while reloading is enabled. `reloader.wrap` would reload from inside one job's
93
+ # fiber, while other jobs on the same reactor thread are mid-perform, since the reload lock counts that thread as
94
+ # one holder; the reactor reloads between jobs instead.
95
+ #
96
+ #: (?untyped, ?fanout: bool?) -> void
97
+ def create_task(delay = 0, fanout: false)
98
+ return super unless fiber_pool? && ReloadGate.enabled?
99
+
100
+ future = Concurrent::ScheduledTask.new(delay, args: [self, performer], executor:,
101
+ timer_set:) do |thr_scheduler, thr_performer|
102
+ Thread.current.name = Thread.current.name.sub('-worker-', '-thread-') if Thread.current.name
103
+ GoodJob::SafeState[:good_job_scheduler] = thr_scheduler
104
+ Thread.current.priority = -3 if thr_scheduler.lower_thread_priority
105
+
106
+ ReloadGate.wrap do
107
+ thr_performer.next do |found|
108
+ thr_scheduler.create_thread({ fanout: }) if found && fanout
109
+ end
110
+ end
111
+ end
112
+ future.add_observer(self, :task_observer)
113
+ future.execute
114
+ end
115
+
116
+ # Every job keeps its state (`GoodJob::CurrentThread`, ActiveRecord leases, `Current` attributes) in Rails'
117
+ # isolated execution state, which fibers on one reactor thread would share under thread isolation.
118
+ #
119
+ #: () -> void
120
+ def check_isolation!
121
+ level = ActiveSupport::IsolatedExecutionState.isolation_level
122
+ return if level == :fiber
123
+
124
+ raise IsolationError,
125
+ "#{name} runs jobs as fibers, which needs per-fiber state, but the isolation level is " \
126
+ "#{level.inspect}. Set config.active_support.isolation_level = :fiber."
127
+ end
128
+
129
+ # Advisory locks are session locks, so each in-flight job holds a database connection for its whole run. Logged
130
+ # once per scheduler, not on every restart.
131
+ #
132
+ #: () -> void
133
+ def warn_about_lock_strategy
134
+ return if @async_lock_strategy_warned
135
+
136
+ @async_lock_strategy_warned = true
137
+ strategy = lock_strategy
138
+ return unless LOCK_STRATEGIES_HOLDING_SESSIONS.include?(strategy)
139
+
140
+ GoodJob.logger.warn(
141
+ "#{name} runs jobs as fibers under the #{strategy.inspect} lock strategy, whose advisory locks hold a " \
142
+ 'database connection for every in-flight job. Consider lock_strategy :skiplocked.'
143
+ )
144
+ end
145
+
146
+ # The lock strategy of the capsule this scheduler's performer works for.
147
+ #
148
+ #: () -> Symbol?
149
+ def lock_strategy
150
+ configuration = capsule_configuration
151
+ configuration.respond_to?(:lock_strategy) ? configuration.lock_strategy : :advisory
152
+ end
153
+
154
+ # The configuration of the capsule this scheduler's performer works for, as GoodJob's performer reads it, or the
155
+ # global one for a performer without a capsule.
156
+ #
157
+ #: () -> GoodJob::Configuration
158
+ def capsule_configuration
159
+ capsule = performer.instance_variable_get(:@capsule)
160
+ capsule.respond_to?(:configuration) ? capsule.configuration : GoodJob.configuration
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,8 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module GoodJob
5
+ module AsyncExecutor
6
+ VERSION = '0.1.0'
7
+ end
8
+ end