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,192 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'good_job/async_executor/reactor'
5
+
6
+ module GoodJob
7
+ module AsyncExecutor
8
+ # Closes the database connections of fibers whose reactor was killed, so no killed job keeps a session (and with
9
+ # it, its advisory locks and open transaction) alive. It does so in two places:
10
+ #
11
+ # - While a killed reactor thread unwinds, its fibers' `ensure` blocks run, cut short wherever they yield. Rails'
12
+ # executor then checks their connections back in, often before GoodJob's own `ensure` could unlock the job. So a
13
+ # connection checked in by a reactor thread that is being killed is closed and removed instead (`CheckinGuard`).
14
+ # - Once the thread is dead, the executor calls `release` (its `on_abandon`) with the fibers that were running,
15
+ # for connections that were never checked in.
16
+ #
17
+ # `release` finds connections by who owns them when it runs, not from any earlier list: a killed fiber's `ensure`
18
+ # blocks may have checked out, or reconnected, a session after the fibers were snapshotted.
19
+ #
20
+ # Usually the reactor thread is dead by then, so nothing else touches these connections. If it ignored
21
+ # `Thread#kill` for the whole grace period, it may still be inside one. `release` then neither waits for it nor
22
+ # fails: it closes the connection under it, which is what unsticks it (its next read fails), and Postgres ends the
23
+ # session either way.
24
+ module ConnectionCleanup
25
+ # Prepended to ActiveRecord's `ConnectionPool`. A connection given back by a reactor thread being killed is in an
26
+ # unknown state (its fiber's `ensure` blocks were cut short), so it is closed rather than handed to the next
27
+ # caller. Every other thread goes straight to ActiveRecord.
28
+ #
29
+ # `active_record-async_connection_pool` overrides `checkin` too, and detaches the raw connection there, resetting
30
+ # it over the network and returning it to its raw pool. Whichever of the two is prepended last runs first, and
31
+ # that order is up to the app. So this guard also takes over `release_connection` (which the pool gem leaves
32
+ # alone, and through which Rails' executor and `with_connection` give connections back), and `RawPoolGuard` is
33
+ # prepended onto the pool gem's own module, so a direct `checkin` is caught before the gem's either way.
34
+ module CheckinGuard
35
+ #: (untyped) -> void
36
+ def checkin(conn)
37
+ super unless ConnectionCleanup.discarded_on_checkin?(self, conn)
38
+ end
39
+
40
+ #: (?untyped) -> bool?
41
+ def release_connection(existing_lease = nil)
42
+ return super unless ConnectionCleanup.killed_reactor_thread?
43
+ return if discarded?
44
+
45
+ conn = connection_lease.release
46
+ return false unless conn
47
+
48
+ checkin(conn) unless ConnectionCleanup.discarded_on_checkin?(self, conn)
49
+ true
50
+ end
51
+ end
52
+
53
+ # Prepended to the pool gem's `PoolExtension`, so it runs before that module's `checkin`.
54
+ module RawPoolGuard
55
+ #: (untyped) -> void
56
+ def checkin(conn)
57
+ super unless ConnectionCleanup.discarded_on_checkin?(self, conn)
58
+ end
59
+ end
60
+
61
+ class << self
62
+ # Prepends `RawPoolGuard` onto the pool gem's `PoolExtension`, once the gem is loaded. Safe to call repeatedly.
63
+ #
64
+ #: () -> void
65
+ def install_raw_pool_guard
66
+ return unless defined?(ActiveRecord::AsyncConnectionPool::PoolExtension)
67
+ return if ActiveRecord::AsyncConnectionPool::PoolExtension <= RawPoolGuard
68
+
69
+ ActiveRecord::AsyncConnectionPool::PoolExtension.prepend(RawPoolGuard)
70
+ end
71
+
72
+ # Closes and removes the connection instead of checking it in, if this is a reactor thread being killed.
73
+ # Never raises: the connection is out of the pool either way, and raising would cut short the rest of the
74
+ # dying fiber's `ensure` blocks.
75
+ #
76
+ #: (untyped, untyped) -> bool
77
+ def discarded_on_checkin?(pool, conn)
78
+ return false unless killed_reactor_thread?
79
+ return false if pool.instance_variable_get(:@pinned_connection).equal?(conn)
80
+
81
+ begin
82
+ discard(pool, conn)
83
+ rescue StandardError
84
+ nil
85
+ end
86
+ true
87
+ end
88
+
89
+ # Closes every connection leased by one of the fibers and takes it out of its pool. Fibers that are dead or
90
+ # hold nothing are skipped. Every connection is attempted; the first error is raised afterwards.
91
+ #
92
+ #: (Array[Fiber]) -> void
93
+ def release(fibers)
94
+ owners = fibers.to_set
95
+ return if owners.empty? || !defined?(ActiveRecord::Base)
96
+
97
+ errors = []
98
+ each_leased_connection(owners) do |pool, adapter|
99
+ discard(pool, adapter)
100
+ rescue StandardError => error
101
+ errors << error
102
+ end
103
+ raise errors.first if errors.any?
104
+ end
105
+
106
+ # Closes the adapter's connection and removes it from the pool, which also clears its lease. With
107
+ # `active_record-async_connection_pool`'s raw pool, the raw connection is dropped, freeing its slot.
108
+ #
109
+ #: (untyped, untyped) -> void
110
+ def discard(pool, adapter)
111
+ if raw_pool?(pool)
112
+ adapter.drop_raw_connection!
113
+ else
114
+ disconnect(adapter)
115
+ end
116
+ ensure
117
+ pool.remove(adapter)
118
+ end
119
+
120
+ # Whether this is a reactor thread unwinding from `Thread#kill`.
121
+ #
122
+ #: () -> bool
123
+ def killed_reactor_thread?
124
+ # The thread variable first: it is false on every other thread, and `status` allocates a String.
125
+ thread = Thread.current
126
+ thread.thread_variable_get(Reactor::THREAD_VARIABLE) == true && thread.status == 'aborting'
127
+ end
128
+
129
+ private
130
+
131
+ #: (Set[Fiber]) { (untyped, untyped) -> void } -> void
132
+ def each_leased_connection(owners)
133
+ ActiveRecord::Base.connection_handler.connection_pool_list.each do |pool|
134
+ Array(pool.connections).each do |adapter|
135
+ yield pool, adapter if owners.include?(adapter.owner)
136
+ end
137
+ end
138
+ end
139
+
140
+ #: (untyped) -> bool
141
+ def raw_pool?(pool)
142
+ pool.respond_to?(:raw_pool) && !pool.raw_pool.nil?
143
+ end
144
+
145
+ # `disconnect!` takes the adapter's lock, which a still-running reactor thread may hold forever. If the lock is
146
+ # taken, the raw connection is closed directly instead.
147
+ #
148
+ #: (untyped) -> void
149
+ def disconnect(adapter)
150
+ return if with_lock_if_free(adapter.lock) { adapter.disconnect! }
151
+
152
+ raw = adapter.instance_variable_get(:@raw_connection)
153
+ raw.close if raw.respond_to?(:close) && !(raw.respond_to?(:finished?) && raw.finished?)
154
+ end
155
+
156
+ # Runs the block holding the lock if it is free right now. False, without running it, if another thread or
157
+ # fiber holds it. ActiveRecord's lock is a `Monitor` when the pool locks to a fiber, its own `ThreadMonitor`
158
+ # when it locks to a thread, and otherwise a no-op lock.
159
+ #
160
+ #: (untyped) { () -> void } -> bool
161
+ def with_lock_if_free(lock) # rubocop:disable Naming/PredicateMethod
162
+ case lock
163
+ when ::Monitor
164
+ return false unless lock.try_enter
165
+
166
+ begin
167
+ yield
168
+ ensure
169
+ lock.exit
170
+ end
171
+ when ActiveSupport::Concurrency::ThreadMonitor
172
+ return false unless lock.send(:mon_try_enter)
173
+
174
+ begin
175
+ yield
176
+ ensure
177
+ lock.send(:mon_exit)
178
+ end
179
+ else
180
+ yield
181
+ end
182
+ true
183
+ end
184
+ end
185
+ end
186
+ end
187
+ end
188
+
189
+ ActiveSupport.on_load(:active_record) do
190
+ ActiveRecord::ConnectionAdapters::ConnectionPool.prepend(GoodJob::AsyncExecutor::ConnectionCleanup::CheckinGuard)
191
+ GoodJob::AsyncExecutor::ConnectionCleanup.install_raw_pool_guard
192
+ end
@@ -0,0 +1,11 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module GoodJob
5
+ module AsyncExecutor
6
+ class Error < StandardError; end
7
+
8
+ # Raised when the Rails isolation level is not :fiber, which fiber execution depends on.
9
+ class IsolationError < Error; end
10
+ end
11
+ end
@@ -0,0 +1,404 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ require 'good_job/async_executor/errors'
5
+ require 'good_job/async_executor/hard_stop'
6
+ require 'good_job/async_executor/queue_shape'
7
+ require 'good_job/async_executor/reactor'
8
+
9
+ module GoodJob
10
+ module AsyncExecutor
11
+ # Runs tasks as fibers across a fixed set of reactor threads, in place of GoodJob's thread pool executor for a
12
+ # fiber queue group.
13
+ #
14
+ # Duck-types what GoodJob's `Scheduler` and concurrent-ruby's `Future`, `ScheduledTask` and `TimerSet` use: `post`
15
+ # and its lifecycle (`running?`, `shuttingdown?`, `shutdown?`, `shutdown`, `kill`, `wait_for_termination`) plus
16
+ # `ready_worker_count`. In a forked child each of these first sets the executor up for the child's process (see
17
+ # `reset_if_forked`).
18
+ class Executor
19
+ # concurrent-ruby's `Future` and `ScheduledTask` accept only executors that include this module.
20
+ include Concurrent::ExecutorService
21
+
22
+ # How long a killed reactor thread gets to die, running its fibers' `ensure` blocks, before `on_abandon` runs
23
+ # anyway.
24
+ ABANDON_GRACE = 0.5
25
+
26
+ # How often, with a reload gate, the executor checks on reactors draining for a reload.
27
+ WATCH_INTERVAL = 0.1
28
+
29
+ # How often, at most, the executor itself asks whether a reload is pending for a busy reactor with tasks waiting.
30
+ # Without an evented file watcher each check scans the app's files, and reactors already check before each task.
31
+ PENDING_CHECK_INTERVAL = 0.5
32
+
33
+ #: QueueShape
34
+ attr_reader :shape
35
+
36
+ #: String
37
+ attr_reader :name
38
+
39
+ # `on_error` receives any error that escapes a task or `on_abandon`. By default it goes to
40
+ # `GoodJob.on_thread_error`, as an error escaping a thread pool task does.
41
+ #
42
+ # `shutdown_timeout` returns GoodJob's `shutdown_timeout` for the pool, read when needed. Tasks `kill` stops get
43
+ # `AsyncExecutor.hard_stop_timeout` to unwind before their reactors are killed, or `shutdown_timeout` when that
44
+ # is shorter and not negative. `on_abandon` receives the fibers still running on each reactor about to be killed,
45
+ # so whatever they hold can be released.
46
+ #
47
+ # `reload_gate` (`ReloadGate`, in development) makes reactors hold the reload lock and drain for reloads. A drain
48
+ # gets `shutdown_timeout` (`hard_stop_timeout` when that is nil or negative), then its tasks are stopped as `kill`
49
+ # does: `Async::Stop`, and if a task still has not stopped after as long again, the reactor is killed, its fibers
50
+ # go to `on_abandon`, and a fresh reactor takes its place and its queued tasks. `on_replace` receives the fibers
51
+ # of a reactor about to be replaced, before it is killed, and returns a callable run once it has been abandoned
52
+ # (eg. to release what its jobs claimed, read while they still run).
53
+ #
54
+ # @rbs shape: QueueShape
55
+ # @rbs name: String
56
+ # @rbs on_error: (^(Exception) -> void)?
57
+ # @rbs shutdown_timeout: ^() -> (Float | Integer)?
58
+ # @rbs on_abandon: ^(Array[Fiber]) -> void
59
+ # @rbs on_replace: ^(Array[Fiber]) -> (^() -> void)?
60
+ # @rbs reload_gate: untyped
61
+ # @rbs return: void
62
+ def initialize(shape:, name:, on_error: nil, shutdown_timeout: -> {}, # rubocop:disable Metrics/ParameterLists
63
+ on_abandon: -> (_fibers) {}, on_replace: -> (_fibers) {}, reload_gate: nil)
64
+ raise ArgumentError, "#{self.class} needs a fiber queue shape" unless shape.fibers?
65
+
66
+ @shape = shape
67
+ @name = name
68
+ @shutdown_timeout = shutdown_timeout
69
+ @on_abandon = on_abandon
70
+ @on_replace = on_replace
71
+ @mutex = Thread::Mutex.new
72
+ @shutting_down = false
73
+ @on_error = on_error || -> (error) { report_error(error) }
74
+ @reload_gate = reload_gate
75
+ start_reactors
76
+ end
77
+
78
+ # Queues the task on the live reactor with the most free slots. Never blocks, so tasks may post from their own
79
+ # fiber. Returns false, discarding the task, once shutting down or when every live reactor is full, as GoodJob's
80
+ # thread pool does with `fallback_policy: :discard`.
81
+ #
82
+ #: (*untyped) ?{ (*untyped) -> untyped } -> bool
83
+ def post(*args, &task) # rubocop:disable Naming/PredicateMethod
84
+ raise ArgumentError, 'no block given' unless task
85
+
86
+ @mutex.synchronize do
87
+ reset_if_forked!(rebuild: true)
88
+ return false if @shutting_down
89
+
90
+ reactor = @reactors.select(&:alive?).max_by(&:free_slots)
91
+ return false if reactor.nil? || reactor.full?
92
+
93
+ reactor.enqueue(task, args)
94
+ end
95
+
96
+ true
97
+ end
98
+
99
+ # Tasks can be discarded when every reactor is full.
100
+ #
101
+ #: () -> bool
102
+ def can_overflow?
103
+ true
104
+ end
105
+
106
+ # How many more tasks would start right away. A reactor's queued tasks wait for that reactor's slots, so a backlog
107
+ # on one reactor does not reduce the free slots counted on another.
108
+ #
109
+ #: () -> Integer
110
+ def ready_worker_count
111
+ reset_if_forked
112
+ @reactors.select(&:alive?).sum { |reactor| reactor.free_slots.clamp(0, nil) }
113
+ end
114
+
115
+ # False once shutting down, or once every reactor has died.
116
+ #
117
+ #: () -> bool
118
+ def running?
119
+ reset_if_forked
120
+ !@shutting_down && @reactors.any?(&:alive?)
121
+ end
122
+
123
+ #: () -> bool
124
+ def shuttingdown?
125
+ reset_if_forked
126
+ @shutting_down && @reactors.any?(&:alive?)
127
+ end
128
+
129
+ # True once every reactor has exited, whether shut down or dead, so GoodJob can restart the pool.
130
+ #
131
+ #: () -> bool
132
+ def shutdown?
133
+ reset_if_forked
134
+ @reactors.none?(&:alive?)
135
+ end
136
+
137
+ # Refuses new tasks and lets every accepted task, running or queued, finish.
138
+ #
139
+ #: () -> void
140
+ def shutdown
141
+ @mutex.synchronize do
142
+ # A child shutting down before using the executor has nothing to stop, so builds nothing.
143
+ reset_if_forked!(rebuild: false)
144
+ next if @shutting_down
145
+
146
+ @shutting_down = true
147
+ @reactors.each(&:stop)
148
+ @watch_stop.set
149
+ end
150
+ end
151
+
152
+ # Refuses new tasks, drops queued ones and stops running ones, as killing a thread pool does, but never hangs on a
153
+ # task that does not yield.
154
+ #
155
+ # Each running task gets `Async::Stop` at its next yield, and has `kill_grace` to unwind. A reactor still running
156
+ # after that has a task that never yields, so its thread is killed, which runs its fibers' `ensure` blocks out
157
+ # of order and possibly cut short. Once the thread is dead (or after `ABANDON_GRACE`), `on_abandon`
158
+ # gets the fibers that were running, from this thread, to release whatever they still hold.
159
+ #
160
+ #: () -> void
161
+ def kill
162
+ shutdown
163
+ @reactors.each(&:stop_tasks)
164
+ grace = kill_grace
165
+ abandon_stuck(grace) unless wait_for_termination(grace)
166
+ end
167
+
168
+ # The fibers currently running a task, across every reactor.
169
+ #
170
+ #: () -> Array[Fiber]
171
+ def running_fibers
172
+ reset_if_forked
173
+ @reactors.flat_map(&:running_fibers)
174
+ end
175
+
176
+ # Waits for every reactor to exit, for at most `timeout` seconds in all (forever when nil). True if they all did.
177
+ #
178
+ #: (?(Float | Integer)?) -> bool
179
+ def wait_for_termination(timeout = nil)
180
+ reset_if_forked
181
+ deadline = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) + timeout if timeout
182
+
183
+ remaining = -> { deadline && [deadline - ::Process.clock_gettime(::Process::CLOCK_MONOTONIC), 0].max }
184
+ @reactors.all? do |reactor|
185
+ reactor.join(remaining.call)
186
+ end && (@watchdog.nil? || !@watchdog.join(remaining.call).nil?)
187
+ end
188
+
189
+ # Fiber-specific additions to the scheduler's stats.
190
+ #
191
+ #: () -> { reactors: Integer, fibers_per_reactor: Integer }
192
+ def stats_extras
193
+ { reactors: shape.reactors, fibers_per_reactor: shape.fibers_per_reactor }
194
+ end
195
+
196
+ private
197
+
198
+ # Builds every reactor, and the watchdog with a reload gate, for this process.
199
+ #
200
+ #: () -> void
201
+ def start_reactors
202
+ @reactors = Array.new(shape.reactors) { |index| build_reactor(index) }
203
+ @watch_stop = Concurrent::Event.new
204
+ @watchdog = (Thread.new { watch } if @reload_gate)
205
+ @pid = ::Process.pid
206
+ end
207
+
208
+ # A forked child has none of its parent's reactor or watchdog threads (see `Reactor#forked?`). As
209
+ # concurrent-ruby's thread pool resets itself after a fork, the first use of the executor in a child sets it up
210
+ # for this process: running at the fork, it starts fresh reactors; shut down or shutting down, it counts as
211
+ # terminated. The parent's queued tasks, and everything its reactor threads held, are left behind.
212
+ #
213
+ #: () -> void
214
+ def reset_if_forked
215
+ return if @pid == ::Process.pid
216
+
217
+ @mutex.synchronize { reset_if_forked!(rebuild: true) }
218
+ end
219
+
220
+ # `reset_if_forked`, holding the mutex. Without `rebuild`, a running executor is left with no reactors, for
221
+ # `shutdown` to mark shut down.
222
+ #
223
+ #: (rebuild: bool) -> void
224
+ def reset_if_forked!(rebuild:)
225
+ return if @pid == ::Process.pid
226
+ return start_reactors if rebuild && !@shutting_down
227
+
228
+ @reactors = []
229
+ @watch_stop = Concurrent::Event.new
230
+ @watchdog = nil
231
+ @pid = ::Process.pid
232
+ end
233
+
234
+ # Abandons every reactor still running. One reloading goes last, after up to another `grace` for its reload: one
235
+ # killed mid-reload could leave the app half unloaded, and the reload may be waiting on the others.
236
+ #
237
+ #: (Float | Integer) -> void
238
+ def abandon_stuck(grace)
239
+ reloading, stuck = @reactors.select(&:alive?).partition(&:reloading?)
240
+ stuck.each { |reactor| abandon(reactor) }
241
+ reloading.each do |reactor|
242
+ abandon(reactor) unless reactor.wait_while_reloading(grace) && reactor.join(ABANDON_GRACE)
243
+ end
244
+ end
245
+
246
+ # How long stopped tasks get before their reactors are killed: `hard_stop_timeout`, bounded by a non-negative
247
+ # `shutdown_timeout`.
248
+ #
249
+ #: () -> (Float | Integer)
250
+ def kill_grace
251
+ hard_stop = AsyncExecutor.hard_stop_timeout
252
+ timeout = @shutdown_timeout.call
253
+ timeout.nil? || timeout.negative? ? hard_stop : [timeout, hard_stop].min
254
+ end
255
+
256
+ # How long a drain for a reload gets before its tasks are stopped, and then before its reactor is replaced:
257
+ # `shutdown_timeout`, or `hard_stop_timeout` when that is nil or negative.
258
+ #
259
+ #: () -> (Float | Integer)
260
+ def drain_grace
261
+ timeout = @shutdown_timeout.call
262
+ timeout.nil? || timeout.negative? ? AsyncExecutor.hard_stop_timeout : timeout
263
+ end
264
+
265
+ #: (Integer) -> Reactor
266
+ def build_reactor(index)
267
+ Reactor.new(name: "#{name}-reactor-#{index}", size: shape.fibers_per_reactor, on_error: @on_error,
268
+ reload_gate: @reload_gate, on_crash: -> (reactor) { replace_crashed(reactor) })
269
+ end
270
+
271
+ # With a reload gate, until shutdown: starts a drain on a reactor that cannot check for a reload itself, and
272
+ # stops the tasks of a drain that takes too long.
273
+ #
274
+ #: () -> void
275
+ def watch
276
+ Thread.current.name = "#{name}-reload-watch"
277
+ # Per reactor slot: the drain whose tasks were stopped, and when a pending reload was last checked for.
278
+ @stopped_drains = {} #: Hash[Integer, Float]
279
+ @pending_checked_at = Hash.new(-Float::INFINITY) #: Hash[Integer, Float]
280
+ until @watch_stop.wait(WATCH_INTERVAL)
281
+ @reactors.each_with_index do |reactor, index|
282
+ watch_drain(reactor, index)
283
+ rescue StandardError => error
284
+ @on_error.call(error)
285
+ end
286
+ end
287
+ end
288
+
289
+ # A reactor checks for a reload before starting each task, but not while it waits for a free slot, nor while a
290
+ # task that never yields holds its thread; so a busy reactor with a task waiting is checked here too, as is any
291
+ # busy reactor while another one drains (that one's reload waits for it). A drain gets `drain_grace` to finish,
292
+ # then its tasks are stopped, and once as long again has passed the reactor is replaced.
293
+ #
294
+ #: (Reactor, Integer) -> void
295
+ def watch_drain(reactor, index)
296
+ return unless reactor.alive?
297
+
298
+ since = reactor.draining_since
299
+ return begin_drain_if_pending(reactor, index) if since.nil?
300
+
301
+ timeout = drain_grace
302
+ # Read in this order, so a task started after the drain ended is never taken for one of the drain's.
303
+ return unless reactor.busy? && reactor.draining_since == since
304
+
305
+ escalate_drain(reactor, index, since, timeout)
306
+ end
307
+
308
+ #: (Reactor, Integer, Float, Float | Integer) -> void
309
+ def escalate_drain(reactor, index, since, timeout)
310
+ elapsed = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - since
311
+ if elapsed >= 2 * timeout
312
+ replace(reactor, index, since)
313
+ elsif elapsed >= timeout && @stopped_drains[index] != since
314
+ @stopped_drains[index] = since
315
+ reactor.stop_draining_tasks(since)
316
+ end
317
+ end
318
+
319
+ #: (Reactor, Integer) -> void
320
+ def begin_drain_if_pending(reactor, index)
321
+ return unless reactor.busy? && (reactor.queued? || @reload_gate.draining?)
322
+
323
+ now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
324
+ return if now - @pending_checked_at[index] < PENDING_CHECK_INTERVAL
325
+
326
+ @pending_checked_at[index] = now
327
+ reactor.begin_drain if @reload_gate.reload_pending?
328
+ end
329
+
330
+ # Kills a reactor whose tasks would not stop, as `kill` does, and puts a fresh one in its place with the tasks it
331
+ # had not started, unless the executor is shutting down meanwhile. Nothing happens if the drain's tasks finished
332
+ # (or it started reloading) since they were last checked.
333
+ #
334
+ #: (Reactor, Integer, Float) -> void
335
+ def replace(reactor, index, since)
336
+ return unless reactor.hand_over_if_stuck!(since)
337
+
338
+ after_abandon = report_errors { @on_replace.call(reactor.running_fibers) }
339
+ abandon(reactor)
340
+ report_errors { after_abandon&.call }
341
+ @mutex.synchronize { install_fresh(index, reactor) if @reactors[index].equal?(reactor) }
342
+ end
343
+
344
+ # Puts a fresh reactor in place of one whose loop failed, unless shutting down. Called from the dead reactor's
345
+ # thread as it ends.
346
+ #
347
+ #: (Reactor) -> void
348
+ def replace_crashed(reactor)
349
+ replaced = @mutex.synchronize do
350
+ index = @reactors.index { |candidate| candidate.equal?(reactor) }
351
+ next false if index.nil? || @shutting_down || @pid != ::Process.pid
352
+
353
+ install_fresh(index, reactor)
354
+ end
355
+ @on_error.call(Error.new("#{reactor.name} exited unexpectedly and was replaced")) if replaced
356
+ end
357
+
358
+ # Puts a fresh reactor at `index` in place of `old`, which no longer runs, with the tasks `old` had not started.
359
+ # Must hold the mutex. False, dropping those tasks, when shutting down.
360
+ #
361
+ #: (Integer, Reactor) -> bool
362
+ def install_fresh(index, old) # rubocop:disable Naming/PredicateMethod
363
+ queued = old.take_queued
364
+ return false if @shutting_down
365
+
366
+ fresh = build_reactor(index)
367
+ queued.each { |task, args| fresh.enqueue(task, args) }
368
+ @reactors[index] = fresh
369
+ true
370
+ end
371
+
372
+ # Kills the reactor's thread, then hands its fibers to `on_abandon`. A failing hook is reported, and the reactor
373
+ # still counts as exited.
374
+ #
375
+ #: (Reactor) -> void
376
+ def abandon(reactor)
377
+ reactor.abandon(ABANDON_GRACE) { |fibers| @on_abandon.call(fibers) }
378
+ rescue StandardError => error
379
+ @on_error.call(error)
380
+ end
381
+
382
+ # Runs the block, reporting (and returning nil for) a StandardError it raises.
383
+ #
384
+ #: [T] () { () -> T } -> T?
385
+ def report_errors
386
+ yield
387
+ rescue StandardError => error
388
+ @on_error.call(error)
389
+ nil
390
+ end
391
+
392
+ # Reports an error that escaped a task the way GoodJob reports thread errors.
393
+ #
394
+ #: (Exception) -> void
395
+ def report_error(error)
396
+ if GoodJob.respond_to?(:_on_thread_error)
397
+ GoodJob._on_thread_error(error)
398
+ else
399
+ warn("#{name}: #{error.class}: #{error.message}")
400
+ end
401
+ end
402
+ end
403
+ end
404
+ end
@@ -0,0 +1,68 @@
1
+ # typed: true
2
+ # frozen_string_literal: true
3
+
4
+ module GoodJob
5
+ module AsyncExecutor
6
+ # How long, by default, `kill` gives jobs it told to stop before it kills their reactors.
7
+ DEFAULT_HARD_STOP_TIMEOUT = 5.0
8
+
9
+ # The environment variable read for `hard_stop_timeout` while it is not set in code.
10
+ HARD_STOP_TIMEOUT_VARIABLE = 'GOOD_JOB_ASYNC_EXECUTOR_HARD_STOP_TIMEOUT'
11
+
12
+ @hard_stop_timeout = nil
13
+
14
+ class << self
15
+ # Seconds a fiber pool's `kill` waits, after sending `Async::Stop` to the jobs still running, before it kills
16
+ # their reactors and closes their connections. GoodJob's `shutdown_timeout` is the wait before that, for jobs to
17
+ # finish; a non-negative `shutdown_timeout` shorter than this one bounds this wait too. Like Resque's
18
+ # RESQUE_TERM_TIMEOUT after RESQUE_PRE_SHUTDOWN_TIMEOUT.
19
+ #
20
+ # Set in code, or else read from `GOOD_JOB_ASYNC_EXECUTOR_HARD_STOP_TIMEOUT`, or else `DEFAULT_HARD_STOP_TIMEOUT`.
21
+ # Read at each kill, so a change takes effect on the next one.
22
+ #
23
+ #: () -> (Float | Integer)
24
+ def hard_stop_timeout
25
+ @hard_stop_timeout || hard_stop_timeout_from_environment || DEFAULT_HARD_STOP_TIMEOUT
26
+ end
27
+
28
+ # Sets `hard_stop_timeout`: a finite number of seconds, zero or more, or nil to go back to the environment
29
+ # variable or the default. Untyped, so a wrong value raises ArgumentError rather than a type error.
30
+ #
31
+ #: (untyped) -> void
32
+ def hard_stop_timeout=(seconds)
33
+ unless seconds.nil? || valid_timeout?(seconds)
34
+ raise ArgumentError, "hard_stop_timeout must be a finite number of seconds, 0 or more, got #{seconds.inspect}"
35
+ end
36
+
37
+ @hard_stop_timeout = seconds
38
+ end
39
+
40
+ # Raises ArgumentError naming the environment variable when it holds an invalid value, so a bad value fails when a
41
+ # fiber pool is built rather than at the first kill. A blank or unset variable is fine.
42
+ #
43
+ #: () -> void
44
+ def validate_hard_stop_timeout_variable!
45
+ hard_stop_timeout_from_environment
46
+ end
47
+
48
+ private
49
+
50
+ #: () -> Float?
51
+ def hard_stop_timeout_from_environment
52
+ value = ENV.fetch(HARD_STOP_TIMEOUT_VARIABLE, nil)
53
+ return if value.nil? || value.strip.empty?
54
+
55
+ seconds = Float(value, exception: false)
56
+ return seconds if valid_timeout?(seconds)
57
+
58
+ raise ArgumentError,
59
+ "#{HARD_STOP_TIMEOUT_VARIABLE} must be a finite number of seconds, 0 or more, got #{value.inspect}"
60
+ end
61
+
62
+ #: (untyped) -> bool
63
+ def valid_timeout?(seconds)
64
+ seconds.is_a?(Numeric) && seconds.real? && seconds.finite? && !seconds.negative?
65
+ end
66
+ end
67
+ end
68
+ end