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.
- checksums.yaml +7 -0
- data/MIT-LICENSE +20 -0
- data/README.md +338 -0
- data/Rakefile +11 -0
- data/lib/good_job/async_executor/claim_release.rb +100 -0
- data/lib/good_job/async_executor/configuration_extension.rb +38 -0
- data/lib/good_job/async_executor/connection_cleanup.rb +192 -0
- data/lib/good_job/async_executor/errors.rb +11 -0
- data/lib/good_job/async_executor/executor.rb +404 -0
- data/lib/good_job/async_executor/hard_stop.rb +68 -0
- data/lib/good_job/async_executor/log_subscriber_extension.rb +21 -0
- data/lib/good_job/async_executor/multi_scheduler_extension.rb +92 -0
- data/lib/good_job/async_executor/queue_segment.rb +61 -0
- data/lib/good_job/async_executor/queue_shape.rb +71 -0
- data/lib/good_job/async_executor/reactor/draining.rb +173 -0
- data/lib/good_job/async_executor/reactor.rb +319 -0
- data/lib/good_job/async_executor/reload_gate.rb +168 -0
- data/lib/good_job/async_executor/scheduler_extension.rb +164 -0
- data/lib/good_job/async_executor/version.rb +8 -0
- data/lib/good_job/async_executor/worker_pool.rb +86 -0
- data/lib/good_job/async_executor.rb +30 -0
- metadata +118 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 4262be531b6162f3a55fd106e790b402eb867b61db3c835907dc695265546a1d
|
|
4
|
+
data.tar.gz: 6e4382a93a68e89c2968f12c5bd3486bcdd1399cd42089b600f6bdf3b7d567a6
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 52f7e172ce5340ae44821c2088b856a6b906c104786f2f1eaaf098e1028bde959ea9f76934538611927e5350a4936be7585032ad084b9464dbd4367027380d2a
|
|
7
|
+
data.tar.gz: 4c1541e99148e60bac92b9edc5582548865557d491539095b60adc87d13eb46938879999ef873ff1b9bb40f90c78d608d65464c10c24bdffd256d31910d270a0
|
data/MIT-LICENSE
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Copyright 2026 Minty Fresh
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
4
|
+
a copy of this software and associated documentation files (the
|
|
5
|
+
"Software"), to deal in the Software without restriction, including
|
|
6
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
7
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
8
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
9
|
+
the following conditions:
|
|
10
|
+
|
|
11
|
+
The above copyright notice and this permission notice shall be
|
|
12
|
+
included in all copies or substantial portions of the Software.
|
|
13
|
+
|
|
14
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
15
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
16
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
17
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
18
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
19
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
20
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
# GoodJob::AsyncExecutor
|
|
2
|
+
|
|
3
|
+
Runs chosen GoodJob queue groups as fibers on a few reactor threads, so I/O-bound jobs (HTTP calls, embeddings, slow
|
|
4
|
+
APIs) can run at hundreds of concurrent jobs without hundreds of threads. For Rails apps on GoodJob.
|
|
5
|
+
|
|
6
|
+
Requires:
|
|
7
|
+
|
|
8
|
+
- Ruby >= 3.3
|
|
9
|
+
- good_job >= 4.23, < 5 (4.20 to 4.22 lack APIs this gem uses)
|
|
10
|
+
- activesupport >= 8.1, < 8.2 (it relies on Rails internals that may change in any minor release)
|
|
11
|
+
- async >= 2
|
|
12
|
+
- PostgreSQL (GoodJob is Postgres-only)
|
|
13
|
+
|
|
14
|
+
## Why?
|
|
15
|
+
|
|
16
|
+
GoodJob runs each job on a thread, so concurrency costs threads. A job that mostly waits on the network holds a thread
|
|
17
|
+
(and its memory) the whole time. A fiber is much cheaper, and while it waits the reactor thread runs other fibers.
|
|
18
|
+
|
|
19
|
+
This gem lets a queue group opt in with a fiber count in GoodJob's queue string. Everything else about GoodJob
|
|
20
|
+
(polling, the notifier, retries, the dashboard, shutdown) is unchanged. Queue groups without a fiber suffix run on
|
|
21
|
+
threads as before.
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
Add this line to your application's Gemfile:
|
|
26
|
+
|
|
27
|
+
```ruby
|
|
28
|
+
gem 'good_job-async_executor'
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
And then execute:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
$ bundle
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Set the isolation level to `:fiber`, and give a queue group a fiber count:
|
|
38
|
+
|
|
39
|
+
```ruby
|
|
40
|
+
# config/application.rb
|
|
41
|
+
config.active_support.isolation_level = :fiber
|
|
42
|
+
config.good_job.queues = 'default:5;io:500f'
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Each job keeps its state (ActiveRecord leases, `ActiveSupport::CurrentAttributes`, GoodJob's own bookkeeping) in Rails'
|
|
46
|
+
isolated execution state. Under the default `:thread` isolation, fibers on one reactor thread would share it. So a
|
|
47
|
+
scheduler that runs fibers raises `GoodJob::AsyncExecutor::IsolationError` when it is created unless the level is
|
|
48
|
+
`:fiber`.
|
|
49
|
+
|
|
50
|
+
### Queue syntax
|
|
51
|
+
|
|
52
|
+
The count after the queue name is GoodJob's own syntax, extended:
|
|
53
|
+
|
|
54
|
+
| Queues | Meaning |
|
|
55
|
+
|--------------------|----------------------------------------------------------------------|
|
|
56
|
+
| `io:5` | 5 threads (unchanged) |
|
|
57
|
+
| `io:500f` | 500 fibers on one reactor thread |
|
|
58
|
+
| `io:5x100f` | 100 fibers on each of 5 reactor threads (500 in all) |
|
|
59
|
+
| `default:5;io:50f` | segments are independent: `default` on threads, `io` on fibers |
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
$ GOOD_JOB_QUEUES='default:5;io:500f' bundle exec good_job start
|
|
63
|
+
$ bundle exec good_job start --queues='io:5x100f'
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A count without a suffix is a thread count. An invalid count (`0f`, `0x10f`, `5x0f`, `f`, `io:abc`) raises
|
|
67
|
+
`ArgumentError` at boot. That includes thread-only apps: stock GoodJob silently read counts such as `io:abc` or
|
|
68
|
+
`io:5.5` with `to_i`, and this gem raises instead.
|
|
69
|
+
|
|
70
|
+
A fiber suffix is only accepted in the queue string. `GOOD_JOB_THREADS`, `GOOD_JOB_MAX_THREADS`, `--threads`,
|
|
71
|
+
`--max-threads` and `config.good_job.max_threads` raise `ArgumentError` when given one (`100f`, `5x100f`, in either
|
|
72
|
+
case), since GoodJob would read them with `to_i`.
|
|
73
|
+
|
|
74
|
+
**Without this gem loaded, GoodJob reads `io:500f` as 500 threads and `io:5x100f` as 5 threads.** Keep the gem in every
|
|
75
|
+
process that reads the queue string, or an app that deploys the setting before the gem will start hundreds of threads.
|
|
76
|
+
|
|
77
|
+
### Choosing `Mf` or `NxMf`
|
|
78
|
+
|
|
79
|
+
The reactors are plain threads, so the GVL still lets only one of them run Ruby at a time. Fibers help when jobs wait,
|
|
80
|
+
not when they compute.
|
|
81
|
+
|
|
82
|
+
- `Mf` (one reactor) is right for purely I/O-bound jobs that always yield. It is the cheapest option.
|
|
83
|
+
- `NxMf` (several reactors) contains the damage from CPU-heavy or non-yielding jobs. A job that holds its reactor
|
|
84
|
+
stalls only that reactor's fibers, and the others keep going. It also lets more than one reactor handle the
|
|
85
|
+
connection and parsing work that jobs do between waits.
|
|
86
|
+
|
|
87
|
+
Fibers are spread over reactors by free capacity, so `5x100f` behaves like one pool of 500.
|
|
88
|
+
|
|
89
|
+
## Database connections
|
|
90
|
+
|
|
91
|
+
Every fiber that queries takes an ActiveRecord connection lease for as long as its job runs (and for as long as any
|
|
92
|
+
sticky lease, such as `lease_connection`, lives). 500 fibers that query can need 500 connections. Size the
|
|
93
|
+
database's `max_connections` and the ActiveRecord pool for the number of jobs in flight, or run fewer fibers. GoodJob's
|
|
94
|
+
own warning about the pool being smaller than its thread count counts fibers as threads.
|
|
95
|
+
|
|
96
|
+
### Sizing database connections
|
|
97
|
+
|
|
98
|
+
Without this gem, a count in the queue string is read with `to_i`, so a sizing formula built that way reads `io:500f`
|
|
99
|
+
as 500 and `io:5x100f` as 5. These helpers read the queue string with the same parser that builds the schedulers (the
|
|
100
|
+
same default for a missing count, and the same `ArgumentError` for an invalid one):
|
|
101
|
+
|
|
102
|
+
```ruby
|
|
103
|
+
GoodJob::AsyncExecutor.worker_pools # => [#<data GoodJob::AsyncExecutor::WorkerPool queues=["default"], shape=...>, ...]
|
|
104
|
+
GoodJob::AsyncExecutor.worker_threads_count # threads in thread pools
|
|
105
|
+
GoodJob::AsyncExecutor.worker_fibers_count # fibers in fiber pools
|
|
106
|
+
GoodJob::AsyncExecutor.worker_reactor_threads_count # reactor threads running those fibers
|
|
107
|
+
GoodJob::AsyncExecutor.worker_concurrency # threads + fibers: the most jobs in flight at once
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Each takes an optional `GoodJob::Configuration` (default `GoodJob.configuration`). Each `WorkerPool` has `queues`
|
|
111
|
+
(the segment's queue names, stripped, without the ordering `+`; `*` and a leading `-` are kept as written), `shape` (a
|
|
112
|
+
`QueueShape`), `threads?`, `fibers?` and `concurrency`. For `'+latency:2;io,downloads:5x100f;*:3'`, the pools are
|
|
113
|
+
`["latency"]` (2 threads), `["io", "downloads"]` (500 fibers on 5 reactors) and `["*"]` (3 threads), so
|
|
114
|
+
`worker_concurrency` is 505.
|
|
115
|
+
|
|
116
|
+
They build nothing and do not touch the database, so they work in an ERB `database.yml`. `worker_concurrency` is the
|
|
117
|
+
number of ActiveRecord connection leases running jobs can need at once:
|
|
118
|
+
|
|
119
|
+
```erb
|
|
120
|
+
# config/database.yml
|
|
121
|
+
<%
|
|
122
|
+
rails_max_threads = ENV.fetch('RAILS_MAX_THREADS', 5).to_i
|
|
123
|
+
# +1 for GoodJob's LISTEN notifier, +2 for cron and its other executors.
|
|
124
|
+
good_job_connections = GoodJob::AsyncExecutor.worker_concurrency + 1 + 2
|
|
125
|
+
max_connections =
|
|
126
|
+
case GoodJob.configuration.execution_mode
|
|
127
|
+
when :inline then rails_max_threads
|
|
128
|
+
when :external then GoodJob.cli? ? good_job_connections : rails_max_threads
|
|
129
|
+
when :async, :async_server, :async_all then rails_max_threads + good_job_connections
|
|
130
|
+
end
|
|
131
|
+
%>
|
|
132
|
+
production:
|
|
133
|
+
adapter: postgresql
|
|
134
|
+
database: app_production
|
|
135
|
+
max_connections: <%= max_connections %>
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- `database.yml` is read while the app boots, before the `good_job` command applies its own flags. It does not see
|
|
139
|
+
`--queues`, `--threads` or `--max-threads`, and a segment without a count (including the default `*`) would be
|
|
140
|
+
counted with the default thread count instead of the flag. Set them with `GOOD_JOB_QUEUES` and `GOOD_JOB_THREADS`,
|
|
141
|
+
or `config.good_job.queues` and `config.good_job.threads`.
|
|
142
|
+
- `database.yml` is read when ActiveRecord loads, which can happen before `config/initializers/good_job.rb` runs. Put
|
|
143
|
+
`config.good_job` queue and thread settings in `config/application.rb` or `config/environments/*`, or use the
|
|
144
|
+
environment variables, so the helpers see them.
|
|
145
|
+
- Pipe-delimited subprocess pools (`'default:5|io:500f'`) are flattened, as GoodJob flattens them to run in one
|
|
146
|
+
process, so the helpers count every pool. A subprocess forked by the supervisor inherits the supervisor's
|
|
147
|
+
`GoodJob.configuration` and its `database.yml`, so this total covers each subprocess (each runs only its own pool).
|
|
148
|
+
For one subprocess's number, pass its configuration: `worker_concurrency(GoodJob.configuration.subprocess_configs[i])`.
|
|
149
|
+
- The number is per process. Postgres's own `max_connections` has to cover it for every process: each subprocess,
|
|
150
|
+
plus the web servers' pools.
|
|
151
|
+
|
|
152
|
+
With [active_record-async_connection_pool](#with-active_record-async_connection_pool) (`raw_pool: true`), this number
|
|
153
|
+
sizes the adapter pool (`max_connections`, whose default of 1024 is usually enough already), not the physical
|
|
154
|
+
connections. Those are bounded by `max_raw_connections`, which should follow how many jobs run statements at once
|
|
155
|
+
(see the sizing notes below), not the fiber count. Don't size `max_raw_connections` from `worker_concurrency`.
|
|
156
|
+
|
|
157
|
+
### With active_record-async_connection_pool
|
|
158
|
+
|
|
159
|
+
The better fit is
|
|
160
|
+
[active_record-async_connection_pool](https://github.com/mintyfresh/active_record-async_connection_pool), which lets
|
|
161
|
+
fibers share a small pool of physical connections. Enable `raw_pool` for the database:
|
|
162
|
+
|
|
163
|
+
```yaml
|
|
164
|
+
# config/database.yml
|
|
165
|
+
production:
|
|
166
|
+
adapter: postgresql
|
|
167
|
+
database: app_production
|
|
168
|
+
raw_pool: true
|
|
169
|
+
max_raw_connections: 11
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
With it, 500 fibers can share a handful of connections, and a fiber holds one only while it runs a statement or has a
|
|
173
|
+
transaction open. Use it with `lock_strategy = :skiplocked` (see below), so jobs hold no session in between.
|
|
174
|
+
|
|
175
|
+
Sizing notes:
|
|
176
|
+
|
|
177
|
+
- GoodJob's notifier keeps a `LISTEN` session open, which pins one raw connection for the life of the process. Set
|
|
178
|
+
`max_raw_connections` to the number of connections your jobs need at once, plus 1.
|
|
179
|
+
- The first wave of new adapters loads ActiveRecord's type maps, which costs CPU on the reactor.
|
|
180
|
+
- Each new connection pays for SCRAM authentication on the reactor thread. For latency-sensitive starts, warm the pool
|
|
181
|
+
(`min_connections` and `preconnect`) before the queue fills.
|
|
182
|
+
|
|
183
|
+
### Lock strategies
|
|
184
|
+
|
|
185
|
+
`:advisory` and `:hybrid` hold a session-level advisory lock for every in-flight job, so each job holds a database
|
|
186
|
+
connection for its whole run, which defeats the point of fibers. A fiber pool logs a warning at boot under either one:
|
|
187
|
+
|
|
188
|
+
```
|
|
189
|
+
GoodJob::Scheduler(queues=io max_fibers=500 reactors=1) runs jobs as fibers under the :hybrid lock strategy, whose
|
|
190
|
+
advisory locks hold a database connection for every in-flight job. Consider lock_strategy :skiplocked.
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
```ruby
|
|
194
|
+
config.good_job.lock_strategy = :skiplocked
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Shutdown and kill
|
|
198
|
+
|
|
199
|
+
On shutdown a fiber pool stops accepting jobs and lets running ones finish. A shutdown that gives up on them has two
|
|
200
|
+
phases, each with its own timeout:
|
|
201
|
+
|
|
202
|
+
1. `shutdown_timeout` (GoodJob's own setting): GoodJob waits this long for running jobs to finish, then kills the pool.
|
|
203
|
+
2. `hard_stop_timeout` (this gem's): the kill sends `Async::Stop` to the jobs still running (so they run their
|
|
204
|
+
`ensure` blocks) and waits up to this long. Reactors still running after that are killed, and the database
|
|
205
|
+
connections of their fibers are closed, so a killed job's advisory locks are released and its transactions roll
|
|
206
|
+
back. Postgres sees the session end either way.
|
|
207
|
+
|
|
208
|
+
This is Resque's pair of timeouts: `shutdown_timeout` is `RESQUE_PRE_SHUTDOWN_TIMEOUT`, `hard_stop_timeout` is
|
|
209
|
+
`RESQUE_TERM_TIMEOUT`.
|
|
210
|
+
|
|
211
|
+
`hard_stop_timeout` defaults to 5 seconds. Set it in an initializer, or with `GOOD_JOB_ASYNC_EXECUTOR_HARD_STOP_TIMEOUT`
|
|
212
|
+
(read when it is not set in code); it is read at each kill, and must be a number of seconds, 0 or more:
|
|
213
|
+
|
|
214
|
+
```ruby
|
|
215
|
+
GoodJob::AsyncExecutor.hard_stop_timeout = 10
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The kill never hangs. When the capsule's `shutdown_timeout` is shorter than `hard_stop_timeout` (and not negative), the
|
|
219
|
+
second phase waits only `shutdown_timeout`. When it is negative (GoodJob's default of -1, "wait forever") or unset, the
|
|
220
|
+
second phase waits `hard_stop_timeout`.
|
|
221
|
+
|
|
222
|
+
- A stuck job can hold up shutdown for about `shutdown_timeout` + `hard_stop_timeout`, plus up to 0.5 seconds for each
|
|
223
|
+
stuck reactor (they are killed one after another, each given that long to die). Keep `shutdown_timeout` +
|
|
224
|
+
`hard_stop_timeout` below your platform's termination grace period (eg. Kubernetes' `terminationGracePeriodSeconds`,
|
|
225
|
+
30 seconds by default).
|
|
226
|
+
- With the default `shutdown_timeout` of -1, `GoodJob.shutdown` waits for jobs forever and never kills, as on threads.
|
|
227
|
+
Only a caller that passes a timeout (`GoodJob.shutdown(timeout: 0)`, `GoodJob.restart(timeout: 0)`) makes GoodJob
|
|
228
|
+
kill, and then a stuck job gets `hard_stop_timeout` before its reactor is killed.
|
|
229
|
+
- After a hard kill under `:skiplocked` or `:hybrid`, the killed jobs come back only after the process has exited and
|
|
230
|
+
about five minutes have passed. That is GoodJob's behaviour, and it is the same on threads.
|
|
231
|
+
- `GoodJob.restart(timeout: positive)` raises `ArgumentError` in every supported GoodJob version, with or without this
|
|
232
|
+
gem (GoodJob passes `timeout: nil` to `Scheduler#restart`). Call `GoodJob.shutdown(timeout:)` and then
|
|
233
|
+
`GoodJob.restart`.
|
|
234
|
+
|
|
235
|
+
## Development reloading
|
|
236
|
+
|
|
237
|
+
With `config.enable_reloading` on, GoodJob wraps each job in `Rails.application.reloader.wrap`, which would reload
|
|
238
|
+
from inside one fiber while others on its reactor thread are mid-job. Fiber pools take Rails' reload lock per reactor
|
|
239
|
+
instead: a reactor holds it while it has jobs running, and only the reactor reloads.
|
|
240
|
+
|
|
241
|
+
When code changes, each reactor stops starting jobs, drains the ones in flight, and then the reload runs and the
|
|
242
|
+
reactor resumes on the new code. The drain is bounded by `shutdown_timeout` (or `hard_stop_timeout` when that is
|
|
243
|
+
negative): after that long, jobs still running get `Async::Stop`, and after as long again the reactor is replaced (as
|
|
244
|
+
on kill).
|
|
245
|
+
Interrupted jobs are retried on the reloaded code: under `:skiplocked` and `:hybrid` a replaced reactor's jobs keep
|
|
246
|
+
their row claim (GoodJob releases it in an `ensure` that a killed fiber cannot finish), so the pool releases those
|
|
247
|
+
claims itself, with GoodJob's own release, once the reactor is gone. Each drain is instrumented as `reload_drain.good_job`.
|
|
248
|
+
|
|
249
|
+
- A job that never yields delays noticing the change: the reload check stats each watched file, and each stat waits
|
|
250
|
+
for Ruby's lock behind the job holding the thread.
|
|
251
|
+
- Limitation: child fibers a job spawns do not inherit the flag that marks the reloader as active, so a
|
|
252
|
+
`reloader.wrap` or an Active Job `execute` inside one can start a reload while other jobs run. Development only.
|
|
253
|
+
|
|
254
|
+
In production (`enable_reloading` off) the reload lock is never touched.
|
|
255
|
+
|
|
256
|
+
## Modes
|
|
257
|
+
|
|
258
|
+
- `:external` (the `good_job` CLI), including pipe-delimited pools, which are flattened as GoodJob flattens them
|
|
259
|
+
in-process.
|
|
260
|
+
- `:async` and `:async_server`: under Falcon the web server is detected when Rails boots during `config.ru` loading. In
|
|
261
|
+
any other setup (a different server, a rake task, a console) use `:async_all`.
|
|
262
|
+
- `:inline` runs jobs in the calling process and ignores the suffix.
|
|
263
|
+
- Forking servers (Puma cluster mode with `preload_app!`): a fiber pool keeps working in a forked child, as GoodJob's
|
|
264
|
+
thread pools do. A pool running at the fork still counts as running there and starts fresh reactors on first use,
|
|
265
|
+
leaving behind the parent's queued jobs and whatever its reactor threads held; one shut down, or shutting down, at
|
|
266
|
+
the fork counts as shut down. Shutting a pool down or restarting it in the child never waits on the parent's
|
|
267
|
+
reactors. GoodJob's own advice to shut it down before forking still applies: its notifier and poller do not survive
|
|
268
|
+
a fork.
|
|
269
|
+
|
|
270
|
+
## Notifications and stats
|
|
271
|
+
|
|
272
|
+
The "started scheduler" log line and the scheduler's name show the shape:
|
|
273
|
+
|
|
274
|
+
```
|
|
275
|
+
GoodJob 4.24.1 started scheduler with queues=io max_fibers=500 reactors=5.
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
`GoodJob::Scheduler#stats` keeps GoodJob's keys, with `max_threads` (and so `active_threads` and `available_threads`)
|
|
279
|
+
counting fibers as `N * M`, so the dashboard and process records keep working. A fiber pool adds `reactors` and
|
|
280
|
+
`fibers_per_reactor`:
|
|
281
|
+
|
|
282
|
+
```ruby
|
|
283
|
+
GoodJob::Scheduler.instances.map(&:stats)
|
|
284
|
+
# => [{ name: "GoodJob::Scheduler(queues=io max_fibers=500 reactors=5)", queues: "io", max_threads: 500,
|
|
285
|
+
# active_threads: 12, available_threads: 488, reactors: 5, fibers_per_reactor: 100, ... }]
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Instrumented with `ActiveSupport::Notifications`:
|
|
289
|
+
|
|
290
|
+
| Name | Payload | When |
|
|
291
|
+
|----------------------------------|--------------------------------------------------|------------------------------|
|
|
292
|
+
| `scheduler_create_pool.good_job` | GoodJob's, plus `reactors`, `fibers_per_reactor` | A fiber pool is created |
|
|
293
|
+
| `reload_drain.good_job` | `reactor` | A reactor drains (a block) |
|
|
294
|
+
|
|
295
|
+
## Limitations
|
|
296
|
+
|
|
297
|
+
- A reactor whose own loop fails (eg. a `FiberError` at very high fiber counts) is reported to
|
|
298
|
+
`GoodJob.on_thread_error`, with a `GoodJob::AsyncExecutor::Error` saying it was replaced, and a fresh reactor takes
|
|
299
|
+
its place. Jobs queued on it but not started are dropped, and picked up again by GoodJob's polling.
|
|
300
|
+
- CPU-bound jobs, and C extensions that block the thread without yielding (`mysql2`, and others), stall the whole
|
|
301
|
+
reactor, since fibers only switch when a job waits. Keep them on thread queues, or use `NxMf` to contain them.
|
|
302
|
+
- Rails per-request state (such as `ActiveSupport::CurrentAttributes`) is not propagated to the child fibers a job
|
|
303
|
+
spawns.
|
|
304
|
+
|
|
305
|
+
## Development
|
|
306
|
+
|
|
307
|
+
```bash
|
|
308
|
+
$ mise install # Ruby, plus the PostgreSQL client
|
|
309
|
+
$ docker compose up -d --wait # PostgreSQL (port 5436)
|
|
310
|
+
$ bin/rspec
|
|
311
|
+
$ bin/rubocop
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
The specs run against a dummy Rails application in `spec/dummy`. The server is selected with `DATABASE_HOST`,
|
|
315
|
+
`DATABASE_PORT`, `DATABASE_USERNAME`, `DATABASE_PASSWORD` and `DATABASE` (and `DATABASE_POOL` for the adapter pool),
|
|
316
|
+
which default to the Docker server above:
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
$ DATABASE_HOST=127.0.0.1 DATABASE_PORT=5436 DATABASE_USERNAME=good_job_async_executor \
|
|
320
|
+
DATABASE_PASSWORD=good_job_async_executor DATABASE=good_job_async_executor_test bin/rspec
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
`bin/rspec spec/falcon` runs the gem under a real Falcon server, enqueuing 100 sleeping jobs that run in-process as
|
|
324
|
+
fibers while `/ping` latency stays low.
|
|
325
|
+
|
|
326
|
+
Run the suite against each GoodJob the gemspec allows with `BUNDLE_GEMFILE`:
|
|
327
|
+
|
|
328
|
+
```bash
|
|
329
|
+
$ BUNDLE_GEMFILE=gemfiles/good_job_4_23.gemfile bin/rspec
|
|
330
|
+
$ BUNDLE_GEMFILE=gemfiles/good_job_latest.gemfile bin/rspec
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
The examples for `active_record-async_connection_pool` run when a checkout of it sits beside this one
|
|
334
|
+
(`../active_record-async_connection_pool`), and are skipped otherwise.
|
|
335
|
+
|
|
336
|
+
## License
|
|
337
|
+
|
|
338
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
data/Rakefile
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
module GoodJob
|
|
5
|
+
module AsyncExecutor
|
|
6
|
+
# Gives back the row claims (`locked_by_id`) of jobs whose reactor was killed and replaced for a development reload.
|
|
7
|
+
#
|
|
8
|
+
# Under `:skiplocked` and `:hybrid` a job is claimed by setting its `locked_by_id` to the process, and GoodJob
|
|
9
|
+
# releases that claim in an `ensure` once the job ends. A killed fiber's `ensure` blocks are cut short at their
|
|
10
|
+
# first yield (a yield re-raises the kill), so the claim stays, and GoodJob never picks the job up again while the
|
|
11
|
+
# process lives: only another process's cleanup releases it, after this one exits. On shutdown that is GoodJob's
|
|
12
|
+
# behaviour on threads too, but a reactor replaced for a reload leaves the process running, so its jobs' claims
|
|
13
|
+
# are released here, the way GoodJob's own cleanup releases them, and the jobs are retried as interrupted.
|
|
14
|
+
module ClaimRelease
|
|
15
|
+
# A job a fiber was running when its reactor was replaced, and the claim it held then.
|
|
16
|
+
Claim = Struct.new(:job, :locked_by_id, :locked_at)
|
|
17
|
+
|
|
18
|
+
class << self
|
|
19
|
+
# Reads the claims of the jobs the fibers are running, before their reactor is killed (unwinding resets
|
|
20
|
+
# `GoodJob::CurrentThread`), and returns a callable that releases them once it is dead. The release runs on a
|
|
21
|
+
# thread of its own, within Rails' executor: GoodJob's models reload in development, and the caller (the
|
|
22
|
+
# executor's watchdog) must not wait on a reload that may itself be waiting on another reactor's drain.
|
|
23
|
+
#
|
|
24
|
+
#: (Array[Fiber], scheduler: untyped) -> ^() -> void
|
|
25
|
+
def prepare(fibers, scheduler:)
|
|
26
|
+
claims = fibers.filter_map { |fiber| claim_of(fiber) }
|
|
27
|
+
-> { release_later(claims, scheduler) unless claims.empty? }
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# The claim of the job the fiber is running, from its isolated execution state, or nil.
|
|
31
|
+
#
|
|
32
|
+
#: (Fiber) -> Claim?
|
|
33
|
+
def claim_of(fiber)
|
|
34
|
+
job = ActiveSupport::IsolatedExecutionState.share_with(fiber) { GoodJob::CurrentThread.job }
|
|
35
|
+
return unless job && job.locked_by_id.present? && job.locked_at
|
|
36
|
+
|
|
37
|
+
Claim.new(job, job.locked_by_id, job.locked_at)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Releases each claim if the job still holds it: a claim already released, or a newer one, is left alone.
|
|
41
|
+
#
|
|
42
|
+
# GoodJob retries a release that fails on a lost connection until its worker's scheduler stops running; the
|
|
43
|
+
# scheduler is set for this thread as GoodJob sets it for its own workers, so that holds here too.
|
|
44
|
+
#
|
|
45
|
+
#: (Array[Claim], untyped) -> void
|
|
46
|
+
def release(claims, scheduler)
|
|
47
|
+
GoodJob::SafeState[:good_job_scheduler] = scheduler
|
|
48
|
+
claims.each { |claim| release_claim(claim) }
|
|
49
|
+
ensure
|
|
50
|
+
GoodJob::SafeState.delete(:good_job_scheduler)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
private
|
|
54
|
+
|
|
55
|
+
#: (Array[Claim], untyped) -> Thread
|
|
56
|
+
def release_later(claims, scheduler)
|
|
57
|
+
Thread.new do
|
|
58
|
+
Thread.current.name = 'good_job-async_executor-claim-release'
|
|
59
|
+
wrap { release(claims, scheduler) }
|
|
60
|
+
rescue Exception => error # rubocop:disable Lint/RescueException
|
|
61
|
+
report(error)
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# GoodJob's own release (4.23.1 and later); GoodJob 4.23.0 has none, and matches the claim the same way here.
|
|
66
|
+
#
|
|
67
|
+
#: (Claim) -> void
|
|
68
|
+
def release_claim(claim)
|
|
69
|
+
model = GoodJob::Job
|
|
70
|
+
if model.respond_to?(:release_lock_claim, true)
|
|
71
|
+
model.send(:release_lock_claim, claim.job, locked_by_id: claim.locked_by_id, locked_at: claim.locked_at)
|
|
72
|
+
else
|
|
73
|
+
attributes = { locked_by_id: nil, locked_at: nil }
|
|
74
|
+
attributes[:lock_type] = nil if model.lock_type_column_exists?
|
|
75
|
+
model.where(id: claim.job.id, locked_by_id: claim.locked_by_id, locked_at: claim.locked_at)
|
|
76
|
+
.update_all(attributes) # rubocop:disable Rails/SkipsModelValidations
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
#: [T] () { () -> T } -> T
|
|
81
|
+
def wrap(&block)
|
|
82
|
+
if defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application
|
|
83
|
+
::Rails.application.executor.wrap(&block)
|
|
84
|
+
else
|
|
85
|
+
yield
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
#: (Exception) -> void
|
|
90
|
+
def report(error)
|
|
91
|
+
if GoodJob.respond_to?(:_on_thread_error)
|
|
92
|
+
GoodJob._on_thread_error(error)
|
|
93
|
+
else
|
|
94
|
+
warn("#{self}: #{error.class}: #{error.message}")
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
end
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# typed: true
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require 'good_job/async_executor/queue_shape'
|
|
5
|
+
|
|
6
|
+
module GoodJob
|
|
7
|
+
module AsyncExecutor
|
|
8
|
+
# Prepended to `GoodJob::Configuration`. Fiber counts belong in the queue string only: GoodJob reads the default
|
|
9
|
+
# thread count with `to_i`, so `GOOD_JOB_THREADS=100f` would silently mean 100 threads. It raises instead.
|
|
10
|
+
module ConfigurationExtension
|
|
11
|
+
# Each default thread count setting: its option and `config.good_job` key, and its environment variable.
|
|
12
|
+
THREAD_SETTINGS = { threads: 'GOOD_JOB_THREADS', max_threads: 'GOOD_JOB_MAX_THREADS' }.freeze
|
|
13
|
+
|
|
14
|
+
#: () -> Integer
|
|
15
|
+
def threads
|
|
16
|
+
reject_fiber_thread_counts!
|
|
17
|
+
super
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
#: () -> Integer
|
|
21
|
+
def max_threads
|
|
22
|
+
reject_fiber_thread_counts!
|
|
23
|
+
super
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
private
|
|
27
|
+
|
|
28
|
+
#: () -> void
|
|
29
|
+
def reject_fiber_thread_counts!
|
|
30
|
+
THREAD_SETTINGS.each do |key, env_var|
|
|
31
|
+
QueueShape.reject_fiber_suffix!(options[key], setting: "The `#{key}:` option (--#{key.to_s.dasherize})")
|
|
32
|
+
QueueShape.reject_fiber_suffix!(rails_config[key], setting: "config.good_job.#{key}")
|
|
33
|
+
QueueShape.reject_fiber_suffix!(env[env_var], setting: env_var)
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|