pgbus 1.1.1 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 5b361fe772144c29017651d5a839827f23ef6f259c7607970e1ee10a052693e6
4
- data.tar.gz: 9d2b5cfe211b22334441641451d7db4d10618cb0e141edf5f9afaeb4dfc0e0c7
3
+ metadata.gz: 3109373adbc7ceb54f0e8871de1b0790d71ca4ea5eafe485926a3e8423d974ef
4
+ data.tar.gz: ae9d61208c42c23204b59c92900f94cb43fefb0767407ec811aed2df3df61ff5
5
5
  SHA512:
6
- metadata.gz: 5c5c64b410aaa7f4b1972e4fa6b982162ffdee46c51d7e92ef590729664f5b9ee2d13348fe2de2bd0ae5ce1b6c6fe634017d56808e1de7a8026fbf7609840d97
7
- data.tar.gz: b370b3fdd08557d9eabfa1a05219f5ffd0ad73fa7a08ef22a5171e04bcd48c56b42bd081f3caf7a49b75efeaa43d3e9d04c800cd1c2dfa9cc86c0cf639c7159e
6
+ metadata.gz: 8e29e8cc716f5806743da8187c043da2fe11cf2f1aee88080af5110608661922b7c10369f3e2f51fdbb5a9f94fa35a5e21afe7afc20da0bb4e921be2205ba69d
7
+ data.tar.gz: f302a39d0843bd8d273c18aadc2af84262799fb7df25311d3e48e14cf5b602ddabc881d4354a50677f7f7728e59eb62cfdc650c8bfad673fa9ec0c1bb244b326
data/CHANGELOG.md CHANGED
@@ -8,6 +8,20 @@
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
+
11
25
  ## [1.1.1] - 2026-11-27
12
26
 
13
27
  ### 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 detects the open AR transaction via `ActiveRecord::Base.connection.current_transaction.after_commit`, which is a first-class Rails API — no outbox table, no background worker, no extra storage.
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,7 +1895,7 @@ 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 transaction open the flush runs before `broadcast` returns; a durable coalesced broadcast made inside an open transaction is submitted at its commit, as outside the test modes, and flushes then. `disabled!` restores the timer. `config.streams_coalesce_scheduler` takes any object with `schedule(delay_seconds) { ... }`, such as `Pgbus::Streams::Coalescer::InlineScheduler.new`, read when a window's flush is scheduled; `nil` (the default) is the timer. A scheduler you set yourself is left alone by the test modes, so its own threading applies in tests too.
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
1899
 
1900
1900
  ### Presence
1901
1901
 
@@ -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
@@ -58,31 +77,22 @@ module Pgbus
58
77
  # The write runs inside `connection_pool.with_connection` (issue #694):
59
78
  # the coalescer flushes on a Concurrent IO thread no Rails executor
60
79
  # wraps, so a bare `connection` there was a lease nobody returned. A
61
- # caller that already holds one (a request, a job, an open
62
- # transaction) keeps writing on it.
63
- def record!(queue_name)
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)
64
84
  return false unless table_exists?
65
85
 
66
86
  connection_pool.with_connection do |conn|
67
- conn.execute(
68
- "INSERT INTO #{conn.quote_table_name(table_name)} (queue_name) " \
69
- "VALUES (#{conn.quote(queue_name)}) ON CONFLICT (queue_name) DO NOTHING"
70
- )
71
- # Keep the in-process cache consistent with the write so a subsequent
72
- # stream? check reflects this registration without a re-query. Only
73
- # update an ALREADY-LOADED cache — if @all_names is still nil (this
74
- # process hasn't queried the registry yet), seeding it here would
75
- # fabricate a one-entry set and silently hide every other
76
- # already-registered stream until the next reset_cache!. Leaving it
77
- # nil lets the next all_names call do a real load, which already
78
- # includes this row since the insert above has committed. Taken
79
- # while the connection is held; all_names loads outside the lock.
80
- @names_lock.synchronize do
81
- @names_generation += 1
82
- @all_names = (@all_names | [queue_name]).freeze if @all_names
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
83
91
  end
92
+
93
+ insert_row(conn, queue_name, &on_durable)
94
+ true
84
95
  end
85
- true
86
96
  rescue ActiveRecord::ActiveRecordError => e
87
97
  Pgbus.logger.debug { "[Pgbus] Failed to record stream queue #{queue_name}: #{e.message}" }
88
98
  false
@@ -150,7 +160,7 @@ module Pgbus
150
160
  missing = fingerprint_matched_names - all_names
151
161
  return 0 if missing.empty?
152
162
 
153
- registered = missing.count { |name| record!(name) }
163
+ registered = missing.count { |name| record!(name) == true }
154
164
  reset_cache! if registered.positive?
155
165
  registered
156
166
  end
@@ -186,6 +196,53 @@ module Pgbus
186
196
 
187
197
  private
188
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
+
189
246
  # A non-ActiveRecord error out of a plain INSERT is a bug signal (the
190
247
  # old path's ArgumentError from index resolution was one), not a DB
191
248
  # hiccup — surface it at WARN once per process instead of drowning a
@@ -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 shares this memo — both are one-time
40
- # per stream per process and must both survive a first-broadcast.
41
- return if @stream_indexes_created[stream_name]
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
- # Record the physical queue name so maintenance (stream-archive prune,
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
- private
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?
@@ -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 (Streams#current_open_transaction documents why we
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(&block)
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
- ::ActiveRecord::Base.connection_pool.active_connection?.add_transaction_record(CommitHook.new(block))
101
+ connection.add_transaction_record(CommitHook.new(block))
92
102
  end
93
- transaction
94
103
  end
95
104
  end
96
105
  end
@@ -53,8 +53,9 @@ module Pgbus
53
53
  key = [stream_name, target]
54
54
  schedule = false
55
55
 
56
+ entry = Entry.new(payload, opts)
56
57
  @mutex.synchronize do
57
- @buffer[key] = Entry.new(payload, opts)
58
+ @buffer[key] = entry
58
59
  unless @pending[key]
59
60
  @pending[key] = true
60
61
  schedule = true
@@ -65,19 +66,29 @@ module Pgbus
65
66
 
66
67
  begin
67
68
  @scheduler.schedule(window_ms / 1000.0) { flush_key(key, stream_name, target) }
68
- rescue StandardError
69
- # Nothing will flush this window: free the key, or no later submit
70
- # would schedule it again.
71
- @mutex.synchronize do
72
- @pending.delete(key)
73
- @buffer.delete(key)
74
- end
69
+ rescue StandardError => e
70
+ unschedule(key, entry, e, stream_name, target)
75
71
  raise
76
72
  end
77
73
  end
78
74
 
79
75
  private
80
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
+
81
92
  def flush_key(key, stream_name, target)
82
93
  entry = @mutex.synchronize do
83
94
  @pending.delete(key)
@@ -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
- adapter = self.adapter
204
- adapter.lock.synchronize { adapter.raw_connection.exec_params(sql, binds) }
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 adapter
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.connection
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 an
110
- # after_commit callback. If the transaction rolls back, the broadcast
111
- # silently drops — clients never see the change that the database
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 after_commit callback runs).
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
- transaction = current_open_transaction
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: !transaction.nil?,
185
+ deferred: !deferred_to.nil?,
179
186
  bytes: wrapped["html"].bytesize
180
187
  }
181
188
  Instrumentation.instrument("pgbus.stream.broadcast", instrument_payload) do
182
- if transaction
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
- # after_commit inside a transaction).
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 back, so
360
- # defer the submission to after_commit (mirrors the non-coalesced
361
- # path). Ephemeral coalescing is fire-and-forget, so it submits now.
362
- transaction = resolved_durable ? current_open_transaction : nil
363
- if transaction
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
- @client.ensure_stream_queue(@name)
390
- @ensured = true
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/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pgbus
4
- VERSION = "1.1.1"
4
+ VERSION = "1.1.2"
5
5
  end
@@ -10,8 +10,9 @@ module Pgbus
10
10
  def name: () -> String
11
11
  def durable?: () -> bool
12
12
 
13
- # The msg_id when sent at once; nil when deferred to after_commit, or
14
- # when coalesced.
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?,
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pgbus
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.1.1
4
+ version: 1.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson