pgbus 0.26.0 → 0.27.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 +22 -2
- data/README.md +28 -0
- data/lib/pgbus/client/async_commit.rb +12 -17
- data/lib/pgbus/client/notify_stream.rb +16 -0
- data/lib/pgbus/client/session_gucs.rb +58 -0
- data/lib/pgbus/client.rb +4 -13
- data/lib/pgbus/dedicated_connection.rb +20 -7
- data/lib/pgbus/engine.rb +8 -0
- data/lib/pgbus/open_transaction.rb +96 -0
- data/lib/pgbus/signals/middleware.rb +23 -0
- data/lib/pgbus/signals.rb +282 -0
- data/lib/pgbus/streams.rb +3 -39
- data/lib/pgbus/testing/minitest.rb +1 -0
- data/lib/pgbus/testing.rb +36 -0
- data/lib/pgbus/version.rb +1 -1
- data/lib/pgbus/web/streamer/failover_listener.rb +132 -27
- data/lib/pgbus/web/streamer/hub_client.rb +46 -15
- data/lib/pgbus/web/streamer/hub_protocol.rb +6 -0
- data/lib/pgbus/web/streamer/instance.rb +37 -2
- data/lib/pgbus/web/streamer/listener.rb +113 -24
- data/lib/pgbus/web/streamer/master_hub.rb +87 -2
- data/lib/pgbus/web/streamer/signal_delivery.rb +136 -0
- data/lib/pgbus/web/streamer.rb +10 -0
- data/lib/pgbus.rb +21 -0
- data/sig/pgbus/client.rbs +1 -0
- data/sig/pgbus.rbs +13 -0
- metadata +6 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 1b883f03f4b08531d1e4847486beb29842afde42a872453606cae421952a86e6
|
|
4
|
+
data.tar.gz: '09f28e7f82f7e843ce8bd8aeda05c53481ade115e6f66fb2bc2197ae45d081df'
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: ca5ce2420a6df278b3aae31ebcca0c0dc1980373a8954254de83310a75c56574cda6b3549787a662b38ade7a7fa6a8d24a2471b2ba97981f22e04a6884f4c4fb
|
|
7
|
+
data.tar.gz: fecd5c8e775ef8367f9adceee008b6b02afea7b842ff9827bf000993e3fabb82534a49464e81b68e2fd35d5cb62ecd6cacff6efdd6c04d5eebb08c6e9859a7a7
|
data/CHANGELOG.md
CHANGED
|
@@ -1,15 +1,35 @@
|
|
|
1
1
|
## [Unreleased]
|
|
2
2
|
|
|
3
|
+
### Added
|
|
4
|
+
|
|
5
|
+
- **Process signals: `Pgbus.on_signal(name) { |payload| ... }` runs a block in every web process when any process calls `Pgbus.signal(name, payload = nil)` (issue #674).** This covers a per-process in-memory cache that every Puma worker must drop when its data changes, which had no supported route: the event bus delivers an event to one competing consumer in a worker process, and the streamer only woke SSE connections.
|
|
6
|
+
|
|
7
|
+
- **Sending.** A signal is a `NOTIFY` on `<queue_prefix>_signal_<name>`, sent through `Pgbus.client` (new `Client#notify_signal`). Inside an open ActiveRecord transaction it is sent at `COMMIT` and never on rollback. A `transaction(joinable: false)` block sends at once: the fixture transaction of an app's transactional tests is one, so an `after_commit { Pgbus.signal(...) }` still sends there. The payload is an optional String under NOTIFY's 7999-byte cap; an empty String arrives as `nil`. A name may use lowercase letters, digits and underscores, and its channel must fit the queue-name budget; anything else raises `ArgumentError`.
|
|
8
|
+
- **Transport.** The streamer's LISTEN connection carries the signal: each worker's `Listener` under `streams_listen_scope :process`, the `MasterHub`'s under `:master`. The hub fans it out over the hub socket with new frames: `ssub`/`sack`, refcounted per channel like a stream, and `signal`/`gap`, never dropped by the backpressure policy; a worker evicted for not draining fails over and reports a gap. No worker opens a LISTEN connection of its own. A worker whose master predates signals gets no `sack` and fails over to its own listener. A signal NOTIFY never enters the stream dispatch queue and is never dropped at `streams_dispatch_queue_limit`.
|
|
9
|
+
- **Running the blocks.** Subscribers run on a new per-process `SignalDelivery` thread, started by the first signal for a registered name, each inside `Rails.application.executor.wrap`. A block that raises is reported through `error_reporters` and the others still run. With 1 000 signals waiting behind a slow block, a further one is dropped and reported as a gap.
|
|
10
|
+
- **Eager start.** With at least one subscriber, a process's first request starts its streamer on a background thread (new `Pgbus::Signals::Middleware`, which the engine installs when `streams_enabled`). A process that never served an SSE connection still receives signals, and no request waits on the LISTEN connect. A failed start is reported and retried by a request 30 s later. The middleware adds about 100 ns to a request (65 ns once started; 1M calls, this machine). Without a subscriber nothing changes: no connection, no thread.
|
|
11
|
+
- **Gaps.** Delivery is at most once. Every `on_gap:` callable runs once, once the LISTEN is in place (gaps that arrive before it runs coalesce), after each gap: the process's first LISTEN (nothing sent before it reached the process), a listener reconnect, a worker failover from the master hub, or the hub's own listener reconnecting.
|
|
12
|
+
- **Failover retry.** A worker whose hub died and whose own listener cannot be built now retries the build every 5 s in the background, for streams too (it used to stay degraded until it recycled), then replays every subscription and runs `on_gap`; a retry in flight never holds up the worker's shutdown. The streamer's dedicated LISTEN connection (per worker, and the master hub's) now also opens with `connect_timeout=10`, beside the #664 keepalives (a keyword the connection options already set wins, and so does `PGCONNECT_TIMEOUT`; on libpq < 12, where #664 adds no keepalive keyword, `connect_timeout` is still added), so a connect to an unreachable streams host fails in 10 s instead of waiting out the OS's TCP retries.
|
|
13
|
+
- **Testing.** `Pgbus::Testing.fake!` records signals in `Pgbus::Testing.signals` (a `SignalRecord` with `name` and `payload`; `clear_signals!` empties it) without a NOTIFY. `inline!` also runs the blocks synchronously on the caller's thread, without the Rails executor, so `Current` attributes survive. Both record at the commit of a `transaction do … end` block, never on its rollback.
|
|
14
|
+
- **Scope.** Web processes only: pgbus worker processes are not subscribed.
|
|
15
|
+
- **Internals.** The open-transaction probe `Streams::Stream` used is now `Pgbus::OpenTransaction.current`, unchanged. On Rails 7.1, whose transactions have no `after_commit`, deferral goes through a transaction record.
|
|
16
|
+
|
|
17
|
+
Refs #674.
|
|
18
|
+
|
|
3
19
|
### Changed
|
|
4
20
|
|
|
5
21
|
- **A member-keyed presence `touch` no longer probes `information_schema` on a table without the seat columns, and a forced re-check no longer restarts the backoff (issue #666).** On a `pgbus_presence_members` table where `rails g pgbus:add_presence_seats` has not run, every member-keyed `touch`, `leave` and `sweep!` re-probed a cached "no seats" answer before it ran and restarted the #665 backoff at 30 s. The streamer touches once per connection per heartbeat, so a process with N member-keyed connections sent N catalog queries every `streams_heartbeat_interval` (15 s by default), and its backoff never took effect. A member-keyed `touch` now uses the cached answer and re-checks only on the backoff's schedule: three touches after a reset send one probe instead of four, and none while a "no" is cached. Assumed: on a table migrated under a running process, such a `touch` can also refresh that member's seat rows until the next re-check (at most 10 minutes, `SCHEMA_RECHECK_MAX_SECONDS`); it is an `UPDATE` of `last_seen_at`, so nothing is deleted. A member-keyed `leave` and `sweep!` still re-check a cached "no" before they delete, so they never delete seat rows on a migrated table (#515), now with one probe instead of up to two, answered from that probe. That re-check leaves the backoff alone: over a fresh "no" it changes neither the step nor the schedule however many disconnects force one, and over a "no" already due it is the timed re-check, one step. `reset_schema_cache!` still re-probes at once and starts again from 30 s. Refs #666.
|
|
6
22
|
|
|
23
|
+
- **pgmq-ruby 0.9.0 (was 0.8.2); the gemspec now requires `~> 0.9.0` (issue #656).** What reaches pgbus users is the connection pool: pgmq-ruby's checkout health check now resets a pooled connection in any state other than `CONNECTION_OK`, so a connection a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`) is recovered on the next checkout. Before, the checkout handed it out again, libpq refused every send (`no connection to the server`), and pgbus's stale-connection retry only recovered it on its last attempt by dropping both pools (#645): now the call succeeds on the first attempt, with no retry, no pool reload and no warning. pgmq-ruby also resets a connection whose call raised `PG::ConnectionBad` or `PG::UnableToSend` before it goes back to the pool (not a connection pgbus hands it through a callable, which it neither resets nor closes: the shared ActiveRecord connection, and dedicated connections in `connection_guc_mode = :session` with database.yml `variables`); native statements re-prepare on the new backend as on any reconnect. pgbus keeps its reload before the last stale retry for a connection that still fails after the health check passed it. A checkout reset of a connection in `connection_guc_mode = :session` with `variables` applies its `SET`s again (#671). `produce_topic` and `produce_batch_topic` now raise `PGMQ::Errors::MessageInvalidError` for a message that is not a String or headers that are neither a String nor nil, as `produce` has since 0.8.0. `Client#publish_to_topic` (what `Pgbus.publish` and the outbox poller call; `Pgbus::Testing`'s fake and inline modes never reach PGMQ) serializes the payload and headers to JSON Strings first, so it is unaffected; `headers: false`, which pgmq-ruby dropped before with an integer delay (and stored as JSON `false` with a fractional one) and now rejects, is passed as nil, so it is dropped at any delay. `spec/integration/connection_failure_spec.rb` now asserts the mid-reset connection is recovered at checkout (it failed on 0.8.2), in place of the two examples that pinned the old last-retry recovery. Refs #656.
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- **A pooled connection in `connection_guc_mode = :session` keeps its database.yml `variables` when it is reset (issue #671).** In `:session` mode the `variables` (`statement_timeout`, `lock_timeout` and the like) are applied with `SET` after connect, and `PG::Connection#reset` opens a new backend without them. pgmq-ruby's checkout health check resets an unhealthy pooled connection (`finished?` or `CONNECTION_BAD` since #332, and an intermediate state such as `CONNECTION_STARTED` since pgmq-ruby 0.9.0), so that connection went on serving the job or streams pool with the server's defaults. Each connection the `:session` connect lambda opens now re-applies its `SET`s when it is reset, whoever resets it. A connection whose `SET`s do not all complete, after a connect or a reset, is closed before the error reaches the caller, so it is never pooled without them; with pg 1.5.9 or later the next checkout resets it and applies the `SET`s again (an older pg cannot reset a closed connection, so it is replaced when the pool is reloaded before the last stale-connection retry; the call itself is retried only for a stale-connection error, so a `SET` that always fails, such as an invalid value, fails each time). The completion pipeline's own reset (#619) no longer applies the `SET`s itself (they ran twice), and a `SET` that fails there is now logged as `Resetting the connection or re-applying its session variables failed` and leaves the connection closed, where before the session carried on without its `variables`. `:options` mode, a String URL and the shared ActiveRecord connection are unaffected. Refs #671.
|
|
28
|
+
|
|
7
29
|
## [0.25.1] - 2026-11-15
|
|
8
30
|
|
|
9
31
|
### Changed
|
|
10
32
|
|
|
11
|
-
- **pgmq-ruby 0.9.0 (was 0.8.2); the gemspec now requires `~> 0.9.0` (issue #656).** What reaches pgbus users is the connection pool: pgmq-ruby's checkout health check now resets a pooled connection in any state other than `CONNECTION_OK`, so a connection a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`) is recovered on the next checkout. Before, the checkout handed it out again, libpq refused every send (`no connection to the server`), and pgbus's stale-connection retry only recovered it on its last attempt by dropping both pools (#645): now the call succeeds on the first attempt, with no retry, no pool reload and no warning. pgmq-ruby also resets a connection whose call raised `PG::ConnectionBad` or `PG::UnableToSend` before it goes back to the pool (not a connection pgbus hands it through a callable, which it neither resets nor closes: the shared ActiveRecord connection, and dedicated connections in `connection_guc_mode = :session` with database.yml `variables`); native statements re-prepare on the new backend as on any reconnect. pgbus keeps its reload before the last stale retry for a connection that still fails after the health check passed it. A checkout reset of a connection in `connection_guc_mode = :session` with `variables` does not re-run its `SET`s, as for a `CONNECTION_BAD` one before (#671). `produce_topic` and `produce_batch_topic` now raise `PGMQ::Errors::MessageInvalidError` for a message that is not a String or headers that are neither a String nor nil, as `produce` has since 0.8.0. `Client#publish_to_topic` (what `Pgbus.publish` and the outbox poller call; `Pgbus::Testing`'s fake and inline modes never reach PGMQ) serializes the payload and headers to JSON Strings first, so it is unaffected; `headers: false`, which pgmq-ruby dropped before with an integer delay (and stored as JSON `false` with a fractional one) and now rejects, is passed as nil, so it is dropped at any delay. `spec/integration/connection_failure_spec.rb` now asserts the mid-reset connection is recovered at checkout (it failed on 0.8.2), in place of the two examples that pinned the old last-retry recovery. Refs #656.
|
|
12
|
-
|
|
13
33
|
- **Changed default: the streamer's LISTEN keepalive `streams_listen_health_check_ms` is 5 000 ms instead of 250, and the listener's ack and stop budgets no longer follow it (issue #664).** Every web process running the streamer sent `SELECT 1` on its LISTEN connection four times a second, idle or not: 345 600 queries a day per process, the most frequent statement on a small fleet's database. Since #630 a connect no longer waits on that cycle (the listener wakes through a pipe), so the interval only bounds how long a LISTEN the server dropped on a still-open socket goes unnoticed; now one `SELECT 1` per 5 s idle cycle, 20× fewer. The interval was also wired into three wait budgets, so raising it slowed the failure paths: they now come from a new setting, **`streams_listen_ack_timeout_ms`** (default 1 250, a positive Integer, today's 250 + 1 000). `Listener#ensure_listening` waits at most that for a stuck listener's ack, `Listener#stop` joins for that plus its 5 s grace, and with `streams_listen_scope :master` the worker's `HubClient` waits that plus 1 s before failing over, as before relative to the hub's own budget; the master hub's listener gets the same ack budget. The streamer's dedicated LISTEN connection (per worker, and the master hub's) now opens with libpq TCP keepalives, `keepalives=1 keepalives_idle=5 keepalives_interval=2 keepalives_count=3 tcp_user_timeout=11000`, so a dead socket errors within ~11 s by these settings (5 s idle + 3 probes 2 s apart, and the matching `tcp_user_timeout`; on Linux, where `tcp_user_timeout` applies; the bound follows the settings, it was not measured) even between keepalives, and the listener reconnects and re-LISTENs; a keyword the connection options already set wins, a connection that names a service (`service=` or `PGSERVICE`) gets none so its service file's values stay in force, and on libpq < 12 none is added (the same gate `Client` uses for its read bounds, now `Pgbus::DedicatedConnection.libpq_supports_socket_bounds?`). The worker `NotifyListener` and the doctor's connection are unchanged. The pool autoscaler's check runs on the keepalive tick, so a `streams_pool_autoscale_interval` under 5 s (the default is 300 s) now runs every 5 s. A dedicated connection URL ending in a bare `?` no longer gets an empty `?&` parameter that failed the connect. An explicit `streams_listen_health_check_ms` keeps exactly its value: **pin `config.streams_listen_health_check_ms = 250` for the old keepalive.** If you set it to 5 000 as the workaround, the ack budget drops from 6 s back to 1.25 s. Measured on the same machine (`rake bench:streams`, which pins 100 ms; `rake bench:streams_scale` at M = 100 with the default, 250 ms before and 5 000 ms after, two rounds each): section 4 concurrent connect 0.91–3.07 ms per connect before, 0.86–3.06 ms after; scale bench, all 100 clients registered in 0.11–0.12 s before, 0.09–0.11 s after (one 0.24 s round at load 32, 0.09 s on a re-run), 0 misses either way. Refs #664.
|
|
14
34
|
|
|
15
35
|
### Fixed
|
data/README.md
CHANGED
|
@@ -47,6 +47,7 @@ PostgreSQL-native job processing and event bus for Rails, built on [PGMQ](https:
|
|
|
47
47
|
- [Health endpoints (liveness / readiness)](#health-endpoints-liveness--readiness)
|
|
48
48
|
- [Boot diagnostics banner](#boot-diagnostics-banner)
|
|
49
49
|
- [Real-time broadcasts](#real-time-broadcasts-turbo-streams-replacement)
|
|
50
|
+
- [Process signals](#process-signals)
|
|
50
51
|
- [Testing](#testing)
|
|
51
52
|
- [RSpec setup](#rspec-setup)
|
|
52
53
|
- [Minitest / TestUnit setup](#minitest--testunit-setup)
|
|
@@ -1987,6 +1988,29 @@ The Insights tab gains a "Real-time Streams" section with counts of broadcasts /
|
|
|
1987
1988
|
|
|
1988
1989
|
Overhead on a real Puma + PGMQ setup (`bundle exec rake bench:streams`): the most visible cost is an INSERT per connect/disconnect pair, which shows up under thundering-herd connect scenarios (K=50 concurrent connects: ~+20% per-connect latency). Steady-state broadcast and fanout numbers stay in the run-to-run noise band. Enable it if Insights is useful; leave it off if the write traffic worries you.
|
|
1989
1990
|
|
|
1991
|
+
### Process signals
|
|
1992
|
+
|
|
1993
|
+
Run a block in every web process when any process sends a signal: the way to tell every Puma worker "drop your in-memory cache now" when the data behind it changes.
|
|
1994
|
+
|
|
1995
|
+
```ruby
|
|
1996
|
+
# config/initializers/widgets.rb
|
|
1997
|
+
WIDGETS = Concurrent::Map.new
|
|
1998
|
+
|
|
1999
|
+
Pgbus.on_signal(:widgets_changed, on_gap: -> { WIDGETS.clear }) { |_payload| WIDGETS.clear }
|
|
2000
|
+
|
|
2001
|
+
class Widget < ApplicationRecord
|
|
2002
|
+
after_commit { Pgbus.signal(:widgets_changed) }
|
|
2003
|
+
end
|
|
2004
|
+
```
|
|
2005
|
+
|
|
2006
|
+
- `Pgbus.signal(name, payload = nil)` sends a `NOTIFY` on `<queue_prefix>_signal_<name>`. Inside an open ActiveRecord transaction it is sent at `COMMIT`, and never on rollback. The exception is a `transaction(joinable: false)` block (the kind transactional tests open around each example): there it is sent at once. The payload is an optional String under NOTIFY's 7999-byte cap; an empty String arrives as `nil`.
|
|
2007
|
+
- `Pgbus.on_signal(name) { |payload| ... }` registers a block in this process (register in an initializer, like `Pgbus::Streams.filters`). Names are lowercase letters, digits and underscores, and the channel must fit the queue-name budget.
|
|
2008
|
+
- The signal rides the streamer's LISTEN connection: one per web process under `streams_listen_scope :process`, the master hub's under `:master` (fanned out to every worker, so no worker opens a LISTEN connection of its own). With at least one subscriber, a process's first request starts that listener on a background thread (`Pgbus::Signals::Middleware`, installed by the engine; no request waits on the connect), so a process that never served an SSE connection still receives signals. A failed start is reported and retried by a request 30 s later. Without a subscriber nothing changes: no connection, no thread. Under `:master`, a worker that starts before the master hub has bound its socket uses a LISTEN connection of its own until it recycles, as an SSE-started worker does.
|
|
2009
|
+
- Blocks run on a dedicated thread (not the LISTEN thread, not the stream dispatcher), each inside the Rails executor. A block that raises is reported through `error_reporters` and the other blocks still run. When 1 000 signals are waiting behind a slow block, a further one is dropped and reported as a gap.
|
|
2010
|
+
- Delivery is at most once, within about a second. A signal sent while a process was not listening is lost: before its first LISTEN (whatever it cached at boot, or before a fork under `preload_app!`), while its LISTEN connection reconnected, or while a worker failed over from the master hub. After each such gap, the first LISTEN included, every `on_gap` runs once the LISTEN is in place (gaps that arrive while one is still waiting to run share that run), so it can assume it missed signals. A subscriber whose state can go stale needs an `on_gap`: no request waits for the first LISTEN, so a signal sent between a process's first request and its LISTEN reaches it only as that first gap. A worker whose hub died and whose own listener cannot connect retries every 5 s and runs `on_gap` when it succeeds.
|
|
2011
|
+
- Web processes only: pgbus worker processes do not receive signals. Signals need `streams_enabled` (the default) and a dedicated streams connection, as SSE does: pgbus builds it from `database_url`, a `connection_params` Hash, or the ActiveRecord database configuration, never from a Proc.
|
|
2012
|
+
- In tests, `Pgbus::Testing.fake!` records signals in `Pgbus::Testing.signals` without sending them, and `Pgbus::Testing.inline!` also runs the blocks synchronously on the calling thread, without the Rails executor, so `Current` attributes survive. Both record when the NOTIFY would be sent: at the commit of a `transaction do ... end` block, never on its rollback (the fixture transaction of transactional tests is not waited for). Set a mode in your suite (`config.before { Pgbus::Testing.fake! }`, as for SSE): with `Pgbus::Testing.disabled!` and an `on_signal` registered, the first request spec starts a real streamer, with a LISTEN connection and threads outside the test transaction.
|
|
2013
|
+
|
|
1990
2014
|
## Testing
|
|
1991
2015
|
|
|
1992
2016
|
Pgbus ships opt-in test helpers for both RSpec and Minitest. The testing module is **never autoloaded** by Zeitwerk -- you must `require` it explicitly, so it cannot leak into production.
|
|
@@ -2022,6 +2046,7 @@ RSpec.configure do |config|
|
|
|
2022
2046
|
config.append_after do
|
|
2023
2047
|
Pgbus::Testing.disabled!
|
|
2024
2048
|
Pgbus::Testing.store.clear!
|
|
2049
|
+
Pgbus::Testing.clear_signals!
|
|
2025
2050
|
end
|
|
2026
2051
|
end
|
|
2027
2052
|
```
|
|
@@ -2034,6 +2059,7 @@ RSpec.configure do |config|
|
|
|
2034
2059
|
config.append_after(:each, :pgbus) do
|
|
2035
2060
|
Pgbus::Testing.disabled!
|
|
2036
2061
|
Pgbus::Testing.store.clear!
|
|
2062
|
+
Pgbus::Testing.clear_signals!
|
|
2037
2063
|
end
|
|
2038
2064
|
end
|
|
2039
2065
|
|
|
@@ -2162,6 +2188,8 @@ Pgbus::Testing.disabled? # => true/false
|
|
|
2162
2188
|
|
|
2163
2189
|
The `:inline` mode skips delayed publishes (`delay: > 0`) -- those are captured in the store but not dispatched. Use `Pgbus::Testing.store.drain!` to manually dispatch all captured events including delayed ones.
|
|
2164
2190
|
|
|
2191
|
+
`Pgbus.signal` follows the same modes: `:fake` records `Pgbus::Testing::SignalRecord`s (`name`, `payload`) in `Pgbus::Testing.signals` (`Pgbus::Testing.clear_signals!` empties it), `:inline` records them and runs the process's `on_signal` blocks synchronously, and `:disabled` sends the NOTIFY. See [Process signals](#process-signals).
|
|
2192
|
+
|
|
2165
2193
|
### SSE streams in tests
|
|
2166
2194
|
|
|
2167
2195
|
When using `use_transactional_fixtures = true` (the default in Rails), pgbus SSE streams are incompatible with transactional test isolation. The `rack.hijack` mechanism spawns background threads that acquire their own database connections outside the test transaction, which causes:
|
|
@@ -103,8 +103,11 @@ module Pgbus
|
|
|
103
103
|
# A connection back in the pool in pipeline mode would break the next
|
|
104
104
|
# caller. A lost one is left as it is: pgmq-ruby resets a bad connection
|
|
105
105
|
# at its next checkout, and a reset leaves pipeline mode. One that cannot
|
|
106
|
-
# leave (results left unread by an interrupted read) is reset here.
|
|
106
|
+
# leave (results left unread by an interrupted read) is reset here. One
|
|
107
|
+
# a failed reset closed (its :session SETs failed, SessionGucs) is left
|
|
108
|
+
# closed too: pgmq-ruby resets it at the next checkout.
|
|
107
109
|
def leave_pipeline(conn)
|
|
110
|
+
return if conn.finished?
|
|
108
111
|
return if conn.pipeline_status == PG::PQ_PIPELINE_OFF || conn.status == PG::CONNECTION_BAD
|
|
109
112
|
|
|
110
113
|
conn.exit_pipeline_mode
|
|
@@ -116,32 +119,24 @@ module Pgbus
|
|
|
116
119
|
# fails (the server is gone) is logged and left there, so the error the
|
|
117
120
|
# caller is already raising is the one that surfaces; pgmq-ruby resets a
|
|
118
121
|
# bad connection at its next checkout.
|
|
119
|
-
# A reset reconnects with the same conninfo (the read bounds ride in it)
|
|
120
|
-
#
|
|
121
|
-
#
|
|
122
|
+
# A reset reconnects with the same conninfo (the read bounds ride in it);
|
|
123
|
+
# in :session GUC mode the connection's own reset applies the SETs again
|
|
124
|
+
# and closes it when they fail (SessionGucs, issue #671).
|
|
122
125
|
def discard_session(conn, reason)
|
|
123
126
|
Pgbus.logger.warn { "[Pgbus::Client] #{reason}, resetting the connection" }
|
|
124
|
-
|
|
125
|
-
conn.reset
|
|
126
|
-
rescue PG::Error => e
|
|
127
|
-
Pgbus.logger.warn { "[Pgbus::Client] Resetting the connection failed: #{e.message}" }
|
|
128
|
-
return
|
|
129
|
-
end
|
|
130
|
-
reapply_session_gucs(conn)
|
|
131
|
-
end
|
|
132
|
-
|
|
133
|
-
def reapply_session_gucs(conn)
|
|
134
|
-
apply_session_gucs(conn, @session_gucs) if @session_gucs
|
|
127
|
+
conn.reset
|
|
135
128
|
rescue PG::Error => e
|
|
136
129
|
Pgbus.logger.warn do
|
|
137
|
-
"[Pgbus::Client]
|
|
130
|
+
"[Pgbus::Client] Resetting the connection or re-applying its session variables failed: #{e.message}"
|
|
138
131
|
end
|
|
139
132
|
end
|
|
140
133
|
|
|
141
134
|
# The failed BEGIN block (INERROR) is still open after the sync. A failed
|
|
142
135
|
# COMMIT has already ended it (IDLE); a lost connection reports UNKNOWN
|
|
143
|
-
# and has nothing to roll back.
|
|
136
|
+
# and has nothing to roll back, as does one a reset closed.
|
|
144
137
|
def rollback_async_commit(conn)
|
|
138
|
+
return if conn.finished?
|
|
139
|
+
|
|
145
140
|
conn.exec("ROLLBACK") if [PG::PQTRANS_INERROR, PG::PQTRANS_INTRANS].include?(conn.transaction_status)
|
|
146
141
|
end
|
|
147
142
|
end
|
|
@@ -44,6 +44,22 @@ module Pgbus
|
|
|
44
44
|
end
|
|
45
45
|
end
|
|
46
46
|
|
|
47
|
+
# Fire-and-forget NOTIFY for a process signal (issue #674) on its channel,
|
|
48
|
+
# `<queue_prefix>_signal_<name>` (Pgbus::Signals validates the name and
|
|
49
|
+
# the payload: a String within the cap, or nil for none).
|
|
50
|
+
def notify_signal(name, payload = nil)
|
|
51
|
+
channel = config.queue_name("signal_#{name}")
|
|
52
|
+
Instrumentation.instrument("pgbus.signal.notify", signal: name.to_s, bytes: payload.to_s.bytesize) do
|
|
53
|
+
with_stale_connection_retry do
|
|
54
|
+
synchronized do
|
|
55
|
+
@pgmq.__send__(:with_connection) do |conn|
|
|
56
|
+
conn.exec_params("SELECT pg_notify($1, $2)", [channel, payload])
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
47
63
|
private
|
|
48
64
|
|
|
49
65
|
def validate_notify_payload_size!(stream_name, json)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
class Client
|
|
5
|
+
# The database.yml variables that connection_guc_mode :session applies with
|
|
6
|
+
# SET after connect (issue #332), on every session a pooled connection has.
|
|
7
|
+
#
|
|
8
|
+
# PG::Connection#reset opens a new backend from the same conninfo and does
|
|
9
|
+
# not replay the SETs. pgmq-ruby resets an unhealthy pooled connection at
|
|
10
|
+
# checkout (finished?, CONNECTION_BAD, and since 0.9.0 an intermediate
|
|
11
|
+
# state such as CONNECTION_STARTED), and AsyncCommit#discard_session resets
|
|
12
|
+
# one whose pipeline state cannot be trusted. So each connection #connect
|
|
13
|
+
# opens is extended with this module, whose #reset (and #async_reset,
|
|
14
|
+
# #sync_reset) applies the SETs again (issue #671).
|
|
15
|
+
#
|
|
16
|
+
# A connection whose SETs did not all complete is closed before the error
|
|
17
|
+
# propagates: it is never pooled CONNECTION_OK without them. The next
|
|
18
|
+
# checkout sees it finished? and resets it, which tries again (pg 1.5.9 and
|
|
19
|
+
# later reset a closed connection; an older pg raises, and the pool reload
|
|
20
|
+
# before the last stale-connection retry replaces it).
|
|
21
|
+
#
|
|
22
|
+
# One instance per pool, built at Client construction; it holds only the
|
|
23
|
+
# SET statements, in a frozen array nothing mutates, so concurrent
|
|
24
|
+
# connections share it safely.
|
|
25
|
+
class SessionGucs < Module
|
|
26
|
+
def initialize(variables)
|
|
27
|
+
super()
|
|
28
|
+
statements = variables.map { |name, value| "SET #{name} = '#{value}'" }.freeze
|
|
29
|
+
|
|
30
|
+
# Runs the block (a reset, or nothing after a connect), then the SETs.
|
|
31
|
+
# One ensure covers both, so an async raise between the reset and the
|
|
32
|
+
# first SET also closes the connection.
|
|
33
|
+
define_method(:pgbus_with_session_gucs) do |&before|
|
|
34
|
+
applied = false
|
|
35
|
+
before&.call
|
|
36
|
+
statements.each { |sql| exec(sql) }
|
|
37
|
+
applied = true
|
|
38
|
+
self
|
|
39
|
+
ensure
|
|
40
|
+
close unless applied || finished?
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
# pg's async_reset is an alias bound to PG::Connection#reset and its
|
|
44
|
+
# sync_reset is C, so a hook on reset alone would not see either. None
|
|
45
|
+
# of the three calls another, so each reset applies the SETs once.
|
|
46
|
+
%i[reset async_reset sync_reset].each do |name|
|
|
47
|
+
define_method(name) do
|
|
48
|
+
pgbus_with_session_gucs { super() }
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def connect(pg_opts)
|
|
54
|
+
PG.connect(pg_opts).extend(self).pgbus_with_session_gucs
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
data/lib/pgbus/client.rb
CHANGED
|
@@ -138,9 +138,6 @@ module Pgbus
|
|
|
138
138
|
# safe on this dedicated-connection branch — never on the shared-AR Proc
|
|
139
139
|
# path, where statement_timeout would leak into application queries.
|
|
140
140
|
conn_opts = apply_connection_bounds(conn_opts)
|
|
141
|
-
# What the connect lambda SETs per session (:session GUC mode), kept so
|
|
142
|
-
# a session reset after a failed completion pipeline gets it again.
|
|
143
|
-
@session_gucs = session_gucs(conn_opts)
|
|
144
141
|
conn_opts = wrap_session_gucs(conn_opts)
|
|
145
142
|
@pgmq = PGMQ::Client.new(conn_opts, pool_size: config.resolved_pool_size, pool_timeout: config.pool_timeout)
|
|
146
143
|
@pgmq_mutex = nil
|
|
@@ -2204,17 +2201,15 @@ module Pgbus
|
|
|
2204
2201
|
# PG::Connection each call (pgmq guards against a shared object). Applies to
|
|
2205
2202
|
# a Hash with `:variables` only — a String URL or no variables passes through
|
|
2206
2203
|
# unchanged, as does :options mode (where forward_connection_variables
|
|
2207
|
-
# already baked the GUCs into `options`). See issue #332.
|
|
2204
|
+
# already baked the GUCs into `options`). See issue #332. Each connection
|
|
2205
|
+
# re-applies the SETs when it is reset (issue #671, SessionGucs).
|
|
2208
2206
|
def wrap_session_gucs(conn_opts)
|
|
2209
2207
|
variables = session_gucs(conn_opts)
|
|
2210
2208
|
return conn_opts unless variables
|
|
2211
2209
|
|
|
2212
2210
|
pg_opts = conn_opts.except(:variables)
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
apply_session_gucs(conn, variables)
|
|
2216
|
-
conn
|
|
2217
|
-
end
|
|
2211
|
+
gucs = SessionGucs.new(variables)
|
|
2212
|
+
-> { gucs.connect(pg_opts) }
|
|
2218
2213
|
end
|
|
2219
2214
|
|
|
2220
2215
|
# The database.yml variables :session GUC mode applies with SET after
|
|
@@ -2226,10 +2221,6 @@ module Pgbus
|
|
|
2226
2221
|
variables unless variables.nil? || variables.empty?
|
|
2227
2222
|
end
|
|
2228
2223
|
|
|
2229
|
-
def apply_session_gucs(conn, variables)
|
|
2230
|
-
variables.each { |name, value| conn.exec("SET #{name} = '#{value}'") }
|
|
2231
|
-
end
|
|
2232
|
-
|
|
2233
2224
|
def apply_connection_bounds(conn_opts)
|
|
2234
2225
|
timeout = config.read_timeout
|
|
2235
2226
|
return conn_opts unless timeout&.positive?
|
|
@@ -27,14 +27,18 @@ module Pgbus
|
|
|
27
27
|
# probing starts after 5 idle seconds, every 2 s, 3 times, so a dead
|
|
28
28
|
# socket errors within ~11 s even between the listener's own keepalive
|
|
29
29
|
# queries; tcp_user_timeout bounds data the peer never acknowledges by
|
|
30
|
-
# the same 11 s.
|
|
31
|
-
#
|
|
30
|
+
# the same 11 s. connect_timeout bounds the connect itself (issue #674:
|
|
31
|
+
# a streamer starting for process signals, and a hub worker rebuilding
|
|
32
|
+
# its own listener, otherwise wait on an unreachable host as long as the
|
|
33
|
+
# OS lets the TCP handshake retry). Client-side keywords: never in the
|
|
34
|
+
# startup packet, so a pooler cannot reject them.
|
|
32
35
|
LISTEN_KEEPALIVES = {
|
|
33
36
|
keepalives: 1,
|
|
34
37
|
keepalives_idle: 5,
|
|
35
38
|
keepalives_interval: 2,
|
|
36
39
|
keepalives_count: 3,
|
|
37
|
-
tcp_user_timeout: 11_000
|
|
40
|
+
tcp_user_timeout: 11_000,
|
|
41
|
+
connect_timeout: 10
|
|
38
42
|
}.freeze
|
|
39
43
|
|
|
40
44
|
def connect(opts)
|
|
@@ -76,20 +80,29 @@ module Pgbus
|
|
|
76
80
|
defined?(::PG) && ::PG.respond_to?(:library_version) && ::PG.library_version >= 120_000
|
|
77
81
|
end
|
|
78
82
|
|
|
83
|
+
# LISTEN_KEEPALIVES, without connect_timeout when PGCONNECT_TIMEOUT is set:
|
|
84
|
+
# a conninfo keyword beats the environment, and the operator's value wins.
|
|
85
|
+
def listen_keywords
|
|
86
|
+
keywords = libpq_supports_socket_bounds? ? LISTEN_KEEPALIVES : LISTEN_KEEPALIVES.slice(:connect_timeout)
|
|
87
|
+
return keywords if ENV.fetch("PGCONNECT_TIMEOUT", nil).to_s.empty?
|
|
88
|
+
|
|
89
|
+
keywords.except(:connect_timeout)
|
|
90
|
+
end
|
|
91
|
+
|
|
79
92
|
# Fill in the LISTEN_KEEPALIVES keywords the options do not already set.
|
|
80
|
-
#
|
|
93
|
+
# Only connect_timeout on libpq < 12 (see libpq_supports_socket_bounds?;
|
|
94
|
+
# connect_timeout is older than that), and nothing for a
|
|
81
95
|
# connection that names a service (service=, or PGSERVICE): libpq applies
|
|
82
96
|
# the service file only to keywords the conninfo leaves unset, so an added
|
|
83
97
|
# keyword would override the service's own.
|
|
84
98
|
def with_keepalives(opts)
|
|
85
|
-
return opts unless libpq_supports_socket_bounds?
|
|
86
99
|
return opts if ENV.fetch("PGSERVICE", nil).to_s != ""
|
|
87
100
|
|
|
88
101
|
case opts
|
|
89
102
|
when Hash
|
|
90
103
|
return opts if opts.key?(:service) || opts.key?("service")
|
|
91
104
|
|
|
92
|
-
missing =
|
|
105
|
+
missing = listen_keywords.reject { |key, _| opts.key?(key) || opts.key?(key.to_s) }
|
|
93
106
|
opts.merge(missing)
|
|
94
107
|
when String then append_keepalives(opts)
|
|
95
108
|
else opts
|
|
@@ -105,7 +118,7 @@ module Pgbus
|
|
|
105
118
|
set = conninfo_keywords(conninfo)
|
|
106
119
|
return conninfo if set.nil? || set.include?("service")
|
|
107
120
|
|
|
108
|
-
missing =
|
|
121
|
+
missing = listen_keywords.reject { |key, _| set.include?(key.to_s) }
|
|
109
122
|
return conninfo if missing.empty?
|
|
110
123
|
|
|
111
124
|
if url?(conninfo)
|
data/lib/pgbus/engine.rb
CHANGED
|
@@ -160,6 +160,14 @@ module Pgbus
|
|
|
160
160
|
app.middleware.use Pgbus::Streams::WatermarkCacheMiddleware if Pgbus.configuration.streams_enabled
|
|
161
161
|
end
|
|
162
162
|
|
|
163
|
+
# Process signals (issue #674): start the streamer's LISTEN before a
|
|
164
|
+
# process's first request when a signal is registered. Installed whenever
|
|
165
|
+
# streams are enabled, since on_signal usually runs in an initializer after
|
|
166
|
+
# this one; with no subscriber it does nothing.
|
|
167
|
+
initializer "pgbus.signals.middleware" do |app|
|
|
168
|
+
app.middleware.use Pgbus::Signals::Middleware if Pgbus.configuration.streams_enabled
|
|
169
|
+
end
|
|
170
|
+
|
|
163
171
|
# Make the <pgbus-stream-source> element available to the host app's
|
|
164
172
|
# asset pipeline (Propshaft or Sprockets). The importmap pin points at
|
|
165
173
|
# the minified build (rake frontend:js). Propshaft rewrites its
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
# The caller's open ActiveRecord transaction, for work that must wait for
|
|
5
|
+
# its COMMIT: a durable stream broadcast (Streams::Stream) and a process
|
|
6
|
+
# signal (Signals). Guarded by defined? so both stay usable without Rails.
|
|
7
|
+
module OpenTransaction
|
|
8
|
+
# Runs nothing itself: hands the commit hook a block that runs after
|
|
9
|
+
# the commit (and never on rollback).
|
|
10
|
+
#
|
|
11
|
+
# Duck-typed as a record for Rails 7.1, whose transactions have no public
|
|
12
|
+
# after_commit: ActiveRecord calls committed! / rolledback! on every record
|
|
13
|
+
# added to a transaction. 7.2+ use Transaction#after_commit instead.
|
|
14
|
+
class CommitHook
|
|
15
|
+
def initialize(block)
|
|
16
|
+
@block = block
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def before_committed!; end
|
|
20
|
+
|
|
21
|
+
# should_run_callbacks is false for a duplicate of a record already in
|
|
22
|
+
# the transaction; a hook is only ever equal to itself.
|
|
23
|
+
def committed!(should_run_callbacks: true, **)
|
|
24
|
+
@block.call if should_run_callbacks
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def rolledback!(*, **); end
|
|
28
|
+
|
|
29
|
+
def trigger_transactional_callbacks?
|
|
30
|
+
true
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
# Returns the current AR transaction if one is open, nil otherwise.
|
|
37
|
+
# AR's NullTransaction yields immediately from after_commit, so we have to
|
|
38
|
+
# check #open? explicitly — otherwise every call path would hit the
|
|
39
|
+
# "deferred" branch and the caller would lose its return value.
|
|
40
|
+
#
|
|
41
|
+
# The probe must only inspect a connection the calling thread/fiber
|
|
42
|
+
# ALREADY leases — `connection_pool.active_connection?`, never
|
|
43
|
+
# `ActiveRecord::Base.connection`. On Rails 7.2+ `.connection` takes a
|
|
44
|
+
# sticky executor-scoped lease: on a non-executor thread (the
|
|
45
|
+
# Coalescer's flush thread, app worker threads) it is never released —
|
|
46
|
+
# one pool connection pinned per thread — and inside
|
|
47
|
+
# `with_connection` the sticky flag defeats the block-exit release, so
|
|
48
|
+
# the CALLER's connection leaks when its thread dies. Both variants
|
|
49
|
+
# exhausted an exactly-sized pool deterministically (Zazu fan-out
|
|
50
|
+
# incident, 2026-08-05). Semantics are unchanged: a transaction is
|
|
51
|
+
# per-lease, so a thread holding no connection can have no open
|
|
52
|
+
# transaction to defer on — the old code's fresh checkout always
|
|
53
|
+
# answered nil anyway, at the price of the leak.
|
|
54
|
+
def current
|
|
55
|
+
return nil unless defined?(::ActiveRecord::Base)
|
|
56
|
+
|
|
57
|
+
connection = ::ActiveRecord::Base.connection_pool.active_connection?
|
|
58
|
+
return nil unless connection
|
|
59
|
+
|
|
60
|
+
transaction = connection.current_transaction
|
|
61
|
+
transaction if transaction.open?
|
|
62
|
+
rescue StandardError => e
|
|
63
|
+
# Defensive: if AR is loaded but not yet connected (e.g. a
|
|
64
|
+
# Rake task invoked before Rails boot), don't let the transaction
|
|
65
|
+
# probe break the caller. Debug-logged so a misconfigured
|
|
66
|
+
# app can diagnose "why isn't my work deferring?" without impacting
|
|
67
|
+
# production performance (debug is off by default).
|
|
68
|
+
Pgbus.logger.debug do
|
|
69
|
+
"[Pgbus::OpenTransaction] transaction probe failed (#{e.class}: #{e.message}); " \
|
|
70
|
+
"falling back to running now"
|
|
71
|
+
end
|
|
72
|
+
nil
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Registers +block+ to run after the COMMIT of the caller's open,
|
|
76
|
+
# joinable transaction and returns that transaction; returns nil (and
|
|
77
|
+
# registers nothing) when there is none, so the caller runs the work now.
|
|
78
|
+
#
|
|
79
|
+
# A transaction that is not joinable is not deferred on: in an app's
|
|
80
|
+
# transactional tests that is the fixture transaction, which never
|
|
81
|
+
# commits, so a model's `after_commit { Pgbus.signal(...) }` would never
|
|
82
|
+
# send. Inside it, a `transaction do … end` block is joinable and its
|
|
83
|
+
# commit runs the callbacks, as a production commit does.
|
|
84
|
+
def defer(&block)
|
|
85
|
+
transaction = current
|
|
86
|
+
return nil unless transaction&.joinable?
|
|
87
|
+
|
|
88
|
+
if transaction.respond_to?(:after_commit)
|
|
89
|
+
transaction.after_commit(&block)
|
|
90
|
+
else
|
|
91
|
+
::ActiveRecord::Base.connection_pool.active_connection?.add_transaction_record(CommitHook.new(block))
|
|
92
|
+
end
|
|
93
|
+
transaction
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
end
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Pgbus
|
|
4
|
+
module Signals
|
|
5
|
+
# Starts this process's streamer, on a background thread, at its first
|
|
6
|
+
# request when a process signal is registered (issue #674), so a web
|
|
7
|
+
# process that never served an SSE connection still receives signals. The
|
|
8
|
+
# request does not wait for the LISTEN: what it (or anything before it)
|
|
9
|
+
# read before the LISTEN is covered by the on_gap the streamer runs once
|
|
10
|
+
# its first LISTEN is in place. After that it costs one atomic read.
|
|
11
|
+
# Installed by Pgbus::Engine when streams are enabled.
|
|
12
|
+
class Middleware
|
|
13
|
+
def initialize(app)
|
|
14
|
+
@app = app
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def call(env)
|
|
18
|
+
Pgbus::Signals.start_listening!
|
|
19
|
+
@app.call(env)
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|