pgbus 1.1.0 → 1.1.2
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 +28 -0
- data/README.md +5 -2
- data/app/models/pgbus/job_stat.rb +4 -2
- data/app/models/pgbus/stream_queue.rb +98 -29
- data/app/models/pgbus/stream_stat.rb +15 -8
- data/lib/pgbus/client/ensure_stream_queue.rb +30 -10
- data/lib/pgbus/client.rb +1 -0
- data/lib/pgbus/configuration.rb +18 -0
- data/lib/pgbus/event_bus/stale_connection_retry.rb +1 -1
- data/lib/pgbus/open_transaction.rb +12 -3
- data/lib/pgbus/streams/coalescer.rb +54 -7
- data/lib/pgbus/streams/presence.rb +10 -11
- data/lib/pgbus/streams.rb +25 -32
- data/lib/pgbus/testing.rb +19 -0
- data/lib/pgbus/version.rb +1 -1
- data/sig/pgbus/configuration.rbs +2 -0
- data/sig/pgbus/streams/stream.rbs +3 -2
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 3109373adbc7ceb54f0e8871de1b0790d71ca4ea5eafe485926a3e8423d974ef
|
|
4
|
+
data.tar.gz: ae9d61208c42c23204b59c92900f94cb43fefb0767407ec811aed2df3df61ff5
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 8e29e8cc716f5806743da8187c043da2fe11cf2f1aee88080af5110608661922b7c10369f3e2f51fdbb5a9f94fa35a5e21afe7afc20da0bb4e921be2205ba69d
|
|
7
|
+
data.tar.gz: f302a39d0843bd8d273c18aadc2af84262799fb7df25311d3e48e14cf5b602ddabc881d4354a50677f7f7728e59eb62cfdc650c8bfad673fa9ec0c1bb244b326
|
data/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,34 @@
|
|
|
8
8
|
|
|
9
9
|
### Security
|
|
10
10
|
|
|
11
|
+
## [1.1.2] - 2026-11-27
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- **Durable broadcasts in transactional tests are published** (#695). On Rails 7.2+, a durable `broadcast` (or `broadcast(..., coalesce:)`) made directly inside a `transaction(joinable: false)` block, which is what Rails' transactional tests open around each example, was deferred to a commit that never comes and silently dropped. It is now published at once, as `Pgbus.signal` is; a `transaction do ... end` block inside it publishes at its commit. A test that relied on such broadcasts never arriving now sees them.
|
|
16
|
+
- **`Pgbus::Streams::Presence.connection` is removed** (#695). It handed out the adapter's `PG::Connection` without the adapter's lock, so whatever ran on it could race another thread's presence statement on the same adapter. Presence's own statements lease through `connection_pool.with_connection` and hold the adapter's lock; run SQL of your own through your ActiveRecord connection.
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
|
|
20
|
+
- **Durable broadcasts wait for the commit through `OpenTransaction.defer`** (#695). `Stream#broadcast` and the coalesced submit called `Transaction#after_commit` directly, which Rails 7.1 transactions lack: a durable broadcast inside an open transaction raised `NoMethodError` there. Both now go through `Pgbus::OpenTransaction.defer`, which registers a commit hook on Rails 7.1 and skips a transaction that is not joinable. `pgbus.stream.broadcast` reports `deferred:` from it.
|
|
21
|
+
- **A stream's first broadcast inside a rolled-back transaction registers it again** (#695). The first durable broadcast of a stream records it in `pgbus_stream_queues`. Inside the caller's transaction that row rode the transaction, but the client memoized the stream as set up before the commit, so a rollback left the stream unregistered for the life of the process (maintenance then treated its queue as a job queue). The row also held its lock until the commit, so another thread's first broadcast of the same stream waited for it. Inside an open, joinable transaction `StreamQueue.record!` now writes nothing and returns `:pending`: the row is inserted after the commit (once per transaction and stream, never on a rollback), and the registry memo and the client's per-stream memo are set then, so the next broadcast after a rollback records it again. The archive index keeps its own memo, so it is not redone meanwhile. A transaction that is not joinable (the fixture transaction of transactional tests) is written into at once, as before. An unmigrated install is still memoized after one try. Index DDL that rides the caller's transaction on the shared ActiveRecord connection is not memoized, as `@queues_created` already was not.
|
|
22
|
+
- **Presence returns its ActiveRecord lease** (#695). The presence statements (everything routed through its `exec_params`) leased their adapter through a bare `connection`, a sticky lease on Rails 7.2+ that nothing returned on the streamer's threads (connection-driven presence and the seat heartbeat run there, outside any Rails executor). It now runs inside `connection_pool.with_connection`, holding the adapter's lock as before. `Pgbus/BareConnectionLease` covers `lib/pgbus/streams/**` and `lib/pgbus/open_transaction.rb`.
|
|
23
|
+
- **A coalesced frame lost to a failing scheduler is reported** (#695). When the scheduler raised for one submit while another thread submitted the same key, that other frame was dropped without a trace. It is now reported through `ErrorReporter` (`dropped: true`); the key is freed as before.
|
|
24
|
+
|
|
25
|
+
## [1.1.1] - 2026-11-27
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- **`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.
|
|
30
|
+
|
|
31
|
+
### Changed
|
|
32
|
+
|
|
33
|
+
- **`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.
|
|
34
|
+
|
|
35
|
+
### Fixed
|
|
36
|
+
|
|
37
|
+
- **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.
|
|
38
|
+
|
|
11
39
|
## [1.1.0] - 2026-11-24
|
|
12
40
|
|
|
13
41
|
### Added
|
data/README.md
CHANGED
|
@@ -1713,9 +1713,9 @@ end
|
|
|
1713
1713
|
# atomic with respect to each other.
|
|
1714
1714
|
```
|
|
1715
1715
|
|
|
1716
|
-
ActionCable can't do this because its broadcast path goes through Redis pub/sub, which has no concept of your application's transaction boundary. Pgbus
|
|
1716
|
+
ActionCable can't do this because its broadcast path goes through Redis pub/sub, which has no concept of your application's transaction boundary. Pgbus waits for the commit of the transaction the calling thread already has open, through ActiveRecord's own commit callbacks (`Transaction#after_commit` on Rails 7.2+, a transaction record on Rails 7.1) — no outbox table, no background worker, no extra storage. A durable `coalesce:` broadcast waits the same way before it is submitted; an ephemeral one is fire-and-forget and submits at once.
|
|
1717
1717
|
|
|
1718
|
-
Outside an open transaction, broadcasts are synchronous and return the assigned `msg_id` as before. Inside a transaction, they return `nil` (the id isn't known until commit time).
|
|
1718
|
+
Outside an open transaction, broadcasts are synchronous and return the assigned `msg_id` as before. Inside a transaction, they return `nil` (the id isn't known until commit time). The exception, as for `Pgbus.signal`, is a `transaction(joinable: false)` block: nothing waits for it, so the broadcast is published at once. That is the fixture transaction transactional tests open around each example, which never commits. A `transaction do ... end` block inside it is joinable and publishes when that block commits its savepoint, so a test sees the broadcast; the enclosing transaction can still roll back afterwards, as the fixture transaction always does.
|
|
1719
1719
|
|
|
1720
1720
|
### Replaying history on connect (`replay:`)
|
|
1721
1721
|
|
|
@@ -1895,6 +1895,8 @@ Superseded frames never hit the bus at all — no PGMQ insert, no NOTIFY, no fan
|
|
|
1895
1895
|
|
|
1896
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.
|
|
1897
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 joinable transaction open (the fixture transaction of transactional tests is not one) the flush runs before `broadcast` returns; a durable coalesced broadcast made inside an open, joinable 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
|
+
|
|
1898
1900
|
### Presence
|
|
1899
1901
|
|
|
1900
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:
|
|
@@ -2645,6 +2647,7 @@ Curated headline options for the README. The full operator reference (with types
|
|
|
2645
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) |
|
|
2646
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) |
|
|
2647
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). |
|
|
2648
2651
|
| `streams_stats_enabled` | `false` | Record stream broadcast/connect/disconnect stats (opt-in, can be high volume) |
|
|
2649
2652
|
| `streams_path` | `nil` | Custom URL path for the SSE endpoint (nil = auto-detected from engine mount) |
|
|
2650
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
|
|
@@ -39,13 +39,32 @@ module Pgbus
|
|
|
39
39
|
# load publishes its snapshot only if no such change happened while it ran.
|
|
40
40
|
@names_generation = 0
|
|
41
41
|
|
|
42
|
+
# Per open transaction, the names whose insert already waits for its
|
|
43
|
+
# commit (issue #695): every broadcast of a fresh stream inside it asks
|
|
44
|
+
# again, and one insert at the commit is enough. Keyed weakly by the
|
|
45
|
+
# transaction, so a committed or rolled-back one is forgotten with it.
|
|
46
|
+
@deferred_lock = Mutex.new
|
|
47
|
+
@deferred = ObjectSpace::WeakKeyMap.new
|
|
48
|
+
|
|
42
49
|
class << self
|
|
43
50
|
# Inserts the physical queue name. Idempotent and cheap to call on
|
|
44
51
|
# every broadcast; the caller (`ensure_stream_queue`) also memoizes
|
|
45
52
|
# per-process, so the DB write happens once per stream per process.
|
|
46
53
|
# Errors are swallowed — a registry hiccup must never abort a broadcast.
|
|
47
54
|
# Returns true on a successful write, false when the table is absent or
|
|
48
|
-
# the insert failed (so callers like `backfill!` can report accurately)
|
|
55
|
+
# the insert failed (so callers like `backfill!` can report accurately),
|
|
56
|
+
# and :pending when the caller has a joinable transaction open on this
|
|
57
|
+
# connection (issue #695). Then nothing is written yet: the insert runs
|
|
58
|
+
# after that transaction commits, and never on its rollback. A
|
|
59
|
+
# transaction that is not joinable (the fixture transaction of
|
|
60
|
+
# transactional tests, which never commits) is written into at once, as
|
|
61
|
+
# OpenTransaction.defer runs work at once there. Writing it inside the
|
|
62
|
+
# caller's transaction would let a rollback take the row back after the
|
|
63
|
+
# stream was taken for registered, and would hold the row's lock, so
|
|
64
|
+
# another thread recording the same stream waited for that commit. The
|
|
65
|
+
# optional block runs once the row is written (at once, or after that
|
|
66
|
+
# commit; never on a rollback or a failed write); `ensure_stream_queue`
|
|
67
|
+
# memoizes the stream in it.
|
|
49
68
|
#
|
|
50
69
|
# Deliberately raw SQL rather than `upsert(unique_by:)` (issue #401):
|
|
51
70
|
# Rails resolves `unique_by:` through the pool's schema cache, which
|
|
@@ -54,27 +73,26 @@ module Pgbus
|
|
|
54
73
|
# `table_exists?` guard above passes) poisons every subsequent record!
|
|
55
74
|
# in the process with "No unique index found". The unique index is owned
|
|
56
75
|
# by this gem's own migration, so there is nothing to resolve.
|
|
57
|
-
|
|
76
|
+
#
|
|
77
|
+
# The write runs inside `connection_pool.with_connection` (issue #694):
|
|
78
|
+
# the coalescer flushes on a Concurrent IO thread no Rails executor
|
|
79
|
+
# wraps, so a bare `connection` there was a lease nobody returned. A
|
|
80
|
+
# caller that already holds one (a request, a job, an open transaction)
|
|
81
|
+
# keeps its connection, and an open, joinable transaction on it gets the
|
|
82
|
+
# insert after its commit (above).
|
|
83
|
+
def record!(queue_name, &on_durable)
|
|
58
84
|
return false unless table_exists?
|
|
59
85
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
# fabricate a one-entry set and silently hide every other
|
|
70
|
-
# already-registered stream until the next reset_cache!. Leaving it
|
|
71
|
-
# nil lets the next all_names call do a real load, which already
|
|
72
|
-
# includes this row since the insert above has committed.
|
|
73
|
-
@names_lock.synchronize do
|
|
74
|
-
@names_generation += 1
|
|
75
|
-
@all_names = (@all_names | [queue_name]).freeze if @all_names
|
|
86
|
+
connection_pool.with_connection do |conn|
|
|
87
|
+
transaction = conn.current_transaction if conn.transaction_open?
|
|
88
|
+
if transaction&.joinable?
|
|
89
|
+
defer_insert(conn, transaction, queue_name, &on_durable)
|
|
90
|
+
next :pending
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
insert_row(conn, queue_name, &on_durable)
|
|
94
|
+
true
|
|
76
95
|
end
|
|
77
|
-
true
|
|
78
96
|
rescue ActiveRecord::ActiveRecordError => e
|
|
79
97
|
Pgbus.logger.debug { "[Pgbus] Failed to record stream queue #{queue_name}: #{e.message}" }
|
|
80
98
|
false
|
|
@@ -117,13 +135,16 @@ module Pgbus
|
|
|
117
135
|
# (`a_<queue>_msg_id_idx`). Job queues never get this index. Safe to call
|
|
118
136
|
# when pgmq is absent — returns an empty set rather than raising.
|
|
119
137
|
def fingerprint_matched_names
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
138
|
+
names = connection_pool.with_connection do |conn|
|
|
139
|
+
conn.select_values(<<~SQL.squish)
|
|
140
|
+
SELECT m.queue_name
|
|
141
|
+
FROM pgmq.meta m
|
|
142
|
+
INNER JOIN pg_indexes i
|
|
143
|
+
ON i.schemaname = 'pgmq'
|
|
144
|
+
AND i.indexname = 'a_' || m.queue_name || '_msg_id_idx'
|
|
145
|
+
SQL
|
|
146
|
+
end
|
|
147
|
+
Set.new(names)
|
|
127
148
|
rescue StandardError => e
|
|
128
149
|
Pgbus.logger.debug { "[Pgbus] Failed to discover stream queue fingerprints: #{e.message}" }
|
|
129
150
|
Set.new
|
|
@@ -139,7 +160,7 @@ module Pgbus
|
|
|
139
160
|
missing = fingerprint_matched_names - all_names
|
|
140
161
|
return 0 if missing.empty?
|
|
141
162
|
|
|
142
|
-
registered = missing.count { |name| record!(name) }
|
|
163
|
+
registered = missing.count { |name| record!(name) == true }
|
|
143
164
|
reset_cache! if registered.positive?
|
|
144
165
|
registered
|
|
145
166
|
end
|
|
@@ -167,7 +188,7 @@ module Pgbus
|
|
|
167
188
|
def table_exists?
|
|
168
189
|
return @table_exists if defined?(@table_exists) && @table_exists
|
|
169
190
|
|
|
170
|
-
@table_exists =
|
|
191
|
+
@table_exists = connection_pool.with_connection { |conn| conn.table_exists?(table_name) }
|
|
171
192
|
rescue StandardError => e
|
|
172
193
|
Pgbus.logger.debug { "[Pgbus] Failed to check stream queue table: #{e.message}" }
|
|
173
194
|
false
|
|
@@ -175,6 +196,53 @@ module Pgbus
|
|
|
175
196
|
|
|
176
197
|
private
|
|
177
198
|
|
|
199
|
+
def defer_insert(conn, transaction, queue_name, &on_durable)
|
|
200
|
+
first = @deferred_lock.synchronize do
|
|
201
|
+
names = (@deferred[transaction] ||= Set.new)
|
|
202
|
+
!names.add?(queue_name).nil?
|
|
203
|
+
end
|
|
204
|
+
OpenTransaction.after_commit(conn) { insert(queue_name, &on_durable) } if first
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# The deferred write, after the caller's commit. It runs inside the
|
|
208
|
+
# committing caller's callbacks, so it reports and never raises. Inside
|
|
209
|
+
# a transaction that is still open here (a block committed inside a
|
|
210
|
+
# non-joinable one, the fixture transaction of transactional tests) it
|
|
211
|
+
# writes there.
|
|
212
|
+
def insert(queue_name, &)
|
|
213
|
+
connection_pool.with_connection { |conn| insert_row(conn, queue_name, &) }
|
|
214
|
+
rescue ActiveRecord::ActiveRecordError => e
|
|
215
|
+
Pgbus.logger.debug { "[Pgbus] Failed to record stream queue #{queue_name}: #{e.message}" }
|
|
216
|
+
false
|
|
217
|
+
rescue StandardError => e
|
|
218
|
+
log_record_failure(queue_name, e)
|
|
219
|
+
false
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def insert_row(conn, queue_name, &)
|
|
223
|
+
conn.execute(
|
|
224
|
+
"INSERT INTO #{conn.quote_table_name(table_name)} (queue_name) " \
|
|
225
|
+
"VALUES (#{conn.quote(queue_name)}) ON CONFLICT (queue_name) DO NOTHING"
|
|
226
|
+
)
|
|
227
|
+
registered(queue_name, &)
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# The row is durable: keep the in-process cache consistent with it so a
|
|
231
|
+
# subsequent stream? check reflects this registration without a
|
|
232
|
+
# re-query. Only update an ALREADY-LOADED cache — if @all_names is still
|
|
233
|
+
# nil (this process hasn't queried the registry yet), seeding it here
|
|
234
|
+
# would fabricate a one-entry set and silently hide every other
|
|
235
|
+
# already-registered stream until the next reset_cache!. Leaving it nil
|
|
236
|
+
# lets the next all_names call do a real load, which already includes
|
|
237
|
+
# this row since it has committed. all_names loads outside the lock.
|
|
238
|
+
def registered(queue_name)
|
|
239
|
+
@names_lock.synchronize do
|
|
240
|
+
@names_generation += 1
|
|
241
|
+
@all_names = (@all_names | [queue_name]).freeze if @all_names
|
|
242
|
+
end
|
|
243
|
+
yield if block_given?
|
|
244
|
+
end
|
|
245
|
+
|
|
178
246
|
# A non-ActiveRecord error out of a plain INSERT is a bug signal (the
|
|
179
247
|
# old path's ArgumentError from index resolution was one), not a DB
|
|
180
248
|
# hiccup — surface it at WARN once per process instead of drowning a
|
|
@@ -190,7 +258,8 @@ module Pgbus
|
|
|
190
258
|
def load_names
|
|
191
259
|
return Set.new unless table_exists?
|
|
192
260
|
|
|
193
|
-
|
|
261
|
+
# pluck leases through `connection` on Rails 7.1 (issue #694).
|
|
262
|
+
Set.new(connection_pool.with_connection { all.pluck(:queue_name) })
|
|
194
263
|
rescue StandardError => e
|
|
195
264
|
Pgbus.logger.debug { "[Pgbus] Failed to load stream queues: #{e.message}" }
|
|
196
265
|
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
|
|
@@ -17,6 +17,11 @@ module Pgbus
|
|
|
17
17
|
#
|
|
18
18
|
# Called from `Pgbus.stream(name).broadcast(...)` on first publish per
|
|
19
19
|
# stream and from the streamer on first subscription per stream.
|
|
20
|
+
#
|
|
21
|
+
# Returns true once the setup is settled and memoized, false while part of
|
|
22
|
+
# it waits on the caller's open transaction (issue #695): the index DDL
|
|
23
|
+
# rode it on the shared ActiveRecord connection, or the registry row is
|
|
24
|
+
# written after its commit. A rollback leaves that part to the next call.
|
|
20
25
|
module EnsureStreamQueue
|
|
21
26
|
def ensure_stream_queue(stream_name)
|
|
22
27
|
full_name = config.queue_name(stream_name)
|
|
@@ -36,10 +41,20 @@ module Pgbus
|
|
|
36
41
|
# requires a roundtrip and a brief ACCESS SHARE lock on the archive
|
|
37
42
|
# table. Broadcast-per-after_commit loops can hit this 1000x/sec on
|
|
38
43
|
# the same stream, so memoize per-process after the first success.
|
|
39
|
-
# The StreamQueue registration
|
|
40
|
-
#
|
|
41
|
-
|
|
44
|
+
# The StreamQueue registration has its own memo (issue #695): its row
|
|
45
|
+
# waits for the caller's commit, so it is memoized only once written.
|
|
46
|
+
ensure_stream_archive_index(full_name, stream_name) unless @stream_indexes_created[stream_name]
|
|
47
|
+
register_stream_queue(full_name, stream_name) unless @streams_registered[stream_name]
|
|
48
|
+
@stream_indexes_created.key?(stream_name) && @streams_registered.fetch(stream_name, false)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
private
|
|
42
52
|
|
|
53
|
+
# Index DDL that rode the caller's transaction (the shared ActiveRecord
|
|
54
|
+
# connection) is not memoized: a rollback takes it back, the rule
|
|
55
|
+
# `@queues_created` follows.
|
|
56
|
+
def ensure_stream_archive_index(full_name, stream_name)
|
|
57
|
+
rides_caller_transaction = queue_ddl_rides_caller_transaction?
|
|
43
58
|
sanitized = QueueNameValidator.sanitize!(full_name)
|
|
44
59
|
sql = <<~SQL
|
|
45
60
|
CREATE INDEX IF NOT EXISTS a_#{sanitized}_msg_id_idx
|
|
@@ -61,15 +76,19 @@ module Pgbus
|
|
|
61
76
|
raise unless duplicate_relation_error?(e)
|
|
62
77
|
end
|
|
63
78
|
|
|
64
|
-
|
|
65
|
-
# orphan sweep, compact_archives) and wildcard workers can tell this
|
|
66
|
-
# queue apart from a job queue. No-ops on unmigrated installs.
|
|
67
|
-
Pgbus::StreamQueue.record!(full_name)
|
|
68
|
-
|
|
69
|
-
@stream_indexes_created[stream_name] = true
|
|
79
|
+
@stream_indexes_created[stream_name] = true unless rides_caller_transaction
|
|
70
80
|
end
|
|
71
81
|
|
|
72
|
-
|
|
82
|
+
# Record the physical queue name so maintenance (stream-archive prune,
|
|
83
|
+
# orphan sweep, compact_archives) and wildcard workers can tell this
|
|
84
|
+
# queue apart from a job queue. Memoized once the row is written: now,
|
|
85
|
+
# or after the caller's commit (never on its rollback, so the next
|
|
86
|
+
# broadcast records it again). An unmigrated install or a failed insert
|
|
87
|
+
# (false) is memoized too, so it is not retried on every broadcast.
|
|
88
|
+
def register_stream_queue(full_name, stream_name)
|
|
89
|
+
result = Pgbus::StreamQueue.record!(full_name) { @streams_registered[stream_name] = true }
|
|
90
|
+
@streams_registered[stream_name] = true if result == false
|
|
91
|
+
end
|
|
73
92
|
|
|
74
93
|
# Creates the bare stream queue + forces NOTIFY throttle 0. Retries once
|
|
75
94
|
# when a process-local `@queues_created` memo is stale relative to the
|
|
@@ -110,6 +129,7 @@ module Pgbus
|
|
|
110
129
|
def forget_stream_queue_memo!(full_name, stream_name)
|
|
111
130
|
@queues_created.delete(full_name)
|
|
112
131
|
@stream_indexes_created.delete(stream_name)
|
|
132
|
+
@streams_registered.delete(stream_name)
|
|
113
133
|
end
|
|
114
134
|
|
|
115
135
|
def missing_pgmq_queue_error?(error)
|
data/lib/pgbus/client.rb
CHANGED
|
@@ -179,6 +179,7 @@ module Pgbus
|
|
|
179
179
|
|
|
180
180
|
@queues_created = Concurrent::Map.new
|
|
181
181
|
@stream_indexes_created = Concurrent::Map.new
|
|
182
|
+
@streams_registered = Concurrent::Map.new
|
|
182
183
|
# Per physical queue: its native statements, or false (issue #605).
|
|
183
184
|
@native_statements = Concurrent::Map.new
|
|
184
185
|
@native_unprepared = config.native_statements && ar_disables_prepared_statements?
|
data/lib/pgbus/configuration.rb
CHANGED
|
@@ -363,6 +363,16 @@ module Pgbus
|
|
|
363
363
|
:streams_pool_autoscale_interval, :streams_application_name
|
|
364
364
|
attr_reader :streams_default_broadcast_mode # rubocop:disable Style/AccessorGrouping
|
|
365
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
|
+
|
|
366
376
|
# NOTIFY-gated worker wakeups. When true, workers are woken by a
|
|
367
377
|
# NotifyListener PG connection that LISTENs on their queues' INSERT
|
|
368
378
|
# channels instead of blind-polling. Defaults to the value of
|
|
@@ -693,6 +703,7 @@ module Pgbus
|
|
|
693
703
|
# usually want job stats on and stream stats off, or vice versa.
|
|
694
704
|
@streams_stats_enabled = false
|
|
695
705
|
@streams_test_mode = false
|
|
706
|
+
@streams_coalesce_scheduler = nil
|
|
696
707
|
@streams_default_broadcast_mode = :ephemeral
|
|
697
708
|
@streams_orphan_sweep_interval = 3600 # 1 hour
|
|
698
709
|
@streams_orphan_threshold = 86_400 # 24 hours
|
|
@@ -1416,6 +1427,13 @@ module Pgbus
|
|
|
1416
1427
|
validate_presence_settings!
|
|
1417
1428
|
validate_stream_authorization!
|
|
1418
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
|
+
|
|
1419
1437
|
return if streams_orphan_threshold.nil?
|
|
1420
1438
|
return if streams_orphan_threshold.is_a?(Numeric) && streams_orphan_threshold.positive?
|
|
1421
1439
|
|
|
@@ -67,7 +67,7 @@ module Pgbus
|
|
|
67
67
|
# `clear_all_connections!` would yank sockets out from under sibling
|
|
68
68
|
# consumers sharing the process, turning one recoverable drop into many.
|
|
69
69
|
# `active_connection?` returns the lease or nil, and is the accessor this
|
|
70
|
-
# gem uses everywhere (
|
|
70
|
+
# gem uses everywhere (Pgbus::OpenTransaction.current documents why we
|
|
71
71
|
# never reach for `ActiveRecord::Base.connection`). Its `active_connection`
|
|
72
72
|
# alias is `:nodoc:` and does not exist at all before Rails 7.2 — below
|
|
73
73
|
# our floor, so calling it would raise NoMethodError on the one path that
|
|
@@ -81,16 +81,25 @@ module Pgbus
|
|
|
81
81
|
# commits, so a model's `after_commit { Pgbus.signal(...) }` would never
|
|
82
82
|
# send. Inside it, a `transaction do … end` block is joinable and its
|
|
83
83
|
# commit runs the callbacks, as a production commit does.
|
|
84
|
-
def defer(&
|
|
84
|
+
def defer(&)
|
|
85
85
|
transaction = current
|
|
86
86
|
return nil unless transaction&.joinable?
|
|
87
87
|
|
|
88
|
+
after_commit(::ActiveRecord::Base.connection_pool.active_connection?, &)
|
|
89
|
+
transaction
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Runs +block+ after the COMMIT of +connection+'s current transaction
|
|
93
|
+
# (never on its rollback), for work that already rode that transaction
|
|
94
|
+
# and must not be taken for done before it commits (the stream registry
|
|
95
|
+
# row, issue #695). The caller checked that a transaction is open.
|
|
96
|
+
def after_commit(connection, &block)
|
|
97
|
+
transaction = connection.current_transaction
|
|
88
98
|
if transaction.respond_to?(:after_commit)
|
|
89
99
|
transaction.after_commit(&block)
|
|
90
100
|
else
|
|
91
|
-
|
|
101
|
+
connection.add_transaction_record(CommitHook.new(block))
|
|
92
102
|
end
|
|
93
|
-
transaction
|
|
94
103
|
end
|
|
95
104
|
end
|
|
96
105
|
end
|
|
@@ -34,12 +34,13 @@ module Pgbus
|
|
|
34
34
|
Entry = Struct.new(:payload, :opts)
|
|
35
35
|
|
|
36
36
|
# scheduler: responds to `schedule(delay_seconds) { ... }`. Defaults
|
|
37
|
-
# to a
|
|
37
|
+
# to `config.streams_coalesce_scheduler`, read when a window's flush
|
|
38
|
+
# is scheduled, else a Concurrent::ScheduledTask-backed timer.
|
|
38
39
|
# flush: ->(stream_name:, target:, payload:, opts:) called once per
|
|
39
40
|
# window per key with the latest buffered frame.
|
|
40
41
|
def initialize(flush:, scheduler: nil)
|
|
41
42
|
@flush = flush
|
|
42
|
-
@scheduler = scheduler ||
|
|
43
|
+
@scheduler = scheduler || ConfiguredScheduler.new
|
|
43
44
|
@mutex = Mutex.new
|
|
44
45
|
@buffer = {} # key => Entry (latest)
|
|
45
46
|
@pending = {} # key => true while a flush is scheduled
|
|
@@ -52,19 +53,42 @@ module Pgbus
|
|
|
52
53
|
key = [stream_name, target]
|
|
53
54
|
schedule = false
|
|
54
55
|
|
|
56
|
+
entry = Entry.new(payload, opts)
|
|
55
57
|
@mutex.synchronize do
|
|
56
|
-
@buffer[key] =
|
|
58
|
+
@buffer[key] = entry
|
|
57
59
|
unless @pending[key]
|
|
58
60
|
@pending[key] = true
|
|
59
61
|
schedule = true
|
|
60
62
|
end
|
|
61
63
|
end
|
|
62
64
|
|
|
63
|
-
|
|
65
|
+
return unless schedule
|
|
66
|
+
|
|
67
|
+
begin
|
|
68
|
+
@scheduler.schedule(window_ms / 1000.0) { flush_key(key, stream_name, target) }
|
|
69
|
+
rescue StandardError => e
|
|
70
|
+
unschedule(key, entry, e, stream_name, target)
|
|
71
|
+
raise
|
|
72
|
+
end
|
|
64
73
|
end
|
|
65
74
|
|
|
66
75
|
private
|
|
67
76
|
|
|
77
|
+
# Nothing will flush this window: free the key, or no later submit would
|
|
78
|
+
# schedule it again. A frame another submit buffered meanwhile found the
|
|
79
|
+
# key pending and returned normally; this caller gets the error, that
|
|
80
|
+
# one would lose its frame without a trace, so it is reported.
|
|
81
|
+
def unschedule(key, entry, error, stream_name, target)
|
|
82
|
+
dropped = @mutex.synchronize do
|
|
83
|
+
@pending.delete(key)
|
|
84
|
+
waiting = @buffer.delete(key)
|
|
85
|
+
waiting && !waiting.equal?(entry)
|
|
86
|
+
end
|
|
87
|
+
return unless dropped
|
|
88
|
+
|
|
89
|
+
ErrorReporter.report(error, { component: "streams.coalescer", stream: stream_name, target: target, dropped: true })
|
|
90
|
+
end
|
|
91
|
+
|
|
68
92
|
def flush_key(key, stream_name, target)
|
|
69
93
|
entry = @mutex.synchronize do
|
|
70
94
|
@pending.delete(key)
|
|
@@ -81,14 +105,37 @@ module Pgbus
|
|
|
81
105
|
ErrorReporter.report(e, { component: "streams.coalescer", stream: stream_name, target: target })
|
|
82
106
|
end
|
|
83
107
|
|
|
84
|
-
#
|
|
85
|
-
# tiny adapter so the Coalescer can be unit-tested with a
|
|
86
|
-
# fake scheduler (no real timers, no sleeps).
|
|
108
|
+
# The timer: a Concurrent::ScheduledTask on the global IO executor.
|
|
109
|
+
# Kept as a tiny adapter so the Coalescer can be unit-tested with a
|
|
110
|
+
# synchronous fake scheduler (no real timers, no sleeps).
|
|
87
111
|
class ScheduledTaskScheduler
|
|
88
112
|
def schedule(delay_seconds, &)
|
|
89
113
|
Concurrent::ScheduledTask.execute(delay_seconds, &)
|
|
90
114
|
end
|
|
91
115
|
end
|
|
116
|
+
|
|
117
|
+
# Runs the flush at once, on the thread that submitted it (issue #694).
|
|
118
|
+
# For tests: the flush then writes on that thread's own connection, with
|
|
119
|
+
# no IO thread sharing a pinned connection across the test boundary.
|
|
120
|
+
# Pgbus::Testing.fake! / inline! select it. It removes the coalescing
|
|
121
|
+
# itself: every submit is broadcast.
|
|
122
|
+
class InlineScheduler
|
|
123
|
+
def schedule(_delay_seconds) = yield
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# The default: `config.streams_coalesce_scheduler`, read when a window's
|
|
127
|
+
# flush is scheduled (its first submit) so a scheduler set after boot (an
|
|
128
|
+
# initializer, a test mode) takes effect on the process-wide coalescer,
|
|
129
|
+
# else the timer.
|
|
130
|
+
class ConfiguredScheduler
|
|
131
|
+
def initialize
|
|
132
|
+
@timer = ScheduledTaskScheduler.new
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def schedule(delay_seconds, &)
|
|
136
|
+
(Pgbus.configuration.streams_coalesce_scheduler || @timer).schedule(delay_seconds, &)
|
|
137
|
+
end
|
|
138
|
+
end
|
|
92
139
|
end
|
|
93
140
|
end
|
|
94
141
|
end
|
|
@@ -185,12 +185,6 @@ module Pgbus
|
|
|
185
185
|
end
|
|
186
186
|
end
|
|
187
187
|
|
|
188
|
-
# The PG::Connection under the adapter. Run SQL through exec_params,
|
|
189
|
-
# not on this: the adapter's lock is released once it is returned.
|
|
190
|
-
def connection
|
|
191
|
-
adapter.raw_connection
|
|
192
|
-
end
|
|
193
|
-
|
|
194
188
|
# Runs one statement on the adapter's PG::Connection while holding
|
|
195
189
|
# the adapter's lock (issue #566). raw_connection takes that lock
|
|
196
190
|
# only to hand the connection out; on a pinned pool (transactional
|
|
@@ -198,10 +192,15 @@ module Pgbus
|
|
|
198
192
|
# that keeps a second thread's statement off the libpq connection
|
|
199
193
|
# while this one is in flight. Unpinned, the lock is a NullLock. The
|
|
200
194
|
# lock is reentrant, so a thread already holding it (a request
|
|
201
|
-
# inside a transaction) re-enters it.
|
|
195
|
+
# inside a transaction) re-enters it. The adapter is leased through
|
|
196
|
+
# connection_pool.with_connection (issue #695): presence also runs on
|
|
197
|
+
# the streamer's threads, which no Rails executor wraps, and a bare
|
|
198
|
+
# `connection` there was a lease nobody returned. A caller's own
|
|
199
|
+
# lease (a request, an open transaction) is reused.
|
|
202
200
|
def exec_params(sql, binds)
|
|
203
|
-
|
|
204
|
-
|
|
201
|
+
with_adapter do |adapter|
|
|
202
|
+
adapter.lock.synchronize { adapter.raw_connection.exec_params(sql, binds) }
|
|
203
|
+
end
|
|
205
204
|
end
|
|
206
205
|
|
|
207
206
|
# Reports a seat join/leave to streams_presence_on_change (issue #515).
|
|
@@ -229,13 +228,13 @@ module Pgbus
|
|
|
229
228
|
# the default path uses ActiveRecord::Base. Matches the
|
|
230
229
|
# canonical pattern in Pgbus::Process::QueueLock#connection
|
|
231
230
|
# and Pgbus::Configuration's connection probe.
|
|
232
|
-
def
|
|
231
|
+
def with_adapter(&)
|
|
233
232
|
unless defined?(::ActiveRecord::Base)
|
|
234
233
|
raise Pgbus::ConfigurationError,
|
|
235
234
|
"Pgbus::Streams::Presence requires ActiveRecord (no AR connection available)"
|
|
236
235
|
end
|
|
237
236
|
|
|
238
|
-
record_base.
|
|
237
|
+
record_base.connection_pool.with_connection(&)
|
|
239
238
|
end
|
|
240
239
|
|
|
241
240
|
def record_base
|
data/lib/pgbus/streams.rb
CHANGED
|
@@ -105,15 +105,16 @@ module Pgbus
|
|
|
105
105
|
# Callers pass a plain HTML string; the wrapping is an implementation
|
|
106
106
|
# detail.
|
|
107
107
|
#
|
|
108
|
-
# Transactional semantics: if this call is made inside an open
|
|
109
|
-
# ActiveRecord transaction, the PGMQ insert is deferred to
|
|
110
|
-
#
|
|
111
|
-
#
|
|
108
|
+
# Transactional semantics: if this call is made inside an open, joinable
|
|
109
|
+
# ActiveRecord transaction, the PGMQ insert is deferred to its COMMIT
|
|
110
|
+
# (OpenTransaction.defer; a transaction that is not joinable, such as
|
|
111
|
+
# the fixture transaction of transactional tests, publishes at once).
|
|
112
|
+
# If the transaction rolls back, the broadcast silently drops — clients never see the change that the database
|
|
112
113
|
# never persisted. This is the feature no other Rails real-time stack
|
|
113
114
|
# (including turbo-rails over ActionCable) can offer: the broadcast
|
|
114
115
|
# and the data mutation are atomic with respect to each other.
|
|
115
116
|
# Returns the assigned msg_id when sent synchronously, nil when
|
|
116
|
-
# deferred (the id isn't known until the
|
|
117
|
+
# deferred (the id isn't known until the commit runs it).
|
|
117
118
|
#
|
|
118
119
|
# Audience filtering: pass `visible_to:` with a filter label (a
|
|
119
120
|
# Symbol previously registered via Pgbus::Streams.filters.register)
|
|
@@ -171,20 +172,21 @@ module Pgbus
|
|
|
171
172
|
return broadcast_ephemeral(wrapped) unless use_durable
|
|
172
173
|
|
|
173
174
|
ensure_queue!
|
|
174
|
-
|
|
175
|
+
send_now = -> { @client.send_stream_message(@name, wrapped) }
|
|
176
|
+
# The COMMIT of the caller's open, joinable transaction, as
|
|
177
|
+
# Pgbus.signal waits for it (issue #695): OpenTransaction.defer skips a
|
|
178
|
+
# transaction that is not joinable (the fixture transaction of an
|
|
179
|
+
# app's transactional tests, which never commits) and registers a
|
|
180
|
+
# commit hook on Rails 7.1, whose transactions have no after_commit.
|
|
181
|
+
deferred_to = OpenTransaction.defer(&send_now)
|
|
175
182
|
instrument_payload = {
|
|
176
183
|
stream: @name,
|
|
177
184
|
visible_to: visible_to,
|
|
178
|
-
deferred: !
|
|
185
|
+
deferred: !deferred_to.nil?,
|
|
179
186
|
bytes: wrapped["html"].bytesize
|
|
180
187
|
}
|
|
181
188
|
Instrumentation.instrument("pgbus.stream.broadcast", instrument_payload) do
|
|
182
|
-
|
|
183
|
-
transaction.after_commit { @client.send_stream_message(@name, wrapped) }
|
|
184
|
-
nil
|
|
185
|
-
else
|
|
186
|
-
@client.send_stream_message(@name, wrapped)
|
|
187
|
-
end
|
|
189
|
+
deferred_to ? nil : send_now.call
|
|
188
190
|
end
|
|
189
191
|
end
|
|
190
192
|
|
|
@@ -204,8 +206,8 @@ module Pgbus
|
|
|
204
206
|
# `action` defaults to :replace. `target` is required. `exclude:`,
|
|
205
207
|
# `visible_to:`, and `durable:` are forwarded to #broadcast unchanged,
|
|
206
208
|
# so actor-echo suppression and audience filtering compose. Returns
|
|
207
|
-
# whatever #broadcast returns (msg_id, or nil when deferred to
|
|
208
|
-
#
|
|
209
|
+
# whatever #broadcast returns (msg_id, or nil when deferred to the
|
|
210
|
+
# commit of the caller's open, joinable transaction).
|
|
209
211
|
#
|
|
210
212
|
# See Pgbus::Streams::Renderer for the renderable-resolution order.
|
|
211
213
|
# Components that need URL helpers or a full view context should be
|
|
@@ -356,15 +358,11 @@ module Pgbus
|
|
|
356
358
|
end
|
|
357
359
|
|
|
358
360
|
# Transaction gating: a coalesced DURABLE broadcast made inside an
|
|
359
|
-
# open transaction must not flush if the transaction rolls
|
|
360
|
-
#
|
|
361
|
-
#
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
transaction.after_commit { submit.call }
|
|
365
|
-
else
|
|
366
|
-
submit.call
|
|
367
|
-
end
|
|
361
|
+
# open, joinable transaction must not flush if the transaction rolls
|
|
362
|
+
# back, so the submission waits for its COMMIT through
|
|
363
|
+
# OpenTransaction.defer, like the non-coalesced path (issue #695).
|
|
364
|
+
# Ephemeral coalescing is fire-and-forget, so it submits now.
|
|
365
|
+
submit.call unless resolved_durable && OpenTransaction.defer(&submit)
|
|
368
366
|
nil
|
|
369
367
|
end
|
|
370
368
|
|
|
@@ -386,16 +384,11 @@ module Pgbus
|
|
|
386
384
|
@ensure_mutex.synchronize do
|
|
387
385
|
return if @ensured
|
|
388
386
|
|
|
389
|
-
|
|
390
|
-
|
|
387
|
+
# false: the setup rode the caller's open transaction and could
|
|
388
|
+
# still roll back (issue #695), so the next broadcast ensures again.
|
|
389
|
+
@ensured = @client.ensure_stream_queue(@name) != false
|
|
391
390
|
end
|
|
392
391
|
end
|
|
393
|
-
|
|
394
|
-
# The caller's open AR transaction, or nil (Pgbus::OpenTransaction.current
|
|
395
|
-
# explains the lease-safe probe).
|
|
396
|
-
def current_open_transaction
|
|
397
|
-
OpenTransaction.current
|
|
398
|
-
end
|
|
399
392
|
end
|
|
400
393
|
end
|
|
401
394
|
end
|
data/lib/pgbus/testing.rb
CHANGED
|
@@ -92,6 +92,9 @@ module Pgbus
|
|
|
92
92
|
@mode_lock = Mutex.new
|
|
93
93
|
@default_mode = nil
|
|
94
94
|
|
|
95
|
+
# The scheduler fake/inline select for the coalescer (issue #694).
|
|
96
|
+
INLINE_COALESCE_SCHEDULER = Pgbus::Streams::Coalescer::InlineScheduler.new.freeze
|
|
97
|
+
|
|
95
98
|
class << self
|
|
96
99
|
def mode!(mode, &block)
|
|
97
100
|
raise ArgumentError, "Unknown mode: #{mode}. Valid modes: #{MODES.join(", ")}" unless MODES.include?(mode)
|
|
@@ -169,6 +172,7 @@ module Pgbus
|
|
|
169
172
|
def sync_streams_test_mode!(mode)
|
|
170
173
|
return unless defined?(Pgbus.configuration)
|
|
171
174
|
|
|
175
|
+
sync_coalesce_scheduler!(mode)
|
|
172
176
|
if mode == :disabled
|
|
173
177
|
Pgbus.configuration.streams_test_mode = false
|
|
174
178
|
reset_streamer!
|
|
@@ -177,6 +181,21 @@ module Pgbus
|
|
|
177
181
|
end
|
|
178
182
|
end
|
|
179
183
|
|
|
184
|
+
# Fake/inline flush coalesced broadcasts on the calling thread (issue
|
|
185
|
+
# #694): the coalescer's timer runs them on a Concurrent IO thread,
|
|
186
|
+
# which could take the test's pinned connection and keep it past the
|
|
187
|
+
# test. Only Testing's own inline scheduler is swapped in and out, so a
|
|
188
|
+
# scheduler the application configured stays as it is.
|
|
189
|
+
def sync_coalesce_scheduler!(mode)
|
|
190
|
+
config = Pgbus.configuration
|
|
191
|
+
current = config.streams_coalesce_scheduler
|
|
192
|
+
if mode == :disabled
|
|
193
|
+
config.streams_coalesce_scheduler = nil if current.equal?(INLINE_COALESCE_SCHEDULER)
|
|
194
|
+
elsif current.nil?
|
|
195
|
+
config.streams_coalesce_scheduler = INLINE_COALESCE_SCHEDULER
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
|
|
180
199
|
# A live streamer at this point is legitimate inside a
|
|
181
200
|
# `disabled! do ... end` real-stream test, so a clean teardown only
|
|
182
201
|
# warns. Threads that outlived shutdown! are a different matter: left
|
data/lib/pgbus/version.rb
CHANGED
data/sig/pgbus/configuration.rbs
CHANGED
|
@@ -218,6 +218,8 @@ module Pgbus
|
|
|
218
218
|
def streams_authorize=: (untyped) -> untyped
|
|
219
219
|
def streams_broadcast_queue: () -> untyped
|
|
220
220
|
def streams_broadcast_queue=: (untyped) -> untyped
|
|
221
|
+
def streams_coalesce_scheduler: () -> untyped
|
|
222
|
+
def streams_coalesce_scheduler=: (untyped) -> untyped
|
|
221
223
|
def streams_connection_options: () -> untyped
|
|
222
224
|
def streams_database_url: () -> untyped
|
|
223
225
|
def streams_database_url=: (untyped) -> untyped
|
|
@@ -10,8 +10,9 @@ module Pgbus
|
|
|
10
10
|
def name: () -> String
|
|
11
11
|
def durable?: () -> bool
|
|
12
12
|
|
|
13
|
-
# The msg_id
|
|
14
|
-
#
|
|
13
|
+
# The msg_id of a durable publish sent at once; nil for an ephemeral
|
|
14
|
+
# NOTIFY, a durable publish deferred to the commit of the caller's open,
|
|
15
|
+
# joinable transaction, or a coalesced broadcast.
|
|
15
16
|
def broadcast: (String payload, ?visible_to: Symbol?, ?durable: bool?, ?exclude: String?, ?event: String?,
|
|
16
17
|
?coalesce: (bool | Numeric)?, ?target: String?) -> Integer?
|
|
17
18
|
def broadcast_render: (target: String, ?action: Symbol, ?renderable: untyped, ?visible_to: Symbol?, ?durable: bool?,
|