pgbus 1.0.0 → 1.1.1
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 +24 -0
- data/README.md +11 -1
- data/app/models/pgbus/job_stat.rb +4 -2
- data/app/models/pgbus/stream_queue.rb +37 -25
- data/app/models/pgbus/stream_stat.rb +15 -8
- data/lib/pgbus/active_job/adapter.rb +13 -3
- data/lib/pgbus/active_job/coalesce/job_mixin.rb +40 -0
- data/lib/pgbus/active_job/coalesce.rb +3 -1
- data/lib/pgbus/configuration.rb +29 -0
- data/lib/pgbus/engine.rb +1 -0
- data/lib/pgbus/pgmq_schema/pgmq_v1.13.2.sql +2354 -0
- data/lib/pgbus/streams/coalescer.rb +42 -6
- data/lib/pgbus/testing.rb +19 -0
- data/lib/pgbus/version.rb +1 -1
- data/lib/pgbus/workflow/step_job.rb +11 -3
- data/sig/pgbus/active_job/adapter.rbs +12 -0
- data/sig/pgbus/configuration.rbs +4 -0
- metadata +3 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 5b361fe772144c29017651d5a839827f23ef6f259c7607970e1ee10a052693e6
|
|
4
|
+
data.tar.gz: 9d2b5cfe211b22334441641451d7db4d10618cb0e141edf5f9afaeb4dfc0e0c7
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 5c5c64b410aaa7f4b1972e4fa6b982162ffdee46c51d7e92ef590729664f5b9ee2d13348fe2de2bd0ae5ce1b6c6fe634017d56808e1de7a8026fbf7609840d97
|
|
7
|
+
data.tar.gz: b370b3fdd08557d9eabfa1a05219f5ffd0ad73fa7a08ef22a5171e04bcd48c56b42bd081f3caf7a49b75efeaa43d3e9d04c800cd1c2dfa9cc86c0cf639c7159e
|
data/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,30 @@
|
|
|
8
8
|
|
|
9
9
|
### Security
|
|
10
10
|
|
|
11
|
+
## [1.1.1] - 2026-11-27
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- **`config.streams_coalesce_scheduler` and `Pgbus::Streams::Coalescer::InlineScheduler`** (#694). The coalescer reads the scheduler when a window's flush is scheduled: any object with `schedule(delay_seconds) { ... }`, or `nil` (the default) for its `Concurrent::ScheduledTask` timer. `InlineScheduler` runs the flush at once on the thread that submits it. When none is configured, `Pgbus::Testing.fake!` and `.inline!` select it, so a `broadcast(..., coalesce:)` in a test writes on the test thread's own connection, before it returns when no transaction is open (a durable one inside an open transaction is still submitted at its commit); `disabled!` restores the timer. A scheduler without `#schedule` fails `validate!`. A scheduler the application configured is left alone. This replaces prepending `Coalescer::ScheduledTaskScheduler#schedule` in a test suite.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- **`Pgbus::Testing.fake!` and `.inline!` no longer coalesce** (#694). Every `broadcast(..., coalesce:)` submit is broadcast at once, so a test that asserted only the last frame of a window now sees each frame. Set `config.streams_coalesce_scheduler` to a scheduler of your own to keep the window in tests.
|
|
20
|
+
|
|
21
|
+
### Fixed
|
|
22
|
+
|
|
23
|
+
- **The stream registry and stream stats return their ActiveRecord lease** (#694). `StreamQueue.record!`, `table_exists?`, the registry load and `fingerprint_matched_names`, and `StreamStat.record!` and `table_exists?`, reached the database through a bare `connection`, a lease nothing returned on Rails 7.2+ (and `StreamStat.cleanup!` / `JobStat.cleanup!`, the dispatcher's prunes, through a relation, which leases the same way on Rails 7.1). The first durable broadcast of a stream records it, and for a coalesced broadcast that ran on a Concurrent IO thread no Rails executor wraps: each such thread kept a `BusRecord` connection checked out for its life. Under a pinned pool (Rails 7.2+ transactional tests) that lease was the test's pinned connection and outlived the test, so the next test's setup and the IO thread could drive one `PG::Connection` at once and hang. They now run inside `connection_pool.with_connection`, as the job path does since #649: a caller's own lease (a request, a job, an open transaction) is reused, and one taken is returned. The `Pgbus/BareConnectionLease` cop covers both models.
|
|
24
|
+
|
|
25
|
+
## [1.1.0] - 2026-11-24
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- **`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.
|
|
30
|
+
|
|
31
|
+
### Changed
|
|
32
|
+
|
|
33
|
+
- **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.
|
|
34
|
+
|
|
11
35
|
## [1.0.0] - 2026-11-21
|
|
12
36
|
|
|
13
37
|
**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.
|
data/README.md
CHANGED
|
@@ -848,6 +848,13 @@ config.middleware.insert_after ActionDispatch::Executor, Pgbus::ActiveJob::Coale
|
|
|
848
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
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
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
|
+
```
|
|
851
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.
|
|
852
859
|
|
|
853
860
|
The scope emits `pgbus.coalesce` with `buffered`, `sent`, `retried`, `failed` and `duration` (ms).
|
|
@@ -865,7 +872,7 @@ batch = Pgbus.batch(description: "Import users", properties: { initiated_by: cur
|
|
|
865
872
|
end
|
|
866
873
|
```
|
|
867
874
|
|
|
868
|
-
`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, 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.
|
|
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.
|
|
869
876
|
|
|
870
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.
|
|
871
878
|
|
|
@@ -1888,6 +1895,8 @@ Superseded frames never hit the bus at all — no PGMQ insert, no NOTIFY, no fan
|
|
|
1888
1895
|
|
|
1889
1896
|
Semantics: the first submit for a `(stream, target)` schedules the flush one window later; every subsequent submit within that window only overwrites the buffered payload. Latency is bounded to one window (trailing-edge-with-max-wait, not a resettable debounce). The flush re-enters the normal broadcast path, so a coalesced frame still composes with `visible_to:`, `exclude:`, `event:`, and `durable:`. Coalescing is process-wide and in-memory — behind multiple Puma workers or Falcon processes, each process debounces its own submissions independently.
|
|
1890
1897
|
|
|
1898
|
+
In tests, unless you set `config.streams_coalesce_scheduler` yourself, `Pgbus::Testing.fake!` and `.inline!` flush every coalesced broadcast at once, on the thread that submits it, so it writes on that thread's own connection and no IO thread takes a connection (and no frame is held back: each submit is broadcast). With no transaction open the flush runs before `broadcast` returns; a durable coalesced broadcast made inside an open transaction is submitted at its commit, as outside the test modes, and flushes then. `disabled!` restores the timer. `config.streams_coalesce_scheduler` takes any object with `schedule(delay_seconds) { ... }`, such as `Pgbus::Streams::Coalescer::InlineScheduler.new`, read when a window's flush is scheduled; `nil` (the default) is the timer. A scheduler you set yourself is left alone by the test modes, so its own threading applies in tests too.
|
|
1899
|
+
|
|
1891
1900
|
### Presence
|
|
1892
1901
|
|
|
1893
1902
|
Pgbus tracks who is currently subscribed to a stream via a `pgbus_presence_members` table. This is the standard "X people are in this room" feature that chat apps and collaboration tools need:
|
|
@@ -2638,6 +2647,7 @@ Curated headline options for the README. The full operator reference (with types
|
|
|
2638
2647
|
| `streams_database_url` / `streams_host` / `streams_port` | `nil` | Override the streamer's LISTEN connection target (e.g. direct primary port when workers use a pooler) |
|
|
2639
2648
|
| `streams_pool_database_url` / `streams_pool_host` / `streams_pool_port` | `nil` | Override the streams **pool** target independently of LISTEN (so pool traffic can stay on the pooler while LISTEN stays direct) |
|
|
2640
2649
|
| `streams_test_mode` | `false` | Return a stub SSE response without hijack or background threads. Auto-enabled by `Pgbus::Testing.fake!`/`.inline!`. See [SSE streams in tests](#sse-streams-in-tests). |
|
|
2650
|
+
| `streams_coalesce_scheduler` | `nil` | What runs a `coalesce:` broadcast's flush: an object with `schedule(delay_seconds) { ... }`. `nil` is the timer; `Pgbus::Testing.fake!`/`.inline!` select `Pgbus::Streams::Coalescer::InlineScheduler`, which flushes on the calling thread. See [`coalesce:`](#coalesce--publish-side-debounce). |
|
|
2641
2651
|
| `streams_stats_enabled` | `false` | Record stream broadcast/connect/disconnect stats (opt-in, can be high volume) |
|
|
2642
2652
|
| `streams_path` | `nil` | Custom URL path for the SSE endpoint (nil = auto-detected from engine mount) |
|
|
2643
2653
|
| `execution_mode` | `:threads` | Global execution mode (`:threads` or `:async`). Per-worker override via capsule config. |
|
|
@@ -178,9 +178,11 @@ module Pgbus
|
|
|
178
178
|
.map { |q, avg, p95, count| { queue_name: q, avg_ms: avg.to_i, p95_ms: p95.to_i, count: count.to_i } }
|
|
179
179
|
end
|
|
180
180
|
|
|
181
|
-
# Cleanup old stats
|
|
181
|
+
# Cleanup old stats. Off-request (the dispatcher), so the delete takes its
|
|
182
|
+
# own lease and returns it; delete_all leases through `connection` on
|
|
183
|
+
# Rails 7.1 (issue #694).
|
|
182
184
|
def self.cleanup!(older_than:)
|
|
183
|
-
where("created_at < ?", older_than).delete_all
|
|
185
|
+
connection_pool.with_connection { where("created_at < ?", older_than).delete_all }
|
|
184
186
|
end
|
|
185
187
|
end
|
|
186
188
|
end
|
|
@@ -54,25 +54,33 @@ module Pgbus
|
|
|
54
54
|
# `table_exists?` guard above passes) poisons every subsequent record!
|
|
55
55
|
# in the process with "No unique index found". The unique index is owned
|
|
56
56
|
# by this gem's own migration, so there is nothing to resolve.
|
|
57
|
+
#
|
|
58
|
+
# The write runs inside `connection_pool.with_connection` (issue #694):
|
|
59
|
+
# the coalescer flushes on a Concurrent IO thread no Rails executor
|
|
60
|
+
# wraps, so a bare `connection` there was a lease nobody returned. A
|
|
61
|
+
# caller that already holds one (a request, a job, an open
|
|
62
|
+
# transaction) keeps writing on it.
|
|
57
63
|
def record!(queue_name)
|
|
58
64
|
return false unless table_exists?
|
|
59
65
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
@
|
|
75
|
-
|
|
66
|
+
connection_pool.with_connection do |conn|
|
|
67
|
+
conn.execute(
|
|
68
|
+
"INSERT INTO #{conn.quote_table_name(table_name)} (queue_name) " \
|
|
69
|
+
"VALUES (#{conn.quote(queue_name)}) ON CONFLICT (queue_name) DO NOTHING"
|
|
70
|
+
)
|
|
71
|
+
# Keep the in-process cache consistent with the write so a subsequent
|
|
72
|
+
# stream? check reflects this registration without a re-query. Only
|
|
73
|
+
# update an ALREADY-LOADED cache — if @all_names is still nil (this
|
|
74
|
+
# process hasn't queried the registry yet), seeding it here would
|
|
75
|
+
# fabricate a one-entry set and silently hide every other
|
|
76
|
+
# already-registered stream until the next reset_cache!. Leaving it
|
|
77
|
+
# nil lets the next all_names call do a real load, which already
|
|
78
|
+
# includes this row since the insert above has committed. Taken
|
|
79
|
+
# while the connection is held; all_names loads outside the lock.
|
|
80
|
+
@names_lock.synchronize do
|
|
81
|
+
@names_generation += 1
|
|
82
|
+
@all_names = (@all_names | [queue_name]).freeze if @all_names
|
|
83
|
+
end
|
|
76
84
|
end
|
|
77
85
|
true
|
|
78
86
|
rescue ActiveRecord::ActiveRecordError => e
|
|
@@ -117,13 +125,16 @@ module Pgbus
|
|
|
117
125
|
# (`a_<queue>_msg_id_idx`). Job queues never get this index. Safe to call
|
|
118
126
|
# when pgmq is absent — returns an empty set rather than raising.
|
|
119
127
|
def fingerprint_matched_names
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
128
|
+
names = connection_pool.with_connection do |conn|
|
|
129
|
+
conn.select_values(<<~SQL.squish)
|
|
130
|
+
SELECT m.queue_name
|
|
131
|
+
FROM pgmq.meta m
|
|
132
|
+
INNER JOIN pg_indexes i
|
|
133
|
+
ON i.schemaname = 'pgmq'
|
|
134
|
+
AND i.indexname = 'a_' || m.queue_name || '_msg_id_idx'
|
|
135
|
+
SQL
|
|
136
|
+
end
|
|
137
|
+
Set.new(names)
|
|
127
138
|
rescue StandardError => e
|
|
128
139
|
Pgbus.logger.debug { "[Pgbus] Failed to discover stream queue fingerprints: #{e.message}" }
|
|
129
140
|
Set.new
|
|
@@ -167,7 +178,7 @@ module Pgbus
|
|
|
167
178
|
def table_exists?
|
|
168
179
|
return @table_exists if defined?(@table_exists) && @table_exists
|
|
169
180
|
|
|
170
|
-
@table_exists =
|
|
181
|
+
@table_exists = connection_pool.with_connection { |conn| conn.table_exists?(table_name) }
|
|
171
182
|
rescue StandardError => e
|
|
172
183
|
Pgbus.logger.debug { "[Pgbus] Failed to check stream queue table: #{e.message}" }
|
|
173
184
|
false
|
|
@@ -190,7 +201,8 @@ module Pgbus
|
|
|
190
201
|
def load_names
|
|
191
202
|
return Set.new unless table_exists?
|
|
192
203
|
|
|
193
|
-
|
|
204
|
+
# pluck leases through `connection` on Rails 7.1 (issue #694).
|
|
205
|
+
Set.new(connection_pool.with_connection { all.pluck(:queue_name) })
|
|
194
206
|
rescue StandardError => e
|
|
195
207
|
Pgbus.logger.debug { "[Pgbus] Failed to load stream queues: #{e.message}" }
|
|
196
208
|
Set.new
|
|
@@ -26,15 +26,20 @@ module Pgbus
|
|
|
26
26
|
# Records a stream event. Called from the Dispatcher when the
|
|
27
27
|
# `streams_stats_enabled` flag is set. Errors are swallowed so a
|
|
28
28
|
# missing table or a connection blip cannot kill the dispatcher.
|
|
29
|
+
# The dispatcher records off-request, where no Rails executor returns a
|
|
30
|
+
# lease, so the write takes its own through `with_connection` and gives
|
|
31
|
+
# it back (issue #694); create! leases through `connection` on Rails 7.1.
|
|
29
32
|
def self.record!(stream_name:, event_type:, duration_ms: 0, fanout: nil)
|
|
30
33
|
return unless table_exists?
|
|
31
34
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
connection_pool.with_connection do
|
|
36
|
+
create!(
|
|
37
|
+
stream_name: stream_name,
|
|
38
|
+
event_type: event_type,
|
|
39
|
+
duration_ms: duration_ms.to_i,
|
|
40
|
+
fanout: fanout
|
|
41
|
+
)
|
|
42
|
+
end
|
|
38
43
|
rescue StandardError => e
|
|
39
44
|
Pgbus.logger.debug { "[Pgbus] Failed to record stream stat: #{e.message}" }
|
|
40
45
|
end
|
|
@@ -55,7 +60,7 @@ module Pgbus
|
|
|
55
60
|
def self.table_exists?
|
|
56
61
|
return @table_exists if defined?(@table_exists)
|
|
57
62
|
|
|
58
|
-
@table_exists =
|
|
63
|
+
@table_exists = connection_pool.with_connection { |conn| conn.table_exists?(table_name) }
|
|
59
64
|
rescue StandardError => e
|
|
60
65
|
Pgbus.logger.debug { "[Pgbus] Failed to check stream stat table: #{e.message}" }
|
|
61
66
|
false
|
|
@@ -119,8 +124,10 @@ module Pgbus
|
|
|
119
124
|
|
|
120
125
|
# Cleanup old stats. Called from Pgbus::Process::Dispatcher on the
|
|
121
126
|
# same cadence as JobStat.cleanup! using the shared stats_retention.
|
|
127
|
+
# Off-request, so the delete takes its own lease and returns it (issue
|
|
128
|
+
# #694); delete_all leases through `connection` on Rails 7.1.
|
|
122
129
|
def self.cleanup!(older_than:)
|
|
123
|
-
where("created_at < ?", older_than).delete_all
|
|
130
|
+
connection_pool.with_connection { where("created_at < ?", older_than).delete_all }
|
|
124
131
|
end
|
|
125
132
|
end
|
|
126
133
|
end
|
|
@@ -96,8 +96,10 @@ module Pgbus
|
|
|
96
96
|
# single path's bookkeeping, a batch member outside its own batch's
|
|
97
97
|
# scope (Pgbus.batch opens one for its block, issue #683; an outer
|
|
98
98
|
# scope's flush could come after the sweep reads the batch as stalled),
|
|
99
|
-
# and a
|
|
100
|
-
#
|
|
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).
|
|
101
103
|
# Serializing now raises an unserializable argument here, as outside a
|
|
102
104
|
# scope, and keeps a later change to the job or its arguments out of
|
|
103
105
|
# the message.
|
|
@@ -106,12 +108,20 @@ module Pgbus
|
|
|
106
108
|
return false if active_job.executions.to_i.positive?
|
|
107
109
|
return false if active_job.is_a?(DeployTaskRunId) && active_job.deploy_task_run_id
|
|
108
110
|
return false if member_batch_id(active_job) != scope.batch_id
|
|
109
|
-
return false
|
|
111
|
+
return false unless coalesce_class?(active_job.class)
|
|
110
112
|
|
|
111
113
|
payload = tag_bulk_member(FairShare.inject_metadata(active_job, Serializer.serialize_job_hash(active_job)), active_job)
|
|
112
114
|
scope.push(self, active_job, payload, due_at)
|
|
113
115
|
end
|
|
114
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
|
+
|
|
115
125
|
# Whole seconds until +job+ is due, 0 for a job due now.
|
|
116
126
|
def job_delay(job)
|
|
117
127
|
scheduled_in_future?(job) ? delay_until(job.scheduled_at.to_f) : 0
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
module ActiveJob
|
|
5
|
+
class Coalesce
|
|
6
|
+
# Whether a Pgbus.coalesce scope (the request middleware's, a batch's)
|
|
7
|
+
# may hold a job class (issue #689). Included on ActiveJob::Base by the
|
|
8
|
+
# engine:
|
|
9
|
+
#
|
|
10
|
+
# class ProcessItemJob < ApplicationJob
|
|
11
|
+
# pgbus_coalesce false # sent at its perform_later, inside a scope too
|
|
12
|
+
# end
|
|
13
|
+
#
|
|
14
|
+
# A class that declares nothing follows config.coalesce_default (true:
|
|
15
|
+
# held). With the default false, only classes that declare
|
|
16
|
+
# `pgbus_coalesce true` are held. Subclasses inherit the setting.
|
|
17
|
+
module JobMixin
|
|
18
|
+
extend ActiveSupport::Concern
|
|
19
|
+
|
|
20
|
+
included do
|
|
21
|
+
# A per-class setting the job's own class body writes at load
|
|
22
|
+
# (`pgbus_coalesce false`); the adapter only reads it at enqueue.
|
|
23
|
+
class_attribute :pgbus_coalesce_enabled, instance_writer: false, default: nil # rubocop:disable ThreadSafety/ClassAndModuleAttributes
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
class_methods do
|
|
27
|
+
def pgbus_coalesce(enabled = true) # rubocop:disable Style/OptionalBooleanParameter
|
|
28
|
+
self.pgbus_coalesce_enabled = enabled ? true : false
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The adapter's check: the class's own setting, else the configured default.
|
|
32
|
+
def pgbus_coalesce?
|
|
33
|
+
enabled = pgbus_coalesce_enabled
|
|
34
|
+
enabled.nil? ? Pgbus.configuration.coalesce_default : enabled
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
@@ -11,7 +11,9 @@ module Pgbus
|
|
|
11
11
|
# decide), serialized at perform_later; a future one with its scheduled
|
|
12
12
|
# time, so its delay is what is left at the flush (issue #686). One with
|
|
13
13
|
# uniqueness or concurrency, a retry re-enqueue, a deploy task run's job,
|
|
14
|
-
# a batch member outside its own batch's scope
|
|
14
|
+
# a batch member outside its own batch's scope, a Workflow::StepJob or a
|
|
15
|
+
# class the scope may not hold (`pgbus_coalesce false`, or no
|
|
16
|
+
# `pgbus_coalesce true` under config.coalesce_default false, issue #689)
|
|
15
17
|
# goes out at once, as it does outside a scope. Active Job's enqueue_after_transaction_commit runs before the
|
|
16
18
|
# adapter, so a job that defers reaches the buffer at commit, and a rolled
|
|
17
19
|
# back one never does.
|
data/lib/pgbus/configuration.rb
CHANGED
|
@@ -314,6 +314,15 @@ module Pgbus
|
|
|
314
314
|
# holds past it while a transaction is open on the batch's connection.
|
|
315
315
|
attr_accessor :coalesce_chunk_size
|
|
316
316
|
|
|
317
|
+
# Whether a Pgbus.coalesce scope holds a job class that declares nothing
|
|
318
|
+
# (issue #689). true: every bulk-eligible job is held unless its class
|
|
319
|
+
# declares `pgbus_coalesce false`. false: only classes that declare
|
|
320
|
+
# `pgbus_coalesce true` are held; every other job is sent at its
|
|
321
|
+
# perform_later, so its caller sees the real outcome. A class that
|
|
322
|
+
# defines pgbus_coalesce? itself (the hook before #689) answers for
|
|
323
|
+
# itself whatever this says.
|
|
324
|
+
attr_accessor :coalesce_default
|
|
325
|
+
|
|
317
326
|
# The MCP server's workflow write tools (issue #550): pgbus_workflow_resume,
|
|
318
327
|
# _cancel, _skip_step, _resume_at, _run_now and _signal. Off by default, and
|
|
319
328
|
# then they are never built, so tools/list cannot show them. Read once, when
|
|
@@ -354,6 +363,16 @@ module Pgbus
|
|
|
354
363
|
:streams_pool_autoscale_interval, :streams_application_name
|
|
355
364
|
attr_reader :streams_default_broadcast_mode # rubocop:disable Style/AccessorGrouping
|
|
356
365
|
|
|
366
|
+
# What runs a coalesced broadcast's flush (`broadcast(..., coalesce:)`):
|
|
367
|
+
# any object with `schedule(delay_seconds) { ... }`. nil (default) is the
|
|
368
|
+
# coalescer's Concurrent::ScheduledTask timer. Read when a window's flush
|
|
369
|
+
# is scheduled (its first submit), so it can change after boot. When it is
|
|
370
|
+
# nil, Pgbus::Testing.fake! / inline! set
|
|
371
|
+
# Pgbus::Streams::Coalescer::InlineScheduler, which flushes on the calling
|
|
372
|
+
# thread (issue #694), and disabled! clears that again; a scheduler the
|
|
373
|
+
# application set is left alone.
|
|
374
|
+
attr_accessor :streams_coalesce_scheduler
|
|
375
|
+
|
|
357
376
|
# NOTIFY-gated worker wakeups. When true, workers are woken by a
|
|
358
377
|
# NotifyListener PG connection that LISTENs on their queues' INSERT
|
|
359
378
|
# channels instead of blind-polling. Defaults to the value of
|
|
@@ -517,6 +536,7 @@ module Pgbus
|
|
|
517
536
|
@web_filter_sensitive = true
|
|
518
537
|
@web_queue_metrics_chunk_size = 100
|
|
519
538
|
@coalesce_chunk_size = 1_000
|
|
539
|
+
@coalesce_default = true
|
|
520
540
|
@deprecation_warned = Set.new
|
|
521
541
|
|
|
522
542
|
# HTTP health endpoints — nil port disables the standalone server.
|
|
@@ -683,6 +703,7 @@ module Pgbus
|
|
|
683
703
|
# usually want job stats on and stream stats off, or vice versa.
|
|
684
704
|
@streams_stats_enabled = false
|
|
685
705
|
@streams_test_mode = false
|
|
706
|
+
@streams_coalesce_scheduler = nil
|
|
686
707
|
@streams_default_broadcast_mode = :ephemeral
|
|
687
708
|
@streams_orphan_sweep_interval = 3600 # 1 hour
|
|
688
709
|
@streams_orphan_threshold = 86_400 # 24 hours
|
|
@@ -1144,6 +1165,7 @@ module Pgbus
|
|
|
1144
1165
|
raise Pgbus::ConfigurationError, "coalesce_chunk_size must be a positive integer"
|
|
1145
1166
|
end
|
|
1146
1167
|
|
|
1168
|
+
raise Pgbus::ConfigurationError, "coalesce_default must be true or false" unless [true, false].include?(coalesce_default)
|
|
1147
1169
|
raise Pgbus::ConfigurationError, "require_primary must be true or false" unless [true, false].include?(require_primary)
|
|
1148
1170
|
raise Pgbus::ConfigurationError, "mcp_write_tools must be true or false" unless [true, false].include?(mcp_write_tools)
|
|
1149
1171
|
|
|
@@ -1405,6 +1427,13 @@ module Pgbus
|
|
|
1405
1427
|
validate_presence_settings!
|
|
1406
1428
|
validate_stream_authorization!
|
|
1407
1429
|
|
|
1430
|
+
# Coalescer#submit marks the key pending before it schedules, so a
|
|
1431
|
+
# scheduler that cannot schedule would leave that key stuck for good.
|
|
1432
|
+
if !streams_coalesce_scheduler.nil? && !streams_coalesce_scheduler.respond_to?(:schedule)
|
|
1433
|
+
raise Pgbus::ConfigurationError,
|
|
1434
|
+
"streams_coalesce_scheduler must respond to #schedule(delay_seconds) { ... } or be nil"
|
|
1435
|
+
end
|
|
1436
|
+
|
|
1408
1437
|
return if streams_orphan_threshold.nil?
|
|
1409
1438
|
return if streams_orphan_threshold.is_a?(Numeric) && streams_orphan_threshold.positive?
|
|
1410
1439
|
|
data/lib/pgbus/engine.rb
CHANGED