pgbus 0.27.2 → 1.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 +4 -4
- data/CHANGELOG.md +44 -0
- data/README.md +44 -5
- data/app/models/pgbus/batch_entry.rb +27 -6
- data/app/models/pgbus/batch_execution.rb +55 -0
- data/lib/generators/pgbus/add_batch_owner_generator.rb +48 -0
- data/lib/generators/pgbus/templates/add_batch_owner.rb.erb +13 -0
- data/lib/generators/pgbus/templates/migration.rb.erb +1 -0
- data/lib/pgbus/active_job/adapter.rb +194 -16
- data/lib/pgbus/active_job/coalesce/job_mixin.rb +40 -0
- data/lib/pgbus/active_job/coalesce/middleware.rb +48 -0
- data/lib/pgbus/active_job/coalesce.rb +307 -0
- data/lib/pgbus/batch/builder.rb +1 -1
- data/lib/pgbus/batch/sweep.rb +42 -1
- data/lib/pgbus/batch.rb +148 -29
- data/lib/pgbus/configuration.rb +22 -0
- data/lib/pgbus/engine.rb +20 -0
- data/lib/pgbus/generators/migration_detector.rb +12 -0
- data/lib/pgbus/pgmq_schema/pgmq_v1.13.2.sql +2354 -0
- data/lib/pgbus/process/heartbeat.rb +27 -0
- data/lib/pgbus/version.rb +1 -1
- data/lib/pgbus/workflow/step_job.rb +14 -0
- data/lib/pgbus.rb +15 -0
- data/sig/pgbus/active_job/adapter.rbs +14 -0
- data/sig/pgbus/active_job/coalesce.rbs +54 -0
- data/sig/pgbus/configuration.rbs +4 -0
- data/sig/pgbus.rbs +3 -0
- metadata +8 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: a8a1d130e080a9c5b98771d9aa49f42b9799a815916c8fb1d50269723e4e2878
|
|
4
|
+
data.tar.gz: cf3201146bd227f7ff8a6a114ebd6d8e1e9fc349cf9e58f1ead0daa05b58c769
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 7e776479ba3bab58e293c13c7a37b37120c82b94eb3778242ea85a767e81ac13a1e210ef562237dad5652b34a75d5fbb0377ee3c4e5b7b3f5155922757898ccf
|
|
7
|
+
data.tar.gz: 470c5e5fa425ab0d040e1502268e9c7eb7cea583f1db530cef0f5af1ace4eecc9eff1da6b21601471969d4cd0737b887094910564eead713de7ce08e0ad5290a
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,49 @@
|
|
|
1
1
|
## [Unreleased]
|
|
2
2
|
|
|
3
|
+
### Added
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
### Security
|
|
10
|
+
|
|
11
|
+
## [1.1.0] - 2026-11-24
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- **`pgbus_coalesce false/true` and `config.coalesce_default`** (#689). A job class declares `pgbus_coalesce false` to be sent at its `perform_later` inside `Pgbus.coalesce` and the request middleware, so a caller that reads `successfully_enqueued?` or rescues the send sees the real outcome. `config.coalesce_default = false` holds only classes that declare `pgbus_coalesce true`, in a batch's own scope too. The setting is inherited by subclasses. `Workflow::StepJob` declares `pgbus_coalesce false` and defines its `pgbus_coalesce?` reader on itself, so an application's base-class hook cannot shadow it; a class that still defines `pgbus_coalesce?` itself keeps working, and that override wins over the macro and the config for it and its subclasses, so remove it when adopting them.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- **PGMQ: vendored schema v1.13.2 (issue #676).** `pgmq.create()` on an existing queue no longer waits for the queue's open transactions: it ran `CREATE INDEX IF NOT EXISTS` on the queue and archive tables, which takes a `SHARE` lock before it checks for the index, so a process ensuring its queues at boot waited for every open transaction that had sent to one of them, and later sends queued behind it. The index DDL now runs only when `to_regclass()` finds the index missing, and the `pg_monitor` grants only when it lacks them. The fix covers `pgmq.create()` only: other DDL a starting process runs on a queue still waits for its open writers, among it re-arming a NOTIFY trigger (one missing or out of date, and a stream queue's on every cold start) and the `group_mode` FIFO and `fair_share` indexes. Under the default configuration, a job queue whose trigger is in place no longer waits. Fresh embedded installs get 1.13.2. Existing *embedded* installs: `rake pgbus:pgmq:status`, then `rails generate pgbus:upgrade_pgmq` + `rails db:migrate` (`rails db:migrate:pgbus` on a separate-database install); the hop changes functions only, so it carries no fixup. An `:extension` install gets 1.13.2 from `ALTER EXTENSION pgmq UPDATE`. Refs #676.
|
|
20
|
+
|
|
21
|
+
## [1.0.0] - 2026-11-21
|
|
22
|
+
|
|
23
|
+
**pgbus 1.0.** This release stabilises the API that 0.x settled into, and makes enqueueing many jobs cost a constant number of round trips instead of one or more per job.
|
|
24
|
+
|
|
25
|
+
- **Coalesced enqueues.** `Pgbus.coalesce { }` holds a unit of work's jobs and sends them together: one `send_batch` per queue, priority and delay. `config.pgbus.coalesce_requests` turns on an opt-in Rack middleware that does the same for every request. At 5 ms per database round trip, 1 000 `perform_later` calls take about 75 ms instead of 6.9 s.
|
|
26
|
+
- **Building batches.** A `Pgbus.batch` opened in a pgbus process is created `building`, owned by that process's heartbeat row. While it is building, no sweep or finish can touch it. Its block's `perform_later` calls are held and counted in once per chunk (`config.coalesce_chunk_size`). If the owner process dies, the sweep reaps the build. Existing installs add `owner_process_id` with `rails generate pgbus:add_batch_owner` (or `pgbus:update`).
|
|
27
|
+
- **Bulk batch bookkeeping.** A batch's execution rows are inserted, backfilled and uncounted with one statement per group, not one per job. At 5 ms per round trip, 1 000 members through `b.add` take about 0.36 s instead of 15.5 s, and 1 000 `perform_later` calls in a built batch take about 0.36 s instead of 41.6 s.
|
|
28
|
+
- **Bulk scheduled sends.** Jobs with `set(wait:)` go out as one `send_batch` per delay, so a staggered fan-out costs one send per slice.
|
|
29
|
+
- **Breaking:** `Batch.new(on_discard:)` and `Batch#on_discard` are removed; use `on_failure:`. `on_finish` stays until 2.0. The 1.0 table in the upgrade guide lists every change.
|
|
30
|
+
|
|
31
|
+
### Breaking Changes
|
|
32
|
+
|
|
33
|
+
- **`Pgbus::Batch.new(on_discard:)` and `Batch#on_discard` are removed**, as their deprecation warning announced for 1.0 (this release). Pass `on_failure:` and read `#on_failure`. `on_discard:` now raises `ArgumentError` (unknown keyword).
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
|
|
37
|
+
- **`on_finish` stays one more major version.** The `on_finish:` keyword and the builder's `b.on_finish` are still accepted and still warn once per process (`Batch#on_finish` stays as a plain reader alias); the warning now says they are removed in 2.0. Callers in the wild still use them. The `BatchEntry#discarded_jobs` alias, for installs that have not run `pgbus:add_batch_executions`, is also kept until 2.0: the legacy-schema path still reads it. The `on_finish_class` / `on_finish_job` columns, which were to be renamed at 1.0, stay until 2.0 too.
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
|
|
41
|
+
- **Scheduled jobs go out in bulk (issue #686).** `enqueue_all` (`perform_all_later`, `b.add`), a `Pgbus.coalesce` scope and a built batch's block group bulk-eligible jobs by queue, priority and delay (whole seconds), and send each group with one `send_batch` carrying that delay; they used to send every future job on its own. A staggered fan-out (slice i scheduled i × delay ahead) costs one send per slice, and 50 jobs that share a `wait:` one send. A coalesce scope now holds future jobs (`enqueue_at`) as well, and works their delay out at the flush, from the scheduled time, so time spent in the scope is not added to it. A batch's scheduled members are counted and backfilled in bulk with the rest. Uniqueness and concurrency jobs keep the single path, their lock and slot leases covering the delay. Refs #686.
|
|
42
|
+
|
|
43
|
+
- **A batch's bookkeeping takes a constant number of statements, and `Pgbus.batch` coalesces its block (issue #683).** `Batch.track_enqueue` inserts every execution row of a bulk in one `INSERT … SELECT FROM unnest(…) ON CONFLICT (job_id) DO NOTHING` (new `BatchExecution.insert_all_for!`), still in the same transaction as the guarded increment and still before any send. The bulk send backfills each group's `msg_id`s with one `UPDATE … FROM unnest(…)` (`BatchExecution.backfill_all!`); a backfill that fails is logged and never fails an enqueue whose messages are live. A failed bulk send uncounts its group with one `DELETE … WHERE job_id = ANY($1)` and one decrement by the count (`Batch.untrack_enqueue_all`). **A batch opened in a pgbus process is built:** with the new `owner_process_id` column (`rails generate pgbus:add_batch_owner`; fresh installs have it) and a process heartbeat row (a worker, consumer, dispatcher or scheduler), `Pgbus.batch` creates the batch as `building` with that row as its owner. While `building`, the stalled-batch sweep ignores it, no finish can close it (a member sent at once that completes still counts) and no callback fires. Its block runs in a `Pgbus.coalesce` scope of the batch's own: plain `perform_later` calls are held, serialized at the call, counted in once per `config.coalesce_chunk_size` jobs (new, default 1 000; every coalesce scope uses it) and sent with that bookkeeping; the scope never joins an outer one, and an outer scope's flush never sends a batch's members. The block's end counts the last chunk and moves the batch `building` → `pending` in one transaction, then sends it; the usual start re-checks finish. The sweep reaps a build only once its owner's row is gone or its heartbeat is older than `Process::Heartbeat::ALIVE_THRESHOLD`: the batch moves to `processing` with the abandoned build counted as one failed job, so `on_complete` and `on_failure` fire and `on_success` cannot. A batch opened anywhere else (a web request, a console, a rake task; or before the migration) is `pending` and sends its members one at a time, as before. A closing transaction that fails is followed by a bare guarded close, so the batch is `pending`; only a database unreachable through both leaves it `building` until its owner exits. New `Pgbus.batch(on_enqueue_failure:)` (`:raise` default, `:report`, or a callable); `on_failure:` remains the failed-member callback. Batch of N bulk-eligible jobs: about 2N + 4 round trips (`b.add`) or 6N (`perform_later`) before, after a constant number per `coalesce_chunk_size` chunk and per (queue, priority) group, whatever N is within them. **Changed for existing callers:** inside a built batch's block, `perform_later` now returns the job with `provider_job_id` nil until its chunk is sent (at the next chunk or the block's end), a held member that is never sent counts as a failed job of the batch (`on_failure` fires, `on_success` cannot), `AlreadyFinished` surfaces at the block's end, and a member that cannot be sent raises `Pgbus::EnqueueError` when the block ends (or goes to `on_enqueue_failure:`), not at the call; during a rolling deploy a pre-0.28 process rejects an open-batch `batch.add` into a `building` batch with `AlreadyFinished`, and a pre-0.28 dispatcher's orphan-row sweep can remove a `building` batch's unsent row without its count, leaving that batch unfinished; **downgrading** below this release leaves any `building` batch to nobody: move them on first with `UPDATE pgbus_batches SET status = 'pending' WHERE status = 'building'`; a bulk backfill that fails no longer raises out of `enqueue_all`. An empty `Pgbus.coalesce` scope emits no `pgbus.coalesce` event. Refs #683.
|
|
44
|
+
|
|
45
|
+
- **`Pgbus.coalesce { }` and an opt-in Rack middleware send a unit of work's enqueues together: one `send_batch` per (queue, priority) group instead of one send per `perform_later` (issue #682).** Inside the scope the adapter serializes every bulk-eligible job at `perform_later`, holds it, and returns it with `successfully_enqueued?` true and `provider_job_id` nil, as Rails does for a job deferred to after commit. At the end of the block the held payloads go out in bulk; each job left unsent is retried on its own, and what still fails goes to `on_failure:` (`:raise`, the default, raises `Pgbus::EnqueueError` naming each job; `:report` reports it with the serialized jobs; a callable receives `(jobs, error)`). The buffer is also sent when the block raises, and the block's error propagates. Jobs with uniqueness or concurrency, `retry_on` re-enqueues, deploy task runs, batch members, workflow steps, and jobs enqueued on another thread or fiber or after the flush has started go out at once. A nested scope joins the outer one. `Pgbus::ActiveJob::Coalesce::Middleware` sends before it returns the response, never in `rack.response_finished`; `config.pgbus.coalesce_requests = true` (default false) inserts it after `ActionDispatch::Executor`, with `config.pgbus.coalesce_requests_on_failure` (default `:raise`). New `pgbus.coalesce` notification with `buffered`, `sent`, `retried`, `failed` and `duration`. Refs #682.
|
|
46
|
+
|
|
3
47
|
## [0.27.2] - 2026-11-21
|
|
4
48
|
|
|
5
49
|
### Fixed
|
data/README.md
CHANGED
|
@@ -820,6 +820,45 @@ Uses PostgreSQL session-level advisory locks (`pg_try_advisory_lock`). The lock
|
|
|
820
820
|
|
|
821
821
|
How Pgbus integrates with your application's transactions and tracks groups of related work: outbox for atomic publish, batches for fan-out coordination, archive compaction for keeping the queue tables small.
|
|
822
822
|
|
|
823
|
+
### Coalescing enqueues
|
|
824
|
+
|
|
825
|
+
Every `perform_later` is one send, so one database round trip. A unit of work that enqueues several jobs (a request that records a few events, a job that fans out follow-ups) can send them together instead:
|
|
826
|
+
|
|
827
|
+
```ruby
|
|
828
|
+
Pgbus.coalesce do
|
|
829
|
+
EventJob.perform_later("a")
|
|
830
|
+
EventJob.perform_later("b")
|
|
831
|
+
EventJob.perform_later("c")
|
|
832
|
+
end # one send_batch here, per (queue, priority, delay)
|
|
833
|
+
```
|
|
834
|
+
|
|
835
|
+
Or for every request, through an opt-in Rack middleware that runs the request inside the scope and sends before it returns the response, never after it (a crash once the client has its answer cannot lose a job):
|
|
836
|
+
|
|
837
|
+
```ruby
|
|
838
|
+
# config/application.rb
|
|
839
|
+
config.pgbus.coalesce_requests = true # inserted after ActionDispatch::Executor (application.rb or an initializer)
|
|
840
|
+
config.pgbus.coalesce_requests_on_failure = :raise # the default; :report or a callable
|
|
841
|
+
|
|
842
|
+
# or by hand
|
|
843
|
+
config.middleware.insert_after ActionDispatch::Executor, Pgbus::ActiveJob::Coalesce::Middleware, on_failure: :report
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
- **What is held.** A job that the bulk path can send, serialized at `perform_later` (an argument that cannot be serialized raises there, as outside a scope, and a later change to the job or its arguments is not sent). These go out at once, as they do outside a scope: jobs with `ensures_uniqueness` or `limits_concurrency` (the single enqueue path takes or checks their lock or slot), `retry_on` re-enqueues, deploy task runs, batch members (outside their own batch's block), workflow steps, jobs enqueued on another thread or fiber, and jobs enqueued after the flush has started (for example while a streaming body is iterated). On Rails 7.2+ a job that Rails defers to after commit (`enqueue_after_transaction_commit`) reaches the scope at commit, and a rolled-back one never does; a job that does not defer is held like any other; Rails 7.1 has no deferral, so there a job enqueued inside a transaction is held, and sent, whatever the transaction does, as it is sent without a scope.
|
|
847
|
+
- **Future jobs.** A bulk-eligible `set(wait:)` / `set(wait_until:)` job is held too and sent at the flush with the delay left then (never the time it waited in the scope), one `send_batch` per (queue, priority, delay), so a staggered fan-out costs one send per slice (per chunk, past `config.coalesce_chunk_size`). `perform_all_later` and `b.add` group future jobs the same way. A scheduled job with uniqueness or a concurrency limit still takes the single path, so its lock and slot lease cover the wait.
|
|
848
|
+
- **What `perform_later` returns.** The job, with `successfully_enqueued?` true and `provider_job_id` nil until the flush, the same optimistic answer Rails gives a job deferred to after commit. The flush is where delivery is proved.
|
|
849
|
+
- **The flush.** At the end of the block, before its value returns: one `send_batch` per (queue, priority, delay), then each job left unsent is retried on its own. A send whose outcome is unknown (a connection lost mid-statement) may have written its messages, so the retry can deliver a job twice; jobs must be idempotent, as they already must be for at-least-once delivery. What still fails goes to `on_failure`: `:raise` (default) raises `Pgbus::EnqueueError` naming each job's class and id, `:report` sends it to `Rails.error.report` with the serialized jobs (`Pgbus::ErrorReporter`, and so `config.error_reporters`, only without Rails), and a callable receives `(jobs, error)`. If the block itself raised, the buffer is still sent, a callable still gets the failed jobs, nothing in the flush raises (`:raise` becomes a report), and the block's error propagates.
|
|
850
|
+
- **Nesting and batches.** A nested `Pgbus.coalesce` joins the outer scope, whose `on_failure` applies; only the outermost sends. A `Pgbus.batch` built in a pgbus process opens a scope of its own (see Batches): it holds only that batch's members and sends them by the batch block's end, never in an outer scope's flush. Any other batch member (a batch opened outside a pgbus process, an open-batch `batch.add`, a deferred member reaching the adapter at commit) is sent at once and counted in as usual.
|
|
851
|
+
- **Jobs whose caller reads the enqueue outcome.** A caller that checks `successfully_enqueued?` or rescues around `perform_later` to undo its own state needs the job sent at the call. Declare `pgbus_coalesce false` on its class: it is sent at its `perform_later` inside any scope, with its `provider_job_id`, and a send error raises there. This bypasses pgbus's scope only: a job Rails defers to after commit (`enqueue_after_transaction_commit`, Rails 7.2+) still reaches the adapter at commit, so inside a transaction its caller sees Rails' deferred answer, not the send. Subclasses inherit the setting, and `pgbus_coalesce true` turns it back on. When most jobs are like that, set `Pgbus.configure { |c| c.coalesce_default = false }` (default `true`; it is a `Pgbus.configuration` setting, not a `config.pgbus` one): only classes that declare `pgbus_coalesce true` are held, in a `Pgbus.batch` block's own scope too, so declare it on each member class whose jobs should go out in one bulk send. A class that defines `pgbus_coalesce?` itself (the hook before this setting) answers for itself whatever `coalesce_default` says. Already sent at once whatever the setting: the jobs listed under "What is held".
|
|
852
|
+
|
|
853
|
+
```ruby
|
|
854
|
+
class ProcessItemJob < ApplicationJob
|
|
855
|
+
pgbus_coalesce false
|
|
856
|
+
end
|
|
857
|
+
```
|
|
858
|
+
- **When not to use it.** With `:raise`, a job that cannot be sent fails the request after its transaction has committed, and from right after `ActionDispatch::Executor` the error surfaces above `ActionDispatch::ShowExceptions`, so the client gets the server's bare 500. An endpoint that must not answer 500 after committing its writes should pass `on_failure: :report` or a callable that does not raise.
|
|
859
|
+
|
|
860
|
+
The scope emits `pgbus.coalesce` with `buffered`, `sent`, `retried`, `failed` and `duration` (ms).
|
|
861
|
+
|
|
823
862
|
### Batches
|
|
824
863
|
|
|
825
864
|
Coordinate groups of jobs with callbacks when all complete:
|
|
@@ -833,7 +872,7 @@ batch = Pgbus.batch(description: "Import users", properties: { initiated_by: cur
|
|
|
833
872
|
end
|
|
834
873
|
```
|
|
835
874
|
|
|
836
|
-
`b.add` takes job instances (each keeps its own `.set(wait:, queue:)`) and sends them in one bulk enqueue. The batch row exists before the block runs and stays pending until it returns,
|
|
875
|
+
`b.add` takes job instances (each keeps its own `.set(wait:, queue:)`) and sends them in one bulk enqueue. A plain `perform_later` inside the block is coalesced the same way when the batch is opened in a pgbus process (a worker, consumer, dispatcher or scheduler: one with a `pgbus_processes` heartbeat). The batch is then created as `building`, with that process as its owner. While it is `building` the stalled-batch sweep leaves it alone, it cannot finish and no callback fires, whatever its block does. The block's members are held (unless their class may not be held: `pgbus_coalesce false`, or no `pgbus_coalesce true` under `config.coalesce_default = false`; those are sent and counted one at a time), serialized at the call, counted in with one statement per `config.coalesce_chunk_size` jobs (default 1 000), sent with one `send_batch` per (queue, priority, delay) and backfilled with one more, whatever their number. When the block returns, the last chunk is counted in and the batch moves to `pending` in one transaction, before anything of that chunk is sent, so the batch can finish only once every member is counted. If the owner process dies (its heartbeat row is gone or older than five minutes), the sweep reaps the build: the batch moves to `processing` and the abandoned build counts as one failed job, so `on_complete` and `on_failure` fire once the members that were sent resolve, and `on_success` never does. A batch opened anywhere else (a web request, a console, a rake task) has no heartbeat the sweep could watch: it is created `pending` and its plain `perform_later` members are sent and counted one at a time, as before (`b.add` stays one bulk send everywhere). A held member that cannot be sent is retried on its own, counted as a failed job of the batch, then handed to `on_enqueue_failure:` (`:raise` by default, `:report`, or a callable taking `(jobs, error)`; `on_failure:` stays the callback for a member that fails). Uniqueness and concurrency members keep the single enqueue path; future members are held and sent with their delay. The batch row exists before the block runs and stays `building` or `pending` until it returns. A `building` batch cannot finish before its block returns; a `pending` one cannot either, unless the stalled-batch sweep starts it first (below). A built batch keeps a full chunk while a transaction is open on the batch's connection and counts it in once the transaction is gone (or at the block's end), so a rollback never strands a sent member without its count. If the database stays unreachable through both attempts to close a build (the closing transaction and a bare retry), the batch stays `building` until its owner process exits, when the sweep reaps it. Set callbacks first: if the block raises after an `add`, the added jobs still run and the batch finishes later with only the callbacks set by then. A `pending` batch whose block goes `config.batch_stall_threshold` (default 5 minutes) without adding a job is started by the stalled-batch sweep, so keep slow work outside it; a `building` batch is never started that way. Callbacks are job classes or configured instances, never blocks: they are stored on the batch row.
|
|
837
876
|
|
|
838
877
|
Inside a job, `batch { |b| ... }` opens a new batch the same way, and a job that is already a member adds siblings with `batch.add(NextJob.new(id))`. `Pgbus::Batch.new(on_complete: ...)` plus `batch.enqueue { ... }` remains the lower-level form.
|
|
839
878
|
|
|
@@ -841,9 +880,9 @@ Inside a job, `batch { |b| ... }` opens a new batch the same way, and a job that
|
|
|
841
880
|
|
|
842
881
|
| Callback | Fired when |
|
|
843
882
|
|----------|------------|
|
|
844
|
-
| `on_complete` | All jobs completed (success or failure). `on_finish` is a deprecated alias
|
|
883
|
+
| `on_complete` | All jobs completed (success or failure). `on_finish` is a deprecated alias, removed in 2.0 |
|
|
845
884
|
| `on_success` | All jobs completed successfully (zero failed) |
|
|
846
|
-
| `on_failure` | At least one job
|
|
885
|
+
| `on_failure` | At least one job failed (dead-lettered, or never sent) |
|
|
847
886
|
|
|
848
887
|
Callback jobs given as a bare class receive the batch `properties` hash as their argument:
|
|
849
888
|
|
|
@@ -871,8 +910,8 @@ The lock is taken at the top of the block (or at `enqueue`) and held until the b
|
|
|
871
910
|
|
|
872
911
|
#### How batches work
|
|
873
912
|
|
|
874
|
-
1. The top of the `Pgbus.batch` block (or the first `batch.enqueue`) creates a tracking row in `pgbus_batches` with `status: "pending"`
|
|
875
|
-
2. Each job enqueued in the block is tagged with the `pgbus_batch_id` in its payload
|
|
913
|
+
1. The top of the `Pgbus.batch` block (or the first `batch.enqueue`) creates a tracking row in `pgbus_batches`: `status: "building"` with its owner process when opened in a pgbus process (`rails generate pgbus:add_batch_owner` on an existing install), else `status: "pending"`; a built batch moves to `pending` when its block returns
|
|
914
|
+
2. Each job enqueued in the block is tagged with the `pgbus_batch_id` in its payload and counted in before it is sent: `total_jobs` goes up and one `pgbus_batch_executions` row per job is inserted, in one statement for a whole bulk or chunk
|
|
876
915
|
3. After each job completes or is dead-lettered, the executor atomically updates the batch counters
|
|
877
916
|
4. When `completed_jobs + discarded_jobs == total_jobs`, the batch status flips to `"finished"` and callback jobs are enqueued
|
|
878
917
|
5. The dispatcher cleans up finished batches older than 7 days
|
|
@@ -11,11 +11,20 @@ module Pgbus
|
|
|
11
11
|
|
|
12
12
|
scope :finished, -> { where(status: "finished") }
|
|
13
13
|
scope :stale, ->(before:) { finished.where("finished_at < ?", before) }
|
|
14
|
+
# building (issue #683): the batch's block is still open in the process
|
|
15
|
+
# owner_process_id names; no sweep changes its status and no finish
|
|
16
|
+
# closes it (counters still move) until the block closes the build
|
|
17
|
+
# (close_build!) or the owner stops heartbeating.
|
|
18
|
+
UNFINISHED = %w[building pending processing].freeze
|
|
19
|
+
|
|
20
|
+
scope :building, -> { where(status: "building") }
|
|
14
21
|
scope :pending, -> { where(status: "pending") }
|
|
15
22
|
scope :processing, -> { where(status: "processing") }
|
|
16
23
|
scope :without_executions, -> { where.not(batch_id: BatchExecution.select(:batch_id)) }
|
|
17
24
|
|
|
18
|
-
# Deprecated alias
|
|
25
|
+
# Deprecated alias, removed in 2.0, kept for installs that have not run
|
|
26
|
+
# pgbus:add_batch_executions: after the column is dropped this reads
|
|
27
|
+
# failed_jobs.
|
|
19
28
|
def discarded_jobs
|
|
20
29
|
has_attribute?(:discarded_jobs) ? self[:discarded_jobs] : failed_jobs
|
|
21
30
|
end
|
|
@@ -23,8 +32,10 @@ module Pgbus
|
|
|
23
32
|
# Atomically add n to total_jobs on an unfinished batch. Returns true.
|
|
24
33
|
# Raises Batch::AlreadyFinished when the row is already finished (0 rows
|
|
25
34
|
# updated) — the adder-before-insert contract open batches (#415) rely on.
|
|
26
|
-
|
|
27
|
-
|
|
35
|
+
# +statuses+: a batch scope counts a chunk into a batch still building
|
|
36
|
+
# only, never into one the sweep reaped (issue #683).
|
|
37
|
+
def self.increment_total_jobs!(batch_id, count, statuses: UNFINISHED) # rubocop:disable Naming/PredicateMethod
|
|
38
|
+
updated = where(batch_id: batch_id, status: statuses)
|
|
28
39
|
.update_all(["total_jobs = total_jobs + ?", count])
|
|
29
40
|
raise Batch::AlreadyFinished, "Can't add jobs into an already finished batch" if updated.zero?
|
|
30
41
|
|
|
@@ -33,9 +44,19 @@ module Pgbus
|
|
|
33
44
|
|
|
34
45
|
# Reverse of increment_total_jobs! for a job that will never run. Floored
|
|
35
46
|
# at zero; a finished row is left alone.
|
|
36
|
-
def self.decrement_total_jobs!(batch_id)
|
|
37
|
-
where(batch_id: batch_id, status:
|
|
38
|
-
.update_all(["total_jobs = GREATEST(total_jobs -
|
|
47
|
+
def self.decrement_total_jobs!(batch_id, count = 1)
|
|
48
|
+
where(batch_id: batch_id, status: UNFINISHED)
|
|
49
|
+
.update_all(["total_jobs = GREATEST(total_jobs - ?, 0)", count])
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# The block that builds the batch returned: building -> pending, guarded
|
|
53
|
+
# so the block and the sweep's reaping (Sweep.reap_abandoned_builds)
|
|
54
|
+
# cannot both win. Raises AlreadyFinished when the build was reaped.
|
|
55
|
+
def self.close_build!(batch_id)
|
|
56
|
+
closed = where(batch_id: batch_id, status: "building").update_all(status: "pending")
|
|
57
|
+
raise Batch::AlreadyFinished, "Can't close the build of batch #{batch_id}: the sweep reaped it" if closed.zero?
|
|
58
|
+
|
|
59
|
+
closed
|
|
39
60
|
end
|
|
40
61
|
|
|
41
62
|
# Resolve a batch member and count it, in one statement and no
|
|
@@ -23,8 +23,63 @@ module Pgbus
|
|
|
23
23
|
end
|
|
24
24
|
end
|
|
25
25
|
|
|
26
|
+
# insert_for! for many members of one batch, in one statement (issue
|
|
27
|
+
# #683): +rows+ are [job_id, queue_name] pairs, bound as two arrays so
|
|
28
|
+
# the statement keeps three parameters whatever the count.
|
|
29
|
+
def self.insert_all_for!(batch_id:, rows:)
|
|
30
|
+
return if rows.empty?
|
|
31
|
+
|
|
32
|
+
job_ids, queue_names = rows.transpose
|
|
33
|
+
connection_pool.with_connection do |conn|
|
|
34
|
+
conn.exec_query(
|
|
35
|
+
"INSERT INTO #{table_name} (batch_id, job_id, queue_name, created_at) " \
|
|
36
|
+
"SELECT $1, r.job_id, r.queue_name, $4 FROM unnest($2::varchar[], $3::varchar[]) AS r(job_id, queue_name) " \
|
|
37
|
+
"ON CONFLICT (job_id) DO NOTHING",
|
|
38
|
+
"BatchExecution Insert All",
|
|
39
|
+
[batch_id, encode_array(job_ids), encode_array(queue_names), Time.current]
|
|
40
|
+
)
|
|
41
|
+
end
|
|
42
|
+
end
|
|
43
|
+
|
|
26
44
|
def self.backfill!(job_id, msg_id:, queue_name:)
|
|
27
45
|
where(job_id: job_id).update_all(msg_id: msg_id, queue_name: queue_name)
|
|
28
46
|
end
|
|
47
|
+
|
|
48
|
+
# backfill! for a whole send group in one statement (issue #683): +rows+
|
|
49
|
+
# are [job_id, msg_id, queue_name] triples.
|
|
50
|
+
def self.backfill_all!(rows)
|
|
51
|
+
return if rows.empty?
|
|
52
|
+
|
|
53
|
+
job_ids, msg_ids, queue_names = rows.transpose
|
|
54
|
+
connection_pool.with_connection do |conn|
|
|
55
|
+
conn.exec_query(
|
|
56
|
+
"UPDATE #{table_name} AS e SET msg_id = v.msg_id, queue_name = v.queue_name " \
|
|
57
|
+
"FROM unnest($1::varchar[], $2::bigint[], $3::varchar[]) AS v(job_id, msg_id, queue_name) " \
|
|
58
|
+
"WHERE e.job_id = v.job_id",
|
|
59
|
+
"BatchExecution Backfill All",
|
|
60
|
+
[encode_array(job_ids), encode_array(msg_ids), encode_array(queue_names)]
|
|
61
|
+
)
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Deletes the rows of +job_ids+ in one statement; returns how many went.
|
|
66
|
+
def self.delete_all_for!(job_ids)
|
|
67
|
+
return 0 if job_ids.empty?
|
|
68
|
+
|
|
69
|
+
connection_pool.with_connection do |conn|
|
|
70
|
+
conn.exec_delete(
|
|
71
|
+
"DELETE FROM #{table_name} WHERE job_id = ANY($1::varchar[])",
|
|
72
|
+
"BatchExecution Delete All",
|
|
73
|
+
[encode_array(job_ids)]
|
|
74
|
+
)
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# A Postgres array literal, so an array binds as one text parameter the
|
|
79
|
+
# same way on every Rails version.
|
|
80
|
+
def self.encode_array(values)
|
|
81
|
+
PG::TextEncoder::Array.new.encode(values.map { |v| v&.to_s })
|
|
82
|
+
end
|
|
83
|
+
private_class_method :encode_array
|
|
29
84
|
end
|
|
30
85
|
end
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "rails/generators"
|
|
4
|
+
require "rails/generators/active_record"
|
|
5
|
+
require_relative "migration_path"
|
|
6
|
+
|
|
7
|
+
module Pgbus
|
|
8
|
+
module Generators
|
|
9
|
+
class AddBatchOwnerGenerator < Rails::Generators::Base
|
|
10
|
+
include ActiveRecord::Generators::Migration
|
|
11
|
+
include MigrationPath
|
|
12
|
+
|
|
13
|
+
source_root File.expand_path("templates", __dir__)
|
|
14
|
+
|
|
15
|
+
desc "Add owner_process_id to pgbus_batches, so a batch can be built by a watched process (issue #683)"
|
|
16
|
+
|
|
17
|
+
class_option :database,
|
|
18
|
+
type: :string,
|
|
19
|
+
default: nil,
|
|
20
|
+
desc: "Use a separate database for pgbus tables (e.g. --database=pgbus)"
|
|
21
|
+
|
|
22
|
+
def create_migration_file
|
|
23
|
+
migration_template "add_batch_owner.rb.erb",
|
|
24
|
+
File.join(pgbus_migrate_path, "add_pgbus_batch_owner.rb")
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def display_post_install
|
|
28
|
+
say ""
|
|
29
|
+
say "Pgbus batch owner column installed!", :green
|
|
30
|
+
say ""
|
|
31
|
+
say "Next steps:"
|
|
32
|
+
say " 1. Run: rails db:migrate#{migrate_command_suffix}"
|
|
33
|
+
say " 2. Restart pgbus: bin/pgbus start"
|
|
34
|
+
say ""
|
|
35
|
+
say "A Pgbus.batch opened in a pgbus process (a worker, consumer, dispatcher or"
|
|
36
|
+
say "scheduler) is now built: its perform_later calls are held and sent together"
|
|
37
|
+
say "when the block returns."
|
|
38
|
+
say ""
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
private
|
|
42
|
+
|
|
43
|
+
def migration_version
|
|
44
|
+
"[#{ActiveRecord::Migration.current_version}]"
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
class AddPgbusBatchOwner < ActiveRecord::Migration<%= migration_version %>
|
|
2
|
+
# The pgbus_processes row of the process that builds a batch (issue #683):
|
|
3
|
+
# the stalled-batch sweep reaps a build only once that process stops
|
|
4
|
+
# heartbeating. No index: the sweep reads it only for batches in
|
|
5
|
+
# status "building", which idx_pgbus_batches_status narrows.
|
|
6
|
+
def up
|
|
7
|
+
add_column :pgbus_batches, :owner_process_id, :bigint unless column_exists?(:pgbus_batches, :owner_process_id)
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
def down
|
|
11
|
+
remove_column :pgbus_batches, :owner_process_id if column_exists?(:pgbus_batches, :owner_process_id)
|
|
12
|
+
end
|
|
13
|
+
end
|
|
@@ -116,6 +116,7 @@ class CreatePgbusTables < ActiveRecord::Migration<%= migration_version %>
|
|
|
116
116
|
t.integer :completed_jobs, null: false, default: 0
|
|
117
117
|
t.integer :failed_jobs, null: false, default: 0
|
|
118
118
|
t.string :status, null: false, default: "pending"
|
|
119
|
+
t.bigint :owner_process_id
|
|
119
120
|
t.datetime :created_at, null: false, default: -> { "CURRENT_TIMESTAMP" }
|
|
120
121
|
t.datetime :finished_at
|
|
121
122
|
end
|
|
@@ -5,11 +5,22 @@ require "active_job"
|
|
|
5
5
|
module Pgbus
|
|
6
6
|
module ActiveJob
|
|
7
7
|
class Adapter
|
|
8
|
+
# Inside Pgbus.coalesce a bulk-eligible job is serialized now and held,
|
|
9
|
+
# then sent with the rest when the scope ends (issue #682); everything
|
|
10
|
+
# else is sent now. With no scope open this costs one fiber-local read.
|
|
8
11
|
def enqueue(active_job)
|
|
12
|
+
scope = Coalesce.current
|
|
13
|
+
return active_job if scope && coalesce(scope, active_job)
|
|
14
|
+
|
|
9
15
|
enqueue_job(active_job)
|
|
10
16
|
end
|
|
11
17
|
|
|
18
|
+
# A future job is held too inside Pgbus.coalesce (issue #686); its delay
|
|
19
|
+
# is worked out at the flush, from +timestamp+.
|
|
12
20
|
def enqueue_at(active_job, timestamp)
|
|
21
|
+
scope = Coalesce.current
|
|
22
|
+
return active_job if scope && coalesce(scope, active_job, due_at: timestamp)
|
|
23
|
+
|
|
13
24
|
enqueue_job(active_job, delay: delay_until(timestamp))
|
|
14
25
|
end
|
|
15
26
|
|
|
@@ -30,19 +41,143 @@ module Pgbus
|
|
|
30
41
|
individual.each { |j| enqueue_one_of_all(j) }
|
|
31
42
|
|
|
32
43
|
# Group by priority too: send_batch routes through the queue strategy,
|
|
33
|
-
# so a mixed-priority bulk send needs one produce_batch per level.
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
44
|
+
# so a mixed-priority bulk send needs one produce_batch per level. And
|
|
45
|
+
# by delay (issue #686): PGMQ's batch send takes one delay, so jobs
|
|
46
|
+
# scheduled for the same second go out together, a staggered fan-out
|
|
47
|
+
# as one send per slice.
|
|
48
|
+
bulk.group_by { |j| [j.queue_name || Pgbus.configuration.default_queue, j.try(:priority), job_delay(j)] }
|
|
49
|
+
.each do |(queue, priority, delay), jobs|
|
|
50
|
+
enqueue_immediate(queue, jobs, priority: priority, delay: delay)
|
|
39
51
|
end
|
|
40
52
|
|
|
41
53
|
active_jobs.count(&:successfully_enqueued?)
|
|
42
54
|
end
|
|
43
55
|
|
|
56
|
+
# Sends what a Coalesce scope held, as [job, payload, due_at] entries
|
|
57
|
+
# with the payload serialized at perform_later (issue #682): one
|
|
58
|
+
# send_batch per (queue, priority, delay) group (issue #686), through
|
|
59
|
+
# the bulk path enqueue_all uses, then
|
|
60
|
+
# each job left unsent on its own. Queue and priority are the payload's,
|
|
61
|
+
# so a job changed after perform_later goes where it was sent. Never
|
|
62
|
+
# raises: what still fails is the result's +failed+, for on_failure.
|
|
63
|
+
# +counted+: a batch scope already counted the entries into their batch
|
|
64
|
+
# (issue #683), so the send does not count them again.
|
|
65
|
+
def deliver_coalesced(entries, counted: false)
|
|
66
|
+
jobs = entries.map(&:first)
|
|
67
|
+
jobs.each do |job|
|
|
68
|
+
job.successfully_enqueued = false
|
|
69
|
+
job.enqueue_error = nil
|
|
70
|
+
end
|
|
71
|
+
error = nil
|
|
72
|
+
standing = {}.compare_by_identity
|
|
73
|
+
entries.each { |job, payload, _| standing[job] = true if payload[Batch::METADATA_KEY] } if counted
|
|
74
|
+
groups = entries.group_by do |_, payload, due_at|
|
|
75
|
+
[payload["queue_name"] || Pgbus.configuration.default_queue, payload["priority"], due_delay(due_at)]
|
|
76
|
+
end
|
|
77
|
+
groups.each do |(queue, priority, delay), group|
|
|
78
|
+
enqueue_immediate(queue, group.map(&:first), priority: priority, delay: delay, payloads: group.map { _1[1] },
|
|
79
|
+
counted: standing, tracked: counted)
|
|
80
|
+
rescue StandardError => e
|
|
81
|
+
error = e
|
|
82
|
+
end
|
|
83
|
+
sent = jobs.count(&:successfully_enqueued?)
|
|
84
|
+
unsent = entries.reject { |job, *| job.successfully_enqueued? }
|
|
85
|
+
retried, failed, error = retry_coalesced(unsent, standing, error)
|
|
86
|
+
Coalesce::Result.new(buffered: entries.size, sent: sent, retried: retried, failed: failed, error: error)
|
|
87
|
+
end
|
|
88
|
+
|
|
44
89
|
private
|
|
45
90
|
|
|
91
|
+
# Holds +active_job+ in +scope+, serialized now, when the bulk path can
|
|
92
|
+
# send it, a future one included (+due_at+, its scheduled time: the delay is
|
|
93
|
+
# what is left at the flush, issue #686). Sent at once instead:
|
|
94
|
+
# uniqueness and concurrency (their lock or slot, and its lease over the
|
|
95
|
+
# delay, is taken at enqueue), a retry re-enqueue (#424) and a deploy task run's job (#660), which need the
|
|
96
|
+
# single path's bookkeeping, a batch member outside its own batch's
|
|
97
|
+
# scope (Pgbus.batch opens one for its block, issue #683; an outer
|
|
98
|
+
# scope's flush could come after the sweep reads the batch as stalled),
|
|
99
|
+
# and a class the scope may not hold: one that declares
|
|
100
|
+
# `pgbus_coalesce false` (Workflow::StepJob, whose enqueue failure is
|
|
101
|
+
# reported and swept, never raised), or, with config.coalesce_default
|
|
102
|
+
# false, one that does not declare `pgbus_coalesce true` (issue #689).
|
|
103
|
+
# Serializing now raises an unserializable argument here, as outside a
|
|
104
|
+
# scope, and keeps a later change to the job or its arguments out of
|
|
105
|
+
# the message.
|
|
106
|
+
def coalesce(scope, active_job, due_at: nil)
|
|
107
|
+
return false if Uniqueness.uniqueness_config(active_job) || concurrency_config(active_job)
|
|
108
|
+
return false if active_job.executions.to_i.positive?
|
|
109
|
+
return false if active_job.is_a?(DeployTaskRunId) && active_job.deploy_task_run_id
|
|
110
|
+
return false if member_batch_id(active_job) != scope.batch_id
|
|
111
|
+
return false unless coalesce_class?(active_job.class)
|
|
112
|
+
|
|
113
|
+
payload = tag_bulk_member(FairShare.inject_metadata(active_job, Serializer.serialize_job_hash(active_job)), active_job)
|
|
114
|
+
scope.push(self, active_job, payload, due_at)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# A class with pgbus_coalesce? (Coalesce::JobMixin's, or an app's own
|
|
118
|
+
# hook from before #689, which then wins over the macro and the config)
|
|
119
|
+
# answers for itself; a class without it follows config.coalesce_default,
|
|
120
|
+
# like one that declares nothing.
|
|
121
|
+
def coalesce_class?(klass)
|
|
122
|
+
klass.respond_to?(:pgbus_coalesce?) ? klass.pgbus_coalesce? : Pgbus.configuration.coalesce_default
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# Whole seconds until +job+ is due, 0 for a job due now.
|
|
126
|
+
def job_delay(job)
|
|
127
|
+
scheduled_in_future?(job) ? delay_until(job.scheduled_at.to_f) : 0
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Whole seconds until +due_at+ (a scheduled time held by a coalesce
|
|
131
|
+
# scope), counted from now, the flush: 0 for none or a time past.
|
|
132
|
+
def due_delay(due_at)
|
|
133
|
+
due_at ? delay_until(due_at.to_f) : 0
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# Each held job the bulk left unsent, on its own: for a job coalesce
|
|
137
|
+
# admitted, the single path is the plain send, plus a batch member's
|
|
138
|
+
# count and backfill. Returns [retried count, failed jobs, the last error].
|
|
139
|
+
def retry_coalesced(entries, counted, error)
|
|
140
|
+
retried = 0
|
|
141
|
+
failed = []
|
|
142
|
+
entries.each do |job, payload, due_at|
|
|
143
|
+
if resend_coalesced(job, payload, counted: counted.key?(job), delay: due_delay(due_at))
|
|
144
|
+
retried += 1
|
|
145
|
+
else
|
|
146
|
+
failed << job
|
|
147
|
+
end
|
|
148
|
+
rescue StandardError => e
|
|
149
|
+
error = e
|
|
150
|
+
failed << job
|
|
151
|
+
end
|
|
152
|
+
[retried, failed, error]
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# A batch member not +counted+ is counted in first, as a single
|
|
156
|
+
# enqueue is, and uncounted when its send fails before any message can
|
|
157
|
+
# exist; one the bulk counted keeps that count (its send's outcome is
|
|
158
|
+
# unknown) and is only sent.
|
|
159
|
+
def resend_coalesced(job, payload, counted:, delay: 0) # rubocop:disable Naming/PredicateMethod -- sends; the result says whether
|
|
160
|
+
queue = payload["queue_name"] || Pgbus.configuration.default_queue
|
|
161
|
+
priority = payload["priority"]
|
|
162
|
+
member = payload[Batch::METADATA_KEY]
|
|
163
|
+
Batch.track_enqueue(payload) if member && !counted
|
|
164
|
+
begin
|
|
165
|
+
msg_id = Pgbus.client.send_message(queue, payload, delay: delay, priority: priority)
|
|
166
|
+
rescue StandardError => e
|
|
167
|
+
Batch.untrack_enqueue(payload) if member && !counted && !ambiguous_delivery?(e)
|
|
168
|
+
raise
|
|
169
|
+
end
|
|
170
|
+
unless msg_id
|
|
171
|
+
Batch.untrack_enqueue(payload) if member && !counted
|
|
172
|
+
return false
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
job.provider_job_id = msg_id
|
|
176
|
+
job.successfully_enqueued = true
|
|
177
|
+
Batch.backfill_executions([payload], [msg_id], physical_queue(queue, priority)) if member
|
|
178
|
+
true
|
|
179
|
+
end
|
|
180
|
+
|
|
46
181
|
# One job of an enqueue_all that cannot take the bulk path.
|
|
47
182
|
# enqueue_with_concurrency marks it once it is live, as enqueue_immediate
|
|
48
183
|
# marks the bulk; on perform_later the adapter never sets
|
|
@@ -465,16 +600,30 @@ module Pgbus
|
|
|
465
600
|
batch_id ? payload_hash.merge(Batch::METADATA_KEY => batch_id) : payload_hash
|
|
466
601
|
end
|
|
467
602
|
|
|
468
|
-
|
|
603
|
+
# +payloads+: already built (a Coalesce scope serialized them at push).
|
|
604
|
+
# +counted+ (deliver_coalesced) collects the batch members whose count
|
|
605
|
+
# stands after a failure, so their retry does not count them twice.
|
|
606
|
+
# The bookkeeping around the send is one statement per group (issue
|
|
607
|
+
# #683): track_bulk's insert, the backfill, or the untrack on a failure.
|
|
608
|
+
# +tracked+: the payloads are already counted into their batch.
|
|
609
|
+
# +delay+: whole seconds every job of the group waits (issue #686).
|
|
610
|
+
def enqueue_immediate(queue, jobs, priority: nil, delay: 0, payloads: nil, counted: nil, tracked: false)
|
|
469
611
|
return if jobs.empty?
|
|
470
612
|
|
|
471
|
-
payloads
|
|
613
|
+
payloads ||= jobs.map do |j|
|
|
472
614
|
tag_bulk_member(FairShare.inject_metadata(j, Serializer.serialize_job_hash(j)), j)
|
|
473
615
|
end
|
|
474
|
-
track_bulk(payloads)
|
|
616
|
+
track_bulk(payloads) unless tracked
|
|
617
|
+
tracked = true
|
|
475
618
|
physical = physical_queue(queue, priority)
|
|
476
619
|
msg_ids = nil
|
|
477
|
-
|
|
620
|
+
sending = true
|
|
621
|
+
msg_ids = if delay.positive?
|
|
622
|
+
Pgbus.client.send_batch(queue, payloads, delay: delay, priority: priority)
|
|
623
|
+
else
|
|
624
|
+
Pgbus.client.send_batch(queue, payloads, priority: priority)
|
|
625
|
+
end
|
|
626
|
+
sent = true
|
|
478
627
|
|
|
479
628
|
unless msg_ids.is_a?(Array) && msg_ids.size == jobs.size
|
|
480
629
|
raise Pgbus::EnqueueError, "Pgbus batch enqueue failed: expected #{jobs.size} ids, got #{msg_ids&.size || 0}"
|
|
@@ -484,19 +633,48 @@ module Pgbus
|
|
|
484
633
|
job.provider_job_id = id
|
|
485
634
|
job.successfully_enqueued = true
|
|
486
635
|
end
|
|
487
|
-
|
|
636
|
+
Batch.backfill_executions(payloads, msg_ids, physical)
|
|
488
637
|
rescue Pgbus::EnqueueError
|
|
489
|
-
Array(payloads).
|
|
490
|
-
|
|
491
|
-
|
|
638
|
+
unsent = Array(payloads).each_index.select { |index| msg_ids.nil? || msg_ids[index].nil? }
|
|
639
|
+
# Noted before the untrack, which can raise: a member with an id keeps
|
|
640
|
+
# its count either way.
|
|
641
|
+
note_counted(counted, jobs, payloads, Array(payloads).each_index.to_a - unsent)
|
|
642
|
+
# The unsent ones are uncounted here: their retry counts them again.
|
|
643
|
+
unsent.each { |index| counted&.delete(jobs[index]) }
|
|
644
|
+
Batch.untrack_enqueue_all(payloads.values_at(*unsent))
|
|
492
645
|
raise
|
|
493
|
-
rescue
|
|
494
|
-
Pgbus.logger.error { "[Pgbus] #{e.message}" }
|
|
646
|
+
rescue StandardError => e
|
|
647
|
+
Pgbus.logger.error { "[Pgbus] #{e.message}" } if e.is_a?(Pgbus::SchemaNotReady)
|
|
648
|
+
# After the send returned, its messages are live: the counts stand.
|
|
649
|
+
settle_counted(counted, jobs, payloads, ambiguous: sent || (sending && ambiguous_delivery?(e))) if tracked
|
|
495
650
|
raise
|
|
496
651
|
ensure
|
|
497
652
|
jobs.each { |j| forget_enqueue_batch_id(j) }
|
|
498
653
|
end
|
|
499
654
|
|
|
655
|
+
# A coalesce delivery's members after a failed send (+counted+ set):
|
|
656
|
+
# when the send may have committed, their counts stand and the retry
|
|
657
|
+
# does not count them again; when no message can exist, they are
|
|
658
|
+
# uncounted now and the retry counts each again, so a member that
|
|
659
|
+
# fails twice leaves no row behind. Without +counted+ (enqueue_all) the
|
|
660
|
+
# counts stand, as they always did.
|
|
661
|
+
def settle_counted(counted, jobs, payloads, ambiguous:)
|
|
662
|
+
return unless counted
|
|
663
|
+
return note_counted(counted, jobs, payloads, Array(payloads).each_index.to_a) if ambiguous
|
|
664
|
+
|
|
665
|
+
jobs.each { |job| counted.delete(job) }
|
|
666
|
+
Batch.untrack_enqueue_all(payloads)
|
|
667
|
+
end
|
|
668
|
+
|
|
669
|
+
# The members at +indexes+ stay counted in their batch (their send's
|
|
670
|
+
# outcome is unknown, or it returned their id): a retry sends them
|
|
671
|
+
# without counting them again.
|
|
672
|
+
def note_counted(counted, jobs, payloads, indexes)
|
|
673
|
+
return unless counted
|
|
674
|
+
|
|
675
|
+
indexes.each { |index| counted[jobs[index]] = true if payloads[index][Batch::METADATA_KEY] }
|
|
676
|
+
end
|
|
677
|
+
|
|
500
678
|
# One guarded increment per batch for the whole bulk, not one per job.
|
|
501
679
|
# When a later batch refuses (finished), the batches already counted are
|
|
502
680
|
# uncounted before the error goes up: nothing has been sent yet.
|