mankai-jobs-sql 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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2b9b1ec211c77161f8a8ba790a3ff8d48b91781635631e948e9cb2678dd56980
4
+ data.tar.gz: 22291e75ff91411ff2d20c1915963480a2625e2ed5278e3474003d412abd84d8
5
+ SHA512:
6
+ metadata.gz: 2da35e2aaf9155fbdb3615470991419b52a3acf06221a822718a654e5b2825710df62fa6fc99594a62bc75fd875c2f08632554e9895689d5b6e18558c51a6746
7
+ data.tar.gz: '009d0f817d5ae536eac340dc7f2a60b28955bd0dbedc967f7218ea60f82c68fe8064fbb717ee96be33cb6995ffa0cc73d3fa96a1ff4a9a68d768e53bc8ebb7f5'
data/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Break Versioning](https://www.taoensso.com/break-versioning).
7
+
8
+ ## [0.1.0]
9
+
10
+ ### Added
11
+
12
+ - SQL backend for mankai-jobs, tested on PostgreSQL 16–19, MySQL 9 and 26, MariaDB 12 and 13, and SQLite.
13
+ - Worker, dispatcher, scheduler and supervisor processes, run as forks or threads, with lifecycle hooks.
14
+ - Concurrency limits, unique jobs, recorded output, per-job and per-queue retention, and transactional completion.
15
+ - Runtime recurring tasks, queue pause and resume, and admin operations (`queues`, `job`, `failed_jobs`, `retry_failed` and more).
16
+ - Idempotent, versioned migrations installed by `hanami jobs install`.
17
+ - Explanations for missing tables on Hanami's error page (Hanami 3.1+).
18
+ - A warning at boot when a SQLite connection would stall other threads while waiting for a lock, with the one-line fix.
19
+
20
+ ### Fixed
21
+
22
+ - Queue latency is now correct on hosts outside UTC; zone-less SQLite timestamps are read as UTC.
23
+ - Every `mankai.jobs.sql.*` event is registered when the backend is built, so you can subscribe to them before they first fire.
24
+ - "`retry_failed` and `discard_failed` accept job ids (the UUIDs `job(id)` takes and `failed_jobs` returns as `:uuid`); record ids still work."
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Ibrahim Diallo <thisis@ibrahimd.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,268 @@
1
+ <img src="../../assets/logo/mankai-logo.svg" alt="Mankai" width="72">
2
+
3
+ # mankai-jobs-sql
4
+
5
+ The SQL backend for [mankai-jobs](https://github.com/thisisibrahimd/mankai/tree/main/gems/mankai-jobs). It stores jobs in your database and runs them with worker, dispatcher and scheduler processes.
6
+
7
+ | Database | Tested on | Notes |
8
+ |---|---|---|
9
+ | PostgreSQL 9.5+ | 16.16, 17.12, 18.7, 19.0 | |
10
+ | MySQL 8+ | 9.7.4, 26.10.0 | claims use `FOR UPDATE SKIP LOCKED`; connect with `fractional_seconds=true` |
11
+ | MariaDB 10.6+ | 12.3.4, 13.1.2 | as MySQL |
12
+ | SQLite | 3 | writes are serialized, which is fine for small apps |
13
+
14
+ **MySQL and MariaDB:** add `fractional_seconds=true` to the database URL (for example `mysql2://.../app?fractional_seconds=true`), before running the migrations. Without it, Sequel stores whole seconds, so a job due "in 0.2 seconds" can run up to a second off, and mankai-jobs logs a warning at boot. If the migrations already ran without it, add it to the URL, then copy `add_mankai_jobs_controls` into a new migration (with a new timestamp) and migrate. It's idempotent, and with the option on it upgrades the time columns to microseconds.
15
+
16
+ **SQLite:** by default, a SQLite connection waiting for a lock holds Ruby's global lock, so every other thread in the process stops for up to 5 seconds, including the one holding the lock. Worker threads then stall, and can fail with "database is locked". Tell the connection to wait without blocking other threads:
17
+
18
+ ```ruby
19
+ # config/providers/db.rb
20
+ Hanami.app.configure_provider :db do
21
+ config.gateway :default do |gw|
22
+ gw.connection_options after_connect: ->(conn) { conn.busy_handler_timeout = 5000 }
23
+ end
24
+ end
25
+ ```
26
+
27
+ mankai-jobs leaves your connection as it is and logs a warning at boot until it has an `after_connect`. The extra polling connections it opens itself (`silence_polling`) are set up this way already.
28
+
29
+ ## Install
30
+
31
+ ```ruby
32
+ # config/providers/queue.rb
33
+ require "mankai/jobs"
34
+ require "mankai/jobs/sql"
35
+
36
+ Hanami.app.register_provider(:queue, namespace: true, from: :mankai_jobs, source: :jobs) do
37
+ configure do |config|
38
+ config.backend =
39
+ if Hanami.env?(:test)
40
+ :memory
41
+ else
42
+ Mankai::Jobs::SQL.backend(
43
+ workers: [
44
+ {queues: ["realtime", "default"], threads: 5, processes: 2},
45
+ {queues: ["low*"], threads: 1, polling_interval: 1}
46
+ ]
47
+ )
48
+ end
49
+ end
50
+ end
51
+ ```
52
+
53
+ Then install the tables and start the processes:
54
+
55
+ ```bash
56
+ bundle exec hanami jobs install
57
+ ```
58
+
59
+ ```bash
60
+ bundle exec hanami db migrate
61
+ ```
62
+
63
+ ```bash
64
+ bundle exec hanami jobs start
65
+ ```
66
+
67
+ - `install` writes the migrations the app doesn't have yet, into `config/db/migrate/`:
68
+ - `<timestamp>_create_mankai_jobs_tables.rb`
69
+ - `<timestamp>_add_mankai_jobs_controls.rb`, which adds unique keys, recorded output, per-job retention, and an index for per-queue cleanup
70
+
71
+ It recognises them by these names, so keep the names if you edit the files. With a custom `table_prefix:`, pass the same prefix: `hanami jobs install --table-prefix=queue_`.
72
+ - `start` runs the supervisor, workers, dispatcher and, if there are recurring tasks, a scheduler. **Jobs run only while it's running**, so run it next to your web server in every environment that uses this backend. With `bin/dev`, add it to `Procfile.dev`:
73
+
74
+ ```text
75
+ web: bundle exec hanami server
76
+ worker: bundle exec hanami jobs start
77
+ ```
78
+
79
+ In production, run it as its own process (a `worker:` line in a `Procfile`, a systemd unit, or a container), from the same release and environment as the web process.
80
+
81
+ **After upgrading the gem, run `hanami jobs install` again.** It adds only the new migrations, and does nothing when there are none. Until the second migration has run, jobs that don't use the new features keep working.
82
+
83
+ **The migrations are idempotent.** They create only tables, columns and indexes that don't exist yet, and their rollbacks only drop what does exist. So running them twice, or having two copies of a file, does no harm; `install` points out duplicate copies. Rolling back any copy of the create migration drops the tables.
84
+
85
+ The migrations are yours to edit. Put your own schema changes in regular migrations.
86
+
87
+ In development on Hanami 3.1+, an error page caused by missing jobs tables explains the problem and offers to install and run the migration.
88
+
89
+ ## Options
90
+
91
+ | Option | Default | |
92
+ |---|---|---|
93
+ | `gateway` | `"db.gateway"` | a container key (use `"db.gateways.jobs"` for a separate database), a ROM gateway, or a `Sequel::Database` |
94
+ | `table_prefix` | `"jobs_"` | prefix for the tables; install the migrations with the same `--table-prefix` |
95
+ | `preserve_finished` | `true` | keep finished jobs (clear them with `hanami jobs clear` or `backend.clear_finished`) |
96
+ | `in_transaction` | `:join` | what happens when you enqueue inside an open transaction on the same database (see below) |
97
+ | `workers` | `[{queues: ["*"], threads: 3, processes: 1, polling_interval: 0.1}]` | one entry per kind of worker: the queues it serves, in order (exact names, `prefix*` or `*`), its threads, how many processes run it, and seconds between polls when idle |
98
+ | `dispatchers` | `[{polling_interval: 1, batch_size: 500, concurrency_maintenance_interval: 600}]` | seconds between polls, how many due jobs to move per poll, and seconds between concurrency maintenance passes |
99
+ | `scheduler` | `true` | run a scheduler when there are recurring tasks |
100
+ | `dynamic_recurring_tasks` | `false` | also run tasks added at runtime (see [Admin](#admin)) |
101
+ | `recurring_reload_interval` | `5` | seconds between checks for changed runtime tasks |
102
+ | `heartbeat_interval` | `60` | seconds |
103
+ | `alive_threshold` | `300` | seconds without a heartbeat before a process is pruned |
104
+ | `shutdown_timeout` | `5` | seconds running jobs get to finish on TERM |
105
+ | `fork_boot_timeout` | `300` | seconds a forked process may take to register before it's killed and replaced |
106
+ | `silence_polling` | `true` | processes poll through a second connection pool of the same size, without the app's SQL logging. A process can then hold up to twice the pool's connections; set it to `false` if the database's connection limit is tight |
107
+ | `retention` | `{}` | seconds to keep finished jobs, per queue (see below) |
108
+ | `retention_interval` | `600` | seconds between dispatchers' retention passes |
109
+ | `hooks` | `{}` | lifecycle hooks (see below) |
110
+
111
+ ### Retention per queue
112
+
113
+ Dispatchers delete finished jobs once they're older than their queue's retention:
114
+
115
+ ```ruby
116
+ Mankai::Jobs::SQL.backend(
117
+ retention: {
118
+ "mailers" => 3600, # an hour
119
+ "audit" => nil, # forever
120
+ "*" => 7 * 86_400 # every other queue: a week
121
+ }
122
+ )
123
+ ```
124
+
125
+ - **Unlisted queues:** without `"*"`, they're kept forever.
126
+ - **Failed jobs:** they're never deleted by retention.
127
+ - **One job at a time:** a job's `config.preserve_finished = false` deletes it as soon as it finishes.
128
+ - **Doing it by hand:** use `hanami jobs clear --older-than=SECONDS --queue=NAME`, or `backend.clear_finished(older_than:, queue:)`.
129
+
130
+ ### Hooks
131
+
132
+ Each hook is a callable (or an array of them) called with the process, inside that process:
133
+
134
+ ```ruby
135
+ Mankai::Jobs::SQL.backend(
136
+ hooks: {
137
+ worker_start: ->(process) { Metrics.reconnect },
138
+ worker_stop: ->(process) { Metrics.flush }
139
+ }
140
+ )
141
+ ```
142
+
143
+ The hooks are `supervisor_start`, `supervisor_stop`, `worker_start`, `worker_stop`, `dispatcher_start`, `dispatcher_stop`, `scheduler_start` and `scheduler_stop`. An error in a hook is logged, and the process carries on.
144
+
145
+ ## How it works
146
+
147
+ Each job has a row in `jobs_records`. Its state is the execution table it currently sits in:
148
+
149
+ ```
150
+ enqueue ─► scheduled ─(due)─► ready ─(claim)─► claimed ─► finished_at set
151
+ ▲ ▲ │
152
+ │ │ ├─(retry)──► scheduled
153
+ │ blocked ◄─(no slot) └─(failed)─► failed
154
+ ```
155
+
156
+ Moving a job is a delete plus an insert in one transaction. That keeps `jobs_ready`, the table workers poll, small and index-only. The envelope's `metadata` (retry counts per rule, step progress, locale) is stored with the record.
157
+
158
+ - **Workers** claim up to their free thread count with `SELECT … FOR UPDATE SKIP LOCKED`. Queues are polled in the order listed, then by priority (lower first). Use exact names, `prefix*` or `*`. A worker on `*` alone takes the lowest priority across all queues.
159
+ - **Dispatchers** move due scheduled jobs (including retries) to ready. They also run concurrency maintenance, which expires semaphores and unblocks waiting jobs.
160
+ - **Schedulers** enqueue recurring tasks. A unique `(task_key, run_at)` row makes sure each run is enqueued once, even with several schedulers.
161
+ - **The supervisor** forks or threads the processes and replaces any that exit. When a process dies, the supervisor fails the jobs it left behind.
162
+ - Signals: TERM and INT stop gracefully; QUIT stops immediately.
163
+ - Children watch the supervisor's pid, and stop if it goes away.
164
+
165
+ ## Unique jobs, output and transactional jobs
166
+
167
+ These are job settings; see [Job settings](https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-jobs/README.md#job-settings). How this backend handles them:
168
+
169
+ - **Unique jobs:** each key is held by a unique index on `jobs_records.unique_key`.
170
+ - A duplicate fails its insert inside a savepoint, so it never aborts the caller's transaction.
171
+ - The key is cleared when the job succeeds (unless it has a `period`), fails, or is discarded.
172
+ - Retrying a failed job by hand doesn't restore its key.
173
+ - **Recorded output:** stored as JSON in `jobs_records.output`, and read with `backend.job(id)[:output]`.
174
+ - Output over about 60 KB is dropped, with a `mankai.jobs.sql.output_dropped` event.
175
+ - A job deleted when it finishes (`preserve_finished = false`, or retention) takes its output with it.
176
+ - **Transactional jobs:** a worker runs the job inside a transaction on the app's own connection (the one the job's repositories use), and marks it finished in that same transaction.
177
+ - **If it succeeds,** its writes and its completion commit together, so a crash can no longer leave the work done but the job unfinished.
178
+ - **If it fails, or its claim was taken away,** its writes roll back, and the failure is recorded afterwards.
179
+ - Jobs it enqueues join that transaction (with the default `in_transaction: :join`).
180
+ - The transaction stays open for the whole run, so keep these jobs short. On SQLite, a run holds the database's write lock.
181
+
182
+ ## Delivery guarantees and gotchas
183
+
184
+ - **Delivery is at least once, so make jobs idempotent.** What happens to an in-flight job depends on how its process stopped:
185
+ - **Stopped on purpose** (TERM/INT past `shutdown_timeout`, or QUIT): the job goes back to ready and runs again. A resumable job pauses at its next checkpoint instead, without using up an attempt.
186
+ - **A worker crashes or gets `kill -9`:** recorded as failed with `ProcessExitError`.
187
+ - **The supervisor is killed:** its children finish their running jobs, deregister and exit.
188
+ - **Lost host:** recorded as failed with `ProcessPrunedError` once heartbeats stop.
189
+
190
+ The job's own code never sees these errors, and the job's `retry_on` rules and `max_attempts` don't apply to them: the job goes straight to failed. No `mankai.jobs.fail` event is published and the `error_reporter` isn't called; subscribe to `mankai.jobs.sql.fail_claims` to hear about them. Recover them with `backend.retry_failed(id)` (see [Admin](#admin)).
191
+ - **A stuck job on a live process is never recovered.** Heartbeats are per process, so add timeouts inside such jobs.
192
+ - **Enqueuing inside your own transaction** on the same database **joins** it by default: a rollback drops the job, and the job is invisible until commit. This silently changes if you move jobs to another database. Choose explicitly:
193
+ - `in_transaction: :after_commit`: write after commit; the job is lost if the process dies in between.
194
+ - `in_transaction: :raise`: forbid enqueuing inside a transaction, to find any code that relies on either behaviour.
195
+ - **Concurrency `duration` is a safety net, not a timeout.** If a job runs longer, another job with the same key may start. Limits guarantee no overlap, but not order. Limited jobs are also enqueued one at a time, so bulk enqueue loses its batching for them.
196
+ - **Queue order beats priority.** Use one or the other.
197
+ - **`prefix*` costs an extra `DISTINCT` query per poll**, and so does `*` once any queue is paused. Exact queue names and `*` with no paused queues are cheapest.
198
+ - **Pool size:** each worker process needs `threads + 2` connections. Set `max_connections` on the database URL; a warning is logged if the pool is too small. With `silence_polling` (the default), polling uses a second pool of the same size, so count up to twice that against the database's connection limit.
199
+ - **MySQL and MariaDB:**
200
+ - Transactions use `READ COMMITTED`, to avoid most gap-lock deadlocks between enqueue and claim.
201
+ - Concurrency slots are created with an atomic "insert if absent", and unique jobs are inserted in key order.
202
+ - Any remaining deadlock is retried, up to 5 times, because the database rolled the whole transaction back. This doesn't happen inside your own open transaction (with `in_transaction: :join`): only you can retry that, and the enqueue returns `Failure[:backend_error, error]`.
203
+ - **Error details:** they are truncated to about 60 KB.
204
+ - **Times** are stored in UTC and compared with the app clock, so keep hosts' clocks in sync.
205
+ - **Booting:** `hanami jobs start` boots the app before forking, so children share its memory. Use `--prepare` for faster starts.
206
+
207
+ ## Admin
208
+
209
+ ```ruby
210
+ backend = Hanami.app["queue.backend"]
211
+
212
+ backend.counts # => {ready:, scheduled:, claimed:, blocked:, failed:, finished:}
213
+ backend.queues # => [{name:, size:, latency:, paused:}, ...]
214
+ backend.pause("mailers"); backend.resume("mailers")
215
+ backend.clear_queue("low") # delete a queue's ready jobs
216
+
217
+ backend.job(id) # => {id:, job:, queue:, state:, attempts:, args:, output:, error:, ...}
218
+ backend.failed_jobs(limit: 20) # => [{id: 42, uuid: "8f1c…", job:, queue:, attempts:, error: {...}, ...}, ...]
219
+ backend.retry_failed(id1, id2) # => how many were retried
220
+ backend.discard_failed(id1) # => how many were deleted
221
+ backend.clear_finished(older_than: Time.now.utc - 86_400)
222
+ backend.clear_finished(older_than: Time.now.utc - 3600, queue: "mailers")
223
+ backend.apply_retention # what dispatchers do every retention_interval
224
+
225
+ # Recurring tasks added without a deploy (needs dynamic_recurring_tasks: true)
226
+ backend.schedule_recurring("nightly_report", job: "jobs.report", schedule: "every day at 2am", args: {kind: "nightly"})
227
+ backend.unschedule_recurring("nightly_report")
228
+ ```
229
+
230
+ **Job ids.** `id` is the job's id: the `envelope.id` that enqueuing returns, the `:id` of `backend.job(id)`, and the `:uuid` of each `failed_jobs` row. (A `failed_jobs` row's `:id` is the database row id; `retry_failed` and `discard_failed` accept it too.) For example, to retry every failed import:
231
+
232
+ ```ruby
233
+ ids = backend.failed_jobs(limit: 1000).select { |job| job[:job] == "jobs.import" }.map { |job| job[:uuid] }
234
+ backend.retry_failed(ids)
235
+ ```
236
+
237
+ - **Retrying** puts a failed job back on its queue as if newly enqueued. It keeps its attempt count, so a job that used up `max_attempts` fails again after one more error. A unique job's key isn't restored.
238
+ - **Discarding** deletes the job.
239
+ - Ids that don't name a failed job are skipped.
240
+
241
+ Runtime tasks are validated like configured ones. If a runtime task has the same key as a configured one, the configured task wins.
242
+
243
+ ## Events
244
+
245
+ These events are published on the app's notifications bus, alongside the [core events](https://github.com/thisisibrahimd/mankai/blob/main/gems/mankai-jobs/README.md#events). They're registered when the `queue` provider starts, so subscribe as the core events section shows, in the provider's `after(:start)`:
246
+
247
+ | Event | When | Payload |
248
+ |---|---|---|
249
+ | `mankai.jobs.sql.claim` | a worker claims jobs | `process_id:, size:` |
250
+ | `mankai.jobs.sql.release_claims` | jobs go back to ready | `process_id:, size:` |
251
+ | `mankai.jobs.sql.fail_claims` | a dead process's jobs are failed | `size:, error:` (the error class name) |
252
+ | `mankai.jobs.sql.dispatch_scheduled` | due jobs move to ready | `size:` |
253
+ | `mankai.jobs.sql.prune_processes` | processes without heartbeats are pruned | `size:` |
254
+ | `mankai.jobs.sql.enqueue_recurring` | a scheduler enqueues a recurring run | `task:, run_at:, enqueued:` (`false` if another scheduler already had) |
255
+ | `mankai.jobs.sql.apply_retention` | finished jobs past their retention are deleted | `size:` |
256
+ | `mankai.jobs.sql.output_dropped` | a job's output was too large to store | `job:, id:, bytes:` |
257
+
258
+ ## Tests
259
+
260
+ ```bash
261
+ bundle exec rspec
262
+ ```
263
+
264
+ ```bash
265
+ DATABASE_URL=postgres:///mankai_jobs_test bundle exec rspec
266
+ ```
267
+
268
+ The first command runs the specs on SQLite. For MySQL or MariaDB, use a `trilogy://root@127.0.0.1:3306/mankai_jobs_test` URL (the specs add `fractional_seconds=true`).
@@ -0,0 +1,245 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module Mankai
7
+ module Jobs
8
+ module SQL
9
+ # Inspecting and managing jobs and queues: pausing queues, retrying or discarding failed
10
+ # jobs, deleting finished ones, and counts. Backs the admin methods of SQL::Backend.
11
+ #
12
+ # @api private
13
+ # @since 0.1.0
14
+ class Admin
15
+ # Job states that have their own table.
16
+ #
17
+ # @api private
18
+ # @since 0.1.0
19
+ EXECUTION_TABLES = %i[ready scheduled claimed blocked failed].freeze
20
+
21
+ # @param store [Store] dispatches retried jobs and releases concurrency slots
22
+ #
23
+ # @api private
24
+ # @since 0.1.0
25
+ def initialize(database:, store:)
26
+ @database = database
27
+ @store = store
28
+ end
29
+
30
+ # @api private
31
+ # @since 0.1.0
32
+ def pause(queue)
33
+ table(:pauses).insert(queue: queue.to_s, created_at: @database.now)
34
+ rescue Sequel::UniqueConstraintViolation
35
+ nil
36
+ end
37
+
38
+ # @api private
39
+ # @since 0.1.0
40
+ def resume(queue)
41
+ table(:pauses).where(queue: queue.to_s).delete
42
+ end
43
+
44
+ # @return [Array<Hash>] failed jobs with their error, newest first
45
+ #
46
+ # @api private
47
+ # @since 0.1.0
48
+ def failed_jobs(limit: 100)
49
+ records = @database.tables[:records]
50
+ failed = @database.tables[:failed]
51
+ table(:failed).join(records, id: :job_id)
52
+ .select_all(records).select_append(Sequel[failed][:error])
53
+ .reverse(Sequel[failed][:id]).limit(limit).all
54
+ .map { |row| row.merge(error: JSON.parse(row[:error])) }
55
+ end
56
+
57
+ # Dispatches failed jobs again (as if newly enqueued, keeping their attempt count).
58
+ #
59
+ # @param job_ids [Array<String, Integer>] job ids (the UUIDs `job(id)` takes and
60
+ # `failed_jobs` returns as :uuid), or record ids (Integers, :id in `failed_jobs`)
61
+ # @return [Integer] how many jobs were retried
62
+ #
63
+ # @api private
64
+ # @since 0.1.0
65
+ def retry_failed(job_ids)
66
+ @database.transaction do
67
+ ids = failed_record_ids(job_ids)
68
+ table(:failed).where(job_id: ids).delete
69
+ table(:records).where(id: ids).update(scheduled_at: nil, semaphore_id: nil, updated_at: @database.now)
70
+ @store.dispatch(table(:records).where(id: ids).all.map { |row| Record.new(row) })
71
+ ids.size
72
+ end
73
+ end
74
+
75
+ # Deletes failed jobs.
76
+ #
77
+ # @param job_ids [Array<String, Integer>] as for #retry_failed
78
+ # @return [Integer] how many jobs were deleted
79
+ #
80
+ # @api private
81
+ # @since 0.1.0
82
+ def discard_failed(job_ids)
83
+ table(:records).where(id: failed_record_ids(job_ids)).delete
84
+ end
85
+
86
+ # Deletes finished jobs (and recurring run markers for deleted jobs) in batches.
87
+ #
88
+ # @param queue [String, nil] only this queue
89
+ # @param excluding_queues [Array<String>] skip these queues
90
+ # @return [Integer] how many job records were deleted
91
+ #
92
+ # @api private
93
+ # @since 0.1.0
94
+ def clear_finished(older_than:, queue: nil, excluding_queues: [], batch_size: 500)
95
+ scope = table(:records).where(Sequel[:finished_at] < older_than)
96
+ scope = scope.where(queue: queue.to_s) if queue
97
+ scope = scope.exclude(queue: excluding_queues.map(&:to_s)) if excluding_queues.any?
98
+
99
+ total = 0
100
+ loop do
101
+ ids = scope.limit(batch_size).select_map(:id)
102
+ break if ids.empty?
103
+
104
+ total += table(:records).where(id: ids).delete
105
+ end
106
+ table(:recurring_runs).exclude(job_id: table(:records).select(:id)).delete
107
+ total
108
+ end
109
+
110
+ # Deletes finished jobs older than each queue's retention.
111
+ #
112
+ # @param retention [Hash{String => Integer, nil}] seconds to keep finished jobs, per queue
113
+ # name; "*" covers every queue not listed; nil keeps a queue's jobs forever
114
+ # @return [Integer] how many job records were deleted
115
+ #
116
+ # @api private
117
+ # @since 0.1.0
118
+ def apply_retention(retention, batch_size: 500)
119
+ current = @database.now
120
+ named = retention.keys.map(&:to_s) - ["*"]
121
+ total = retention.sum do |queue, seconds|
122
+ next 0 if seconds.nil? || queue.to_s == "*"
123
+
124
+ clear_finished(older_than: current - seconds, queue: queue, batch_size: batch_size)
125
+ end
126
+ if (everything = retention["*"])
127
+ total += clear_finished(older_than: current - everything, excluding_queues: named, batch_size: batch_size)
128
+ end
129
+ @database.event(:apply_retention, size: total) if total.positive?
130
+ total
131
+ end
132
+
133
+ # One job, by id, whatever its state.
134
+ #
135
+ # @return [Hash, nil] {id:, job:, queue:, priority:, state:, attempts:, args:, metadata:,
136
+ # enqueued_at:, scheduled_at:, finished_at:, output:, error:}; state is one of :ready,
137
+ # :scheduled, :claimed, :blocked, :failed, :succeeded, :discarded
138
+ #
139
+ # @api private
140
+ # @since 0.1.0
141
+ def job(id) # rubocop:disable Metrics/AbcSize
142
+ row = table(:records).where(uuid: id.to_s).first
143
+ return unless row
144
+
145
+ record = Record.new(row)
146
+ failed = table(:failed).where(job_id: record.id).first
147
+ {
148
+ id: record.uuid, job: record.job, queue: record.queue, priority: record.priority,
149
+ state: state_of(record, failed), attempts: record.attempts,
150
+ args: JSON.parse(record.args), metadata: JSON.parse(record.metadata || "{}"),
151
+ enqueued_at: record.enqueued_at, scheduled_at: record.scheduled_at, finished_at: record.finished_at,
152
+ output: record.output && JSON.parse(record.output),
153
+ error: failed && JSON.parse(failed[:error])
154
+ }
155
+ end
156
+
157
+ # Queues with ready jobs, or paused.
158
+ #
159
+ # @return [Array<Hash>] {name:, size:, latency:, paused:}; latency is how long (seconds)
160
+ # the oldest ready job has waited
161
+ #
162
+ # @api private
163
+ # @since 0.1.0
164
+ def queues
165
+ current = @database.now
166
+ paused = @store.paused_queues
167
+ rows = table(:ready).group_and_count(:queue).select_append { min(:created_at).as(:oldest) }.all
168
+ found = rows.map do |row|
169
+ {name: row[:queue], size: row[:count], latency: latency(row[:oldest], current),
170
+ paused: paused.include?(row[:queue])}
171
+ end
172
+ idle = paused - found.map { |queue| queue[:name] }
173
+ found.concat(idle.map { |queue| {name: queue, size: 0, latency: 0, paused: true} })
174
+ found.sort_by { |queue| queue[:name] }
175
+ end
176
+
177
+ # Deletes the ready jobs of a queue, releasing their concurrency slots.
178
+ #
179
+ # @return [Integer] how many jobs were deleted
180
+ #
181
+ # @api private
182
+ # @since 0.1.0
183
+ def clear_queue(queue, batch_size: 500)
184
+ total = 0
185
+ loop do
186
+ ready_ids = table(:ready).where(queue: queue.to_s).limit(batch_size).select(:job_id)
187
+ records = table(:records).where(id: ready_ids).all.map { |row| Record.new(row) }
188
+ break if records.empty?
189
+
190
+ total += table(:records).where(id: records.map(&:id)).delete
191
+ records.each { |record| @store.release_concurrency(record) }
192
+ end
193
+ total
194
+ end
195
+
196
+ # @return [Hash{Symbol => Integer}] how many jobs are in each state
197
+ #
198
+ # @api private
199
+ # @since 0.1.0
200
+ def counts
201
+ EXECUTION_TABLES.to_h { |name| [name, table(name).count] }
202
+ .merge(finished: table(:records).exclude(finished_at: nil).count)
203
+ end
204
+
205
+ private
206
+
207
+ # Record ids of the failed jobs among `job_ids`: UUIDs (Strings) or record ids (Integers).
208
+ #
209
+ # @api private
210
+ # @since 0.1.0
211
+ def failed_record_ids(job_ids)
212
+ uuids, record_ids = Array(job_ids).partition { |id| id.is_a?(String) }
213
+ record_ids += table(:records).where(uuid: uuids).select_map(:id) if uuids.any?
214
+ return [] if record_ids.empty?
215
+
216
+ table(:failed).where(job_id: record_ids).select_map(:job_id)
217
+ end
218
+
219
+ # @api private
220
+ # @since 0.1.0
221
+ def state_of(record, failed)
222
+ return record.outcome.to_sym if record.finished_at
223
+ return :failed if failed
224
+
225
+ %i[claimed ready scheduled blocked].find { |state| table(state).where(job_id: record.id).any? } || :unknown
226
+ end
227
+
228
+ # Seconds since `oldest` (which SQLite returns as a zone-less UTC String).
229
+ #
230
+ # @api private
231
+ # @since 0.1.0
232
+ def latency(oldest, now)
233
+ oldest = Time.parse("#{oldest} UTC") if oldest.is_a?(String)
234
+ oldest ? (now - oldest).clamp(0, nil) : 0
235
+ end
236
+
237
+ # @api private
238
+ # @since 0.1.0
239
+ def table(name)
240
+ @database.table(name)
241
+ end
242
+ end
243
+ end
244
+ end
245
+ end