solid_queue 1.4.0 → 1.6.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fd0590f46160c60f3a496158cf8dc2412803025cd06d94ac423c32f0b688dd77
4
- data.tar.gz: 8c892f457280b1974908d2de0c3e5be5229ff6bcb448ed61c2937ff4566da796
3
+ metadata.gz: d6cda6edb92a7805d6c2c0fc13b2649c2c2df26a4d65e555049efde022cb8d14
4
+ data.tar.gz: c6d0036cbeb743e56faa4ed9fe6756f1a8e3ae3705a402f55440bb14cb3174dc
5
5
  SHA512:
6
- metadata.gz: 0a86b46d35b0cc8aef4a235e401b4470a6f6e64ff8c44ebdefc06f597d6cbe67ea76c786fc1e85caee1c3fc4dd492180530348078890ef74af90461705150a60
7
- data.tar.gz: efeadbeb7dc0d044c801915d6ba4d8c249b249ef0dde8726454a359d3f1a4ce9ad4e2edb6cd19f8c371967059081c0ef2904ea630a0ae620123939ce881f0fdb
6
+ metadata.gz: 5f7420684f8aa122d12e2314aa2445fb31a3f18f2a7bc53b4ceffccccd131a7f6d9408ef776da33dbbfe437be4c835437524279ac6150e57d134cf85698caf7a
7
+ data.tar.gz: cd02de9753ce345ec599d72230f634df0e633f278871df5da4330318fcb92b8820d99612f43fb8d89be348460d1cb198a5bfab34fdce5c6f639709ab8dd426a2
data/README.md CHANGED
@@ -23,6 +23,7 @@ Solid Queue can be used with SQL databases such as MySQL, PostgreSQL, or SQLite,
23
23
  - [Threads, processes, and signals](#threads-processes-and-signals)
24
24
  - [Database configuration](#database-configuration)
25
25
  - [Other configuration settings](#other-configuration-settings)
26
+ - [Validating the configuration](#validating-the-configuration)
26
27
  - [Lifecycle hooks](#lifecycle-hooks)
27
28
  - [Errors when enqueuing](#errors-when-enqueuing)
28
29
  - [Concurrency controls](#concurrency-controls)
@@ -44,7 +45,7 @@ Solid Queue is configured by default in new Rails 8 applications. If you're runn
44
45
  1. `bundle add solid_queue`
45
46
  2. `bin/rails solid_queue:install`
46
47
 
47
- (Note: The minimum supported version of Rails is 7.1 and Ruby is 3.1.6.)
48
+ (Note: The minimum supported version of Rails is 7.1 and Ruby is 3.2.)
48
49
 
49
50
  This will configure Solid Queue as the production Active Job backend, create the configuration files `config/queue.yml` and `config/recurring.yml`, and create the `db/queue_schema.rb`. It'll also create a `bin/jobs` executable wrapper that you can use to start Solid Queue.
50
51
 
@@ -203,6 +204,10 @@ Or you can also set the environment variable `SOLID_QUEUE_SUPERVISOR_MODE` to `a
203
204
 
204
205
  **The recommended and default mode is `fork`. Only use `async` if you know what you're doing and have strong reasons to**
205
206
 
207
+ This supervisor mode is separate from a worker's concurrency model. Supervisor mode decides whether supervised processes live in forks or threads. Worker configuration decides whether claimed jobs run in a thread pool (`threads: N`) or as fibers on a single fiber reactor thread (`fibers: N`).
208
+
209
+ Because these are separate concerns, you can combine the default `fork` supervisor mode with fiber workers. In that setup, each worker process gets its own fiber reactor and bounded fiber count.
210
+
206
211
  ## Configuration
207
212
 
208
213
  By default, Solid Queue will try to find your configuration under `config/queue.yml`, but you can set a different path using the environment variable `SOLID_QUEUE_CONFIG` or by using the `-c/--config_file` option with `bin/jobs`, like this:
@@ -213,6 +218,8 @@ bin/jobs -c config/calendar.yml
213
218
 
214
219
  You can also skip the scheduler process by setting the environment variable `SOLID_QUEUE_SKIP_RECURRING=true`. This is useful for environments like staging, review apps, or development where you don't want any recurring jobs to run. This is equivalent to using the `--skip-recurring` option with `bin/jobs`.
215
220
 
221
+ To run **only** the scheduler (no workers or dispatchers)—for example to isolate recurring tasks on a dedicated process—set `SOLID_QUEUE_ONLY_RECURRING=true` or use the `--only-recurring` option with `bin/jobs`.
222
+
216
223
  This is what this configuration looks like:
217
224
 
218
225
  ```yml
@@ -229,6 +236,9 @@ production:
229
236
  threads: 5
230
237
  polling_interval: 0.1
231
238
  processes: 3
239
+ - queues: "api*"
240
+ fibers: 100
241
+ polling_interval: 0.05
232
242
  scheduler:
233
243
  dynamic_tasks_enabled: true
234
244
  polling_interval: 5
@@ -271,9 +281,11 @@ Here's an overview of the different options:
271
281
 
272
282
  Check the sections below on [how queue order behaves combined with priorities](#queue-order-and-priorities), and [how the way you specify the queues per worker might affect performance](#queues-specification-and-performance).
273
283
 
274
- - `threads`: this is the max size of the thread pool that each worker will have to run jobs. Each worker will fetch this number of jobs from their queue(s), at most and will post them to the thread pool to be run. By default, this is `3`. Only workers have this setting.
275
- It is recommended to set this value less than or equal to the queue database's connection pool size minus 2, as each worker thread uses one connection, and two additional connections are reserved for polling and heartbeat.
276
- - `processes`: this is the number of worker processes that will be forked by the supervisor with the settings given. By default, this is `1`, just a single process. This setting is useful if you want to dedicate more than one CPU core to a queue or queues with the same configuration. Only workers have this setting. **Note**: this option will be ignored if [running in `async` mode](#fork-vs-async-mode).
284
+ - `threads`: configures a worker to execute jobs in a thread pool of this size. By default, workers use `threads: 3`. Only workers have this setting, and it can't be combined with `fibers`.
285
+ It is recommended to set this value less than or equal to the queue database's connection pool size minus 2, as each worker uses connections for polling and heartbeat and thread mode may use additional connections for job execution.
286
+ - `fibers`: configures a worker to execute jobs as fibers on a single fiber reactor thread, with this value as the maximum number of in-flight jobs. It can't be combined with `threads`.
287
+ Fiber workers require fiber-scoped isolated execution state. In Rails apps, set `config.active_support.isolation_level = :fiber` before using `fibers`. Solid Queue refuses to boot fiber workers when isolation remains thread-scoped. On Rails 7.2 and later, a practical starting point is usually `3-5` queue database connections per worker process rather than matching the `fibers` value, because ordinary Active Record query paths can release connections between non-blocking waits. On Rails 7.1, size the queue database pool more conservatively, as in-flight fiber jobs may still retain connections roughly in proportion to `fibers`.
288
+ - `processes`: this is the number of worker processes that will be forked by the supervisor with the settings given. By default, this is `1`, just a single process. This setting is useful if you want to dedicate more than one CPU core to a queue or queues with the same configuration. Only workers have this setting. This works with both `threads` and `fibers` workers as long as the supervisor is running in the default `fork` mode. **Note**: this option is ignored only when the supervisor itself is [running in `async` mode](#fork-vs-async-mode).
277
289
  - `concurrency_maintenance`: whether the dispatcher will perform the concurrency maintenance work. This is `true` by default, and it's useful if you don't use any [concurrency controls](#concurrency-controls) and want to disable it or if you run multiple dispatchers and want some of them to just dispatch jobs without doing anything else.
278
290
 
279
291
 
@@ -338,7 +350,7 @@ FROM solid_queue_ready_executions
338
350
  WHERE queue_name LIKE 'beta%';
339
351
  ```
340
352
 
341
- This type of `DISTINCT` query on a column that's the leftmost column in an index can be performed very fast in MySQL thanks to a technique called [Loose Index Scan](https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html#loose-index-scan). PostgreSQL and SQLite, however, don't implement this technique, which means that if your `solid_queue_ready_executions` table is very big because your queues get very deep, this query will get slow. Normally your `solid_queue_ready_executions` table will be small, but it can happen.
353
+ This type of `DISTINCT` query on a column that's the leftmost column in an index can be performed very fast in MySQL thanks to a technique called [Loose Index Scan](https://dev.mysql.com/doc/refman/8.0/en/group-by-optimization.html#loose-index-scan). PostgreSQL doesn't implement this technique natively, so Solid Queue uses a [recursive CTE](https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-RECURSIVE) to emulate it, achieving similar performance by walking the B-tree index and jumping between distinct values. SQLite doesn't implement loose index scan either, but this is unlikely to be a problem since SQLite is typically used in development with small datasets.
342
354
 
343
355
  Similarly to using prefixes, the same will happen if you have paused queues, because we need to get a list of all queues with a query like
344
356
  ```sql
@@ -364,7 +376,17 @@ queues: back*
364
376
 
365
377
  ### Threads, processes, and signals
366
378
 
367
- Workers in Solid Queue use a thread pool to run work in multiple threads, configurable via the `threads` parameter above. Besides this, parallelism can be achieved via multiple processes on one machine (configurable via different workers or the `processes` parameter above) or by horizontal scaling.
379
+ By default, workers in Solid Queue use a thread pool to run work in multiple threads, configurable via the `threads` parameter above. Workers can also be configured with `fibers`, in which case claimed jobs are executed as fibers on a single reactor thread and bounded by the worker's fiber count. Besides this, parallelism can be achieved via multiple processes on one machine (configurable via different workers or the `processes` parameter above) or by horizontal scaling.
380
+
381
+ Fiber worker execution is best suited for cooperative, mostly I/O-bound jobs. Blocking or CPU-heavy work still blocks the single reactor thread, so it should not be expected to outperform thread mode for every workload.
382
+
383
+ Because fiber workers run multiple fibers on a single thread, Rails must also isolate execution state per fiber rather than per thread. If your app keeps the default thread-scoped isolation level, Solid Queue will raise a boot-time error instead of running fiber workers with shared Active Record state.
384
+
385
+ Keep in mind that `config.active_support.isolation_level = :fiber` applies to your whole application, not just to Solid Queue: if you run Solid Queue inside Puma via [the plugin](#puma-plugin), or combine fiber workers with thread workers in the same process using the supervisor's `async` mode, everything in that process will use fiber-scoped execution state. This is fully supported by Rails, but it's a global setting worth being deliberate about.
386
+
387
+ On Rails 7.2 and later, fiber workers can often use a much smaller queue database pool than an equivalent thread pool. A practical starting point is `3-5` queue database connections per worker process: one for job execution, one for polling, one for heartbeats, plus some headroom. In the default `fork` supervisor mode, that guidance applies per worker process. In supervisor `async` mode, all workers share one process, so add together the requirements for the workers running there.
388
+
389
+ That lower-pool guidance depends on job code not holding connections open across non-blocking waits. APIs such as `ActiveRecord::Base.connection`, `lease_connection`, `connection_pool.checkout`, or long-lived `with_connection` / transaction blocks can pin connections and push fiber workers back toward thread-like pool usage. On Rails 7.1, plan conservatively and assume the configured fiber count can still grow queue database connection usage.
368
390
 
369
391
  The supervisor is in charge of managing these processes, and it responds to the following signals when running in its own process via `bin/jobs` or with [the Puma plugin](#puma-plugin) with the default `fork` mode:
370
392
  - `TERM`, `INT`: starts graceful termination. The supervisor will send a `TERM` signal to its supervised processes, and it'll wait up to `SolidQueue.shutdown_timeout` time until they're done. If any supervised processes are still around by then, it'll send a `QUIT` signal to them to indicate they must exit.
@@ -372,8 +394,14 @@ The supervisor is in charge of managing these processes, and it responds to the
372
394
 
373
395
  When receiving a `QUIT` signal, if workers still have jobs in-flight, these will be returned to the queue when the processes are deregistered.
374
396
 
397
+ On Windows, the `QUIT` signal can't be trapped, so the supervisor only responds to `TERM` and `INT` there.
398
+
375
399
  If processes have no chance of cleaning up before exiting (e.g. if someone pulls a cable somewhere), in-flight jobs might remain claimed by the processes executing them. Processes send heartbeats, and the supervisor checks and prunes processes with expired heartbeats. Jobs that were claimed by processes with an expired heartbeat will be marked as failed with a `SolidQueue::Processes::ProcessPrunedError`. You can configure both the frequency of heartbeats and the threshold to consider a process dead. See the section below for this.
376
400
 
401
+ Worker heartbeats are driven by a separate timer task, not by the worker execution backend itself. This means fiber workers do not rely on the reactor loop to prove liveness. However, liveness is still tracked at the worker-process level, not at the individual thread or fiber level.
402
+
403
+ This means finished and failed jobs still follow the normal Solid Queue lifecycle, but a single stuck job can remain claimed if the worker process itself is still alive. If you need stronger stuck-job detection, that requires an explicit timeout or watchdog mechanism on top of process heartbeats.
404
+
377
405
  In a similar way, if a worker is terminated in any other way not initiated by the above signals (e.g. a worker is sent a `KILL` signal), jobs in progress will be marked as failed so that they can be inspected, with a `SolidQueue::Processes::ProcessExitError`. Sometimes a job in particular is responsible for this, for example, if it has a memory leak and you have a mechanism to kill processes over a certain memory threshold, so this will help identifying this kind of situation.
378
406
 
379
407
 
@@ -389,7 +417,7 @@ _Note_: The settings in this section should be set in your `config/application.r
389
417
 
390
418
  There are several settings that control how Solid Queue works that you can set as well:
391
419
  - `logger`: the logger you want Solid Queue to use. Defaults to the app logger.
392
- - `app_executor`: the [Rails executor](https://guides.rubyonrails.org/threading_and_code_execution.html#executor) used to wrap asynchronous operations, defaults to the app executor
420
+ - `app_executor`: the [Rails executor](https://guides.rubyonrails.org/threading_and_code_execution.html#executor) used to wrap background operations, defaults to the app executor
393
421
  - `on_thread_error`: custom lambda/Proc to call when there's an error within a Solid Queue thread that takes the exception raised as argument. Defaults to
394
422
 
395
423
  ```ruby
@@ -401,6 +429,7 @@ There are several settings that control how Solid Queue works that you can set a
401
429
  - `use_skip_locked`: whether to use `FOR UPDATE SKIP LOCKED` when performing locking reads. This will be automatically detected in the future, and for now, you only need to set this to `false` if your database doesn't support it. For MySQL, that'd be versions < 8; for MariaDB, versions < 10.6; and for PostgreSQL, versions < 9.5. If you use SQLite, this has no effect, as writes are sequential.
402
430
  - `process_heartbeat_interval`: the heartbeat interval that all processes will follow—defaults to 60 seconds.
403
431
  - `process_alive_threshold`: how long to wait until a process is considered dead after its last heartbeat—defaults to 5 minutes.
432
+ - `fork_boot_timeout`: how long a forked process can take to finish booting before the supervisor replaces it—defaults to 5 minutes. It only applies in the default `fork` mode.
404
433
  - `shutdown_timeout`: time the supervisor will wait since it sent the `TERM` signal to its supervised processes before sending a `QUIT` version to them requesting immediate termination—defaults to 5 seconds.
405
434
  - `silence_polling`: whether to silence Active Record logs emitted when polling for both workers and dispatchers—defaults to `true`.
406
435
  - `supervisor_pidfile`: path to a pidfile that the supervisor will create when booting to prevent running more than one supervisor in the same host, or in case you want to use it for a health check. It's `nil` by default.
@@ -408,6 +437,22 @@ There are several settings that control how Solid Queue works that you can set a
408
437
  - `clear_finished_jobs_after`: period to keep finished jobs around, in case `preserve_finished_jobs` is true — defaults to 1 day. When installing Solid Queue, [a recurring job](#recurring-tasks) is automatically configured to clear finished jobs every hour on the 12th minute in batches. You can edit the `recurring.yml` configuration to change this as you see fit.
409
438
  - `default_concurrency_control_period`: the value to be used as the default for the `duration` parameter in [concurrency controls](#concurrency-controls). It defaults to 3 minutes.
410
439
 
440
+ ### Validating the configuration
441
+
442
+ You can validate the Solid Queue configuration ahead of time, without starting any process. This is handy in deploy scripts or CI to catch mistakes—a typo in `recurring.yml`, no processes configured, and so on—before they cause a supervisor to boot into a broken state:
443
+
444
+ ```bash
445
+ # Using the bin/jobs binstub
446
+ bin/jobs check
447
+
448
+ # Or via rake
449
+ bin/rails solid_queue:check
450
+ ```
451
+
452
+ Both commands validate the configuration for the current Rails environment. On success they print `Solid Queue configuration is valid.` and exit `0`; otherwise they print the errors and exit non-zero. When the number of threads is larger than the [database connection pool](#database-configuration), they also print an advisory warning about it—the same one the supervisor logs on boot. They're tolerant of a missing database connection, so they can run on CI or deploy hosts without database credentials.
453
+
454
+ `bin/jobs check` accepts the same options as `bin/jobs start` (e.g. `--config_file`, `--recurring_schedule_file`, `--skip-recurring`). The rake task honors the same environment variables Solid Queue already uses: `SOLID_QUEUE_CONFIG`, `SOLID_QUEUE_RECURRING_SCHEDULE`, and `SOLID_QUEUE_SKIP_RECURRING`. To validate a specific environment's configuration, set `RAILS_ENV`, for example `RAILS_ENV=production bin/jobs check`.
455
+
411
456
 
412
457
  ## Lifecycle hooks
413
458
 
@@ -471,7 +516,7 @@ Solid Queue extends Active Job with concurrency controls, that allows you to lim
471
516
 
472
517
  ```ruby
473
518
  class MyJob < ApplicationJob
474
- limits_concurrency to: max_concurrent_executions, key: ->(arg1, arg2, **) { ... }, duration: max_interval_to_guarantee_concurrency_limit, group: concurrency_group, on_conflict: on_conflict_behaviour
519
+ limits_concurrency to: max_concurrent_executions, key: ->(arg1, arg2, *) { ... }, duration: max_interval_to_guarantee_concurrency_limit, group: concurrency_group, on_conflict: on_conflict_behaviour
475
520
 
476
521
  # ...
477
522
  ```
@@ -690,6 +735,8 @@ bin/jobs --recurring_schedule_file=config/schedule.yml
690
735
 
691
736
  You can completely disable recurring tasks by setting the environment variable `SOLID_QUEUE_SKIP_RECURRING=true` or by using the `--skip-recurring` option with `bin/jobs`.
692
737
 
738
+ To run only the scheduler (no workers or dispatchers), set `SOLID_QUEUE_ONLY_RECURRING=true` or use `--only-recurring` with `bin/jobs`.
739
+
693
740
  The configuration itself looks like this:
694
741
 
695
742
  ```yml
@@ -705,7 +752,9 @@ production:
705
752
 
706
753
  Tasks are specified as a hash/dictionary, where the key will be the task's key internally. Each task needs to either have a `class`, which will be the job class to enqueue, or a `command`, which will be eval'ed in the context of a job (`SolidQueue::RecurringJob`) that will be enqueued according to its schedule, in the `solid_queue_recurring` queue.
707
754
 
708
- Each task needs to have also a schedule, which is parsed using [Fugit](https://github.com/floraison/fugit), so it accepts anything [that Fugit accepts as a cron](https://github.com/floraison/fugit?tab=readme-ov-file#fugitcron). You can optionally supply the following for each task:
755
+ Each task needs to have also a schedule, which is parsed using [Fugit](https://github.com/floraison/fugit), so it accepts anything [that Fugit accepts as a cron](https://github.com/floraison/fugit?tab=readme-ov-file#fugitcron). Schedules can include a time zone (e.g. `0 9 * * * America/New_York` or `every day at 9am America/New_York`). When a schedule doesn't specify one, it's interpreted in the application's configured time zone (`config.time_zone`) by default. You can change or disable this default with `config.solid_queue.time_zone`; setting it to `nil` falls back to the system's local time.
756
+
757
+ You can optionally supply the following for each task:
709
758
  - `args`: the arguments to be passed to the job, as a single argument, a hash, or an array of arguments that can also include kwargs as the last element in the array.
710
759
 
711
760
  The job in the example configuration above will be enqueued every second as:
@@ -781,6 +830,8 @@ SolidQueue.unschedule_recurring_task("my_dynamic_task")
781
830
 
782
831
  Only dynamic tasks can be unscheduled at runtime. Attempting to unschedule a static task (defined in `config/recurring.yml`) will raise an `ActiveRecord::RecordNotFound` error.
783
832
 
833
+ To update an existing dynamic task, unschedule it and then schedule it again with the new options. A running scheduler only detects dynamic tasks being created and deleted, so updating a `SolidQueue::RecurringTask` record in place (for example, changing its `schedule` with `update!`) won't be picked up until the scheduler restarts.
834
+
784
835
  Tasks scheduled like this persist between Solid Queue's restarts and won't stop running until you manually unschedule them.
785
836
 
786
837
  ## Inspiration
data/UPGRADING.md CHANGED
@@ -1,3 +1,14 @@
1
+ # Upgrading to version 1.5.x
2
+ Ruby 3.1 is no longer supported, as it reached end-of-life in March 2025. Solid Queue now requires Ruby 3.2 or newer. If you're still on Ruby 3.1, Bundler will continue to resolve solid_queue 1.4.x for you, but you won't receive any new versions until you upgrade Ruby.
3
+
4
+ Recurring schedules that don't specify a time zone are now interpreted in your application's configured time zone (`config.time_zone`) by default, instead of the system's local time. This only affects schedules without an explicit time zone (e.g. `every day at 9am`); schedules that already include one (e.g. `0 9 * * * America/New_York`) are unaffected.
5
+
6
+ If your `config.time_zone` differs from the system time where your processes run, recurring jobs may fire at a different wall-clock time than before. To keep the previous behavior, set:
7
+
8
+ ```ruby
9
+ config.solid_queue.time_zone = nil
10
+ ```
11
+
1
12
  # Upgrading to version 1.x
2
13
  The value returned for `enqueue_after_transaction_commit?` has changed to `true`, and it's no longer configurable. If you want to change this, you need to use Active Job's configuration options.
3
14
 
@@ -43,7 +43,6 @@ class SolidQueue::ClaimedExecution < SolidQueue::Execution
43
43
  SolidQueue.instrument(:fail_many_claimed) do |payload|
44
44
  executions.each do |execution|
45
45
  execution.failed_with(error)
46
- execution.unblock_next_job
47
46
  end
48
47
 
49
48
  payload[:process_ids] = executions.map(&:process_id).uniq
@@ -71,13 +70,11 @@ class SolidQueue::ClaimedExecution < SolidQueue::Execution
71
70
  failed_with(result.error)
72
71
  raise result.error
73
72
  end
74
- ensure
75
- unblock_next_job
76
73
  end
77
74
 
78
75
  def release
79
76
  SolidQueue.instrument(:release_claimed, job_id: job.id, process_id: process_id) do
80
- transaction do
77
+ unless_already_finalized do
81
78
  job.dispatch_bypassing_concurrency_limits
82
79
  destroy!
83
80
  end
@@ -89,14 +86,7 @@ class SolidQueue::ClaimedExecution < SolidQueue::Execution
89
86
  end
90
87
 
91
88
  def failed_with(error)
92
- transaction do
93
- job.failed_with(error)
94
- destroy!
95
- end
96
- end
97
-
98
- def unblock_next_job
99
- job.unblock_next_blocked_job
89
+ finalize { job.failed_with(error) }
100
90
  end
101
91
 
102
92
  private
@@ -108,9 +98,28 @@ class SolidQueue::ClaimedExecution < SolidQueue::Execution
108
98
  end
109
99
 
110
100
  def finished
111
- transaction do
112
- job.finished!
101
+ finalize { job.finished! }
102
+ end
103
+
104
+ def finalize
105
+ finalized = unless_already_finalized do
106
+ yield
113
107
  destroy!
108
+ true
109
+ end
110
+
111
+ # Unblock the next job outside the finalize transaction so a failure while
112
+ # releasing the concurrency lock or dispatching the next job can't roll back
113
+ # a job that already finished or failed. Only the actor that owned and
114
+ # finalized the claim gets here, so the lock is released exactly once.
115
+ job.unblock_next_blocked_job if finalized
116
+ end
117
+
118
+ def unless_already_finalized
119
+ transaction do
120
+ return false unless self.class.unscoped.lock.find_by(id: id)
121
+
122
+ yield
114
123
  end
115
124
  end
116
125
  end
@@ -41,15 +41,16 @@ module SolidQueue
41
41
  end
42
42
 
43
43
  def successfully_dispatched(jobs)
44
- dispatched_and_ready(jobs) + dispatched_and_blocked(jobs)
44
+ jobs_by_id = jobs.index_by(&:id)
45
+ dispatched_and_ready(jobs_by_id) + dispatched_and_blocked(jobs_by_id)
45
46
  end
46
47
 
47
- def dispatched_and_ready(jobs)
48
- where(id: ReadyExecution.where(job_id: jobs.map(&:id)).pluck(:job_id))
48
+ def dispatched_and_ready(jobs_by_id)
49
+ ReadyExecution.where(job_id: jobs_by_id.keys).pluck(:job_id).map { |id| jobs_by_id[id] }
49
50
  end
50
51
 
51
- def dispatched_and_blocked(jobs)
52
- where(id: BlockedExecution.where(job_id: jobs.map(&:id)).pluck(:job_id))
52
+ def dispatched_and_blocked(jobs_by_id)
53
+ BlockedExecution.where(job_id: jobs_by_id.keys).pluck(:job_id).map { |id| jobs_by_id[id] }
53
54
  end
54
55
  end
55
56
 
@@ -23,7 +23,8 @@ module SolidQueue
23
23
  end
24
24
 
25
25
  def successfully_scheduled(jobs)
26
- where(id: ScheduledExecution.where(job_id: jobs.map(&:id)).pluck(:job_id))
26
+ jobs_by_id = jobs.index_by(&:id)
27
+ ScheduledExecution.where(job_id: jobs_by_id.keys).pluck(:job_id).map { |id| jobs_by_id[id] }
27
28
  end
28
29
  end
29
30
 
@@ -6,9 +6,7 @@ module SolidQueue
6
6
 
7
7
  class << self
8
8
  def all
9
- Job.select(:queue_name).distinct.collect do |job|
10
- new(job.queue_name)
11
- end
9
+ Job.distinct_values_of(:queue_name).map { |name| new(name) }
12
10
  end
13
11
 
14
12
  def find_by_name(name)
@@ -43,7 +43,7 @@ module SolidQueue
43
43
  end
44
44
 
45
45
  def all_queues
46
- relation.distinct(:queue_name).pluck(:queue_name)
46
+ relation.distinct_values_of(:queue_name)
47
47
  end
48
48
 
49
49
  def exact_names
@@ -53,7 +53,7 @@ module SolidQueue
53
53
  def prefixed_names
54
54
  if prefixes.empty? then []
55
55
  else
56
- relation.where(([ "queue_name LIKE ?" ] * prefixes.count).join(" OR "), *prefixes).distinct(:queue_name).pluck(:queue_name)
56
+ relation.where(([ "queue_name LIKE ?" ] * prefixes.count).join(" OR "), *prefixes).distinct_values_of(:queue_name)
57
57
  end
58
58
  end
59
59
 
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SolidQueue
4
+ class Record
5
+ module DistinctValues
6
+ extend ActiveSupport::Concern
7
+
8
+ # PostgreSQL has no native loose index scan, so a plain DISTINCT on a leading
9
+ # index column degrades to a full index scan on large tables. We emulate one
10
+ # with a recursive CTE that walks the index jumping between distinct values.
11
+ class_methods do
12
+ def distinct_values_of(column)
13
+ if loose_index_scan_emulation_needed?
14
+ loose_distinct_via_recursive_cte(column)
15
+ else
16
+ distinct.pluck(column)
17
+ end
18
+ end
19
+
20
+ private
21
+ def loose_index_scan_emulation_needed?
22
+ connection_pool.with_connection { |connection| connection.adapter_name == "PostgreSQL" }
23
+ end
24
+
25
+ # Emulates a loose index scan, honoring the current scope (e.g. LIKE prefixes)
26
+ # by building the anchor and the recursive step as scoped relations, whose
27
+ # #to_sql inlines any bind parameters so they can be embedded in the raw CTE.
28
+ def loose_distinct_via_recursive_cte(column)
29
+ connection_pool.with_connection do |connection|
30
+ col = connection.quote_column_name(column)
31
+
32
+ connection.select_values(<<~SQL.squish)
33
+ WITH RECURSIVE t AS (
34
+ (#{next_distinct_value(col, "#{col} IS NOT NULL")})
35
+ UNION ALL
36
+ SELECT (#{next_distinct_value(col, "#{col} > t.#{col}")}) FROM t WHERE t.#{col} IS NOT NULL
37
+ )
38
+ SELECT #{col} FROM t WHERE #{col} IS NOT NULL
39
+ SQL
40
+ end
41
+ end
42
+
43
+ # Smallest value of `col` within the current scope that matches `condition`.
44
+ def next_distinct_value(col, condition)
45
+ all.where(Arel.sql(condition)).reorder(Arel.sql(col)).limit(1).select(Arel.sql(col)).to_sql
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -3,6 +3,9 @@
3
3
  module SolidQueue
4
4
  class Record < ActiveRecord::Base
5
5
  self.abstract_class = true
6
+ self.strict_loading_by_default = false
7
+
8
+ include DistinctValues
6
9
 
7
10
  connects_to(**SolidQueue.connects_to) if SolidQueue.connects_to
8
11
 
@@ -21,6 +24,16 @@ module SolidQueue
21
24
  end
22
25
  end
23
26
 
27
+ def warn_about_pending_migrations
28
+ SolidQueue.deprecator.warn(<<~DEPRECATION)
29
+ Solid Queue has pending database migrations. To get the new migration files, run:
30
+ rails solid_queue:update
31
+ And then:
32
+ rails db:migrate
33
+ These migrations will be required after version #{SolidQueue.next_major_version}.0
34
+ DEPRECATION
35
+ end
36
+
24
37
  # Pass index hints to the query optimizer using SQL comment hints.
25
38
  # Uses MySQL 8 optimizer hint query comments, which SQLite and
26
39
  # PostgreSQL ignore.
@@ -56,16 +56,17 @@ module SolidQueue
56
56
  end
57
57
  end
58
58
 
59
- def delay_from_now
60
- [ (next_time - Time.current).to_f, 0.1 ].max
59
+
60
+ def next_time_after(time)
61
+ parsed_schedule_with_time_zone.next_time(time).utc
61
62
  end
62
63
 
63
64
  def next_time
64
- parsed_schedule.next_time.utc
65
+ parsed_schedule_with_time_zone.next_time.utc
65
66
  end
66
67
 
67
68
  def previous_time
68
- parsed_schedule.previous_time.utc
69
+ parsed_schedule_with_time_zone.previous_time.utc
69
70
  end
70
71
 
71
72
  def last_enqueued_time
@@ -85,6 +86,7 @@ module SolidQueue
85
86
 
86
87
  perform_later.tap do |job|
87
88
  unless job.successfully_enqueued?
89
+ report_enqueue_error(job.enqueue_error, at: at)
88
90
  payload[:enqueue_error] = job.enqueue_error&.message
89
91
  end
90
92
  end
@@ -97,6 +99,7 @@ module SolidQueue
97
99
  payload[:skipped] = true
98
100
  false
99
101
  rescue Job::EnqueueError => error
102
+ report_enqueue_error(error, at: at)
100
103
  payload[:enqueue_error] = error.message
101
104
  false
102
105
  end
@@ -168,11 +171,24 @@ module SolidQueue
168
171
  end
169
172
  end
170
173
 
174
+ def parsed_schedule_with_time_zone
175
+ @parsed_schedule_with_time_zone ||= apply_default_time_zone_to(parsed_schedule)
176
+ end
171
177
 
172
178
  def parsed_schedule
173
179
  @parsed_schedule ||= Fugit.parse(schedule, multi: :fail)
174
180
  end
175
181
 
182
+ def apply_default_time_zone_to(schedule)
183
+ if schedule.respond_to?(:zone) && schedule.zone.nil? && default_time_zone.present?
184
+ Fugit.parse("#{schedule.to_cron_s} #{default_time_zone}", multi: :fail)
185
+ else
186
+ schedule
187
+ end
188
+ rescue ArgumentError
189
+ schedule
190
+ end
191
+
176
192
  def job_class
177
193
  @job_class ||= class_name.present? ? class_name.safe_constantize : self.class.default_job_class
178
194
  end
@@ -180,5 +196,15 @@ module SolidQueue
180
196
  def enqueue_options
181
197
  { queue: queue_name, priority: priority }.compact
182
198
  end
199
+
200
+ def default_time_zone
201
+ SolidQueue.time_zone
202
+ end
203
+
204
+ def report_enqueue_error(error, at:)
205
+ if error
206
+ Rails.error.report(error, handled: true, source: "application.solid_queue", context: { task: key, at: at })
207
+ end
208
+ end
183
209
  end
184
210
  end
@@ -32,7 +32,13 @@ module SolidQueue
32
32
 
33
33
  class Proxy
34
34
  def self.signal_all(jobs)
35
- Semaphore.where(key: jobs.map(&:concurrency_key)).update_all("value = value + 1")
35
+ # Guard against incrementing a semaphore's value beyond its limit. Jobs can
36
+ # have different limits, so group them and cap each group with `value < limit`.
37
+ jobs.group_by { |job| job.concurrency_limit || 1 }.each do |limit, grouped_jobs|
38
+ Semaphore.where(key: grouped_jobs.map(&:concurrency_key))
39
+ .where(value: ...limit)
40
+ .update_all("value = value + 1")
41
+ end
36
42
  end
37
43
 
38
44
  def initialize(job)
@@ -8,9 +8,17 @@ module ActiveJob
8
8
  #
9
9
  # Rails.application.config.active_job.queue_adapter = :solid_queue
10
10
  class SolidQueueAdapter < (Rails::VERSION::MAJOR == 7 && Rails::VERSION::MINOR == 1 ? Object : AbstractAdapter)
11
- class_attribute :stopping, default: false, instance_writer: false
11
+ class_attribute :stopping, default: false, instance_writer: false, instance_predicate: false
12
12
  SolidQueue.on_worker_stop { self.stopping = true }
13
13
 
14
+ # Accept an optional job argument for compatibility with Rails main, which
15
+ # began passing the running job to +queue_adapter.stopping?+ so adapters can
16
+ # decide whether to checkpoint based on it. We rely solely on the worker
17
+ # shutdown flag, so the argument is ignored.
18
+ def stopping?(_job = nil)
19
+ self.class.stopping
20
+ end
21
+
14
22
  def enqueue_after_transaction_commit?
15
23
  true
16
24
  end
@@ -6,7 +6,7 @@ default: &default
6
6
  - queues: "*"
7
7
  threads: 3
8
8
  processes: <%%= ENV.fetch("JOB_CONCURRENCY", 1) %>
9
- polling_interval: 0.1
9
+ polling_interval: 1
10
10
 
11
11
  development:
12
12
  <<: *default
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators/active_record"
4
+
5
+ class SolidQueue::UpdateGenerator < Rails::Generators::Base
6
+ include ActiveRecord::Generators::Migration
7
+
8
+ source_root File.expand_path("templates", __dir__)
9
+
10
+ class_option :database, type: :string, aliases: %i[ --db ], default: "queue",
11
+ desc: "The database that Solid Queue uses. Defaults to `queue`"
12
+
13
+ def copy_new_migrations
14
+ Dir.glob(File.join(self.class.source_root, "db", "*.rb")).each do |migration_file|
15
+ name = File.basename(migration_file)
16
+ migration_template File.join("db", name), File.join(db_migrate_path, name), skip: true
17
+ end
18
+ end
19
+ end
@@ -20,6 +20,10 @@ module SolidQueue
20
20
  desc: "Whether to skip recurring tasks scheduling",
21
21
  banner: "SOLID_QUEUE_SKIP_RECURRING"
22
22
 
23
+ class_option :only_recurring, type: :boolean,
24
+ desc: "Whether to run only the scheduler process for recurring tasks",
25
+ banner: "SOLID_QUEUE_ONLY_RECURRING"
26
+
23
27
  def self.exit_on_failure?
24
28
  true
25
29
  end
@@ -30,5 +34,11 @@ module SolidQueue
30
34
  def start
31
35
  SolidQueue::Supervisor.start(**options.symbolize_keys)
32
36
  end
37
+
38
+ desc :check, "Validates the Solid Queue configuration for the current Rails env without starting anything. Exits non-zero on errors."
39
+ def check
40
+ configuration = SolidQueue::Configuration.new(**options.symbolize_keys)
41
+ exit 1 unless configuration.check
42
+ end
33
43
  end
34
44
  end