pgbus 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a8a1d130e080a9c5b98771d9aa49f42b9799a815916c8fb1d50269723e4e2878
4
- data.tar.gz: cf3201146bd227f7ff8a6a114ebd6d8e1e9fc349cf9e58f1ead0daa05b58c769
3
+ metadata.gz: 5b361fe772144c29017651d5a839827f23ef6f259c7607970e1ee10a052693e6
4
+ data.tar.gz: 9d2b5cfe211b22334441641451d7db4d10618cb0e141edf5f9afaeb4dfc0e0c7
5
5
  SHA512:
6
- metadata.gz: 7e776479ba3bab58e293c13c7a37b37120c82b94eb3778242ea85a767e81ac13a1e210ef562237dad5652b34a75d5fbb0377ee3c4e5b7b3f5155922757898ccf
7
- data.tar.gz: 470c5e5fa425ab0d040e1502268e9c7eb7cea583f1db530cef0f5af1ace4eecc9eff1da6b21601471969d4cd0737b887094910564eead713de7ce08e0ad5290a
6
+ metadata.gz: 5c5c64b410aaa7f4b1972e4fa6b982162ffdee46c51d7e92ef590729664f5b9ee2d13348fe2de2bd0ae5ce1b6c6fe634017d56808e1de7a8026fbf7609840d97
7
+ data.tar.gz: b370b3fdd08557d9eabfa1a05219f5ffd0ad73fa7a08ef22a5171e04bcd48c56b42bd081f3caf7a49b75efeaa43d3e9d04c800cd1c2dfa9cc86c0cf639c7159e
data/CHANGELOG.md CHANGED
@@ -8,6 +8,20 @@
8
8
 
9
9
  ### Security
10
10
 
11
+ ## [1.1.1] - 2026-11-27
12
+
13
+ ### Added
14
+
15
+ - **`config.streams_coalesce_scheduler` and `Pgbus::Streams::Coalescer::InlineScheduler`** (#694). The coalescer reads the scheduler when a window's flush is scheduled: any object with `schedule(delay_seconds) { ... }`, or `nil` (the default) for its `Concurrent::ScheduledTask` timer. `InlineScheduler` runs the flush at once on the thread that submits it. When none is configured, `Pgbus::Testing.fake!` and `.inline!` select it, so a `broadcast(..., coalesce:)` in a test writes on the test thread's own connection, before it returns when no transaction is open (a durable one inside an open transaction is still submitted at its commit); `disabled!` restores the timer. A scheduler without `#schedule` fails `validate!`. A scheduler the application configured is left alone. This replaces prepending `Coalescer::ScheduledTaskScheduler#schedule` in a test suite.
16
+
17
+ ### Changed
18
+
19
+ - **`Pgbus::Testing.fake!` and `.inline!` no longer coalesce** (#694). Every `broadcast(..., coalesce:)` submit is broadcast at once, so a test that asserted only the last frame of a window now sees each frame. Set `config.streams_coalesce_scheduler` to a scheduler of your own to keep the window in tests.
20
+
21
+ ### Fixed
22
+
23
+ - **The stream registry and stream stats return their ActiveRecord lease** (#694). `StreamQueue.record!`, `table_exists?`, the registry load and `fingerprint_matched_names`, and `StreamStat.record!` and `table_exists?`, reached the database through a bare `connection`, a lease nothing returned on Rails 7.2+ (and `StreamStat.cleanup!` / `JobStat.cleanup!`, the dispatcher's prunes, through a relation, which leases the same way on Rails 7.1). The first durable broadcast of a stream records it, and for a coalesced broadcast that ran on a Concurrent IO thread no Rails executor wraps: each such thread kept a `BusRecord` connection checked out for its life. Under a pinned pool (Rails 7.2+ transactional tests) that lease was the test's pinned connection and outlived the test, so the next test's setup and the IO thread could drive one `PG::Connection` at once and hang. They now run inside `connection_pool.with_connection`, as the job path does since #649: a caller's own lease (a request, a job, an open transaction) is reused, and one taken is returned. The `Pgbus/BareConnectionLease` cop covers both models.
24
+
11
25
  ## [1.1.0] - 2026-11-24
12
26
 
13
27
  ### Added
data/README.md CHANGED
@@ -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 transaction open the flush runs before `broadcast` returns; a durable coalesced broadcast made inside an open transaction is submitted at its commit, as outside the test modes, and flushes then. `disabled!` restores the timer. `config.streams_coalesce_scheduler` takes any object with `schedule(delay_seconds) { ... }`, such as `Pgbus::Streams::Coalescer::InlineScheduler.new`, read when a window's flush is scheduled; `nil` (the default) is the timer. A scheduler you set yourself is left alone by the test modes, so its own threading applies in tests too.
1899
+
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
@@ -54,25 +54,33 @@ module Pgbus
54
54
  # `table_exists?` guard above passes) poisons every subsequent record!
55
55
  # in the process with "No unique index found". The unique index is owned
56
56
  # by this gem's own migration, so there is nothing to resolve.
57
+ #
58
+ # The write runs inside `connection_pool.with_connection` (issue #694):
59
+ # the coalescer flushes on a Concurrent IO thread no Rails executor
60
+ # wraps, so a bare `connection` there was a lease nobody returned. A
61
+ # caller that already holds one (a request, a job, an open
62
+ # transaction) keeps writing on it.
57
63
  def record!(queue_name)
58
64
  return false unless table_exists?
59
65
 
60
- conn = connection
61
- conn.execute(
62
- "INSERT INTO #{conn.quote_table_name(table_name)} (queue_name) " \
63
- "VALUES (#{conn.quote(queue_name)}) ON CONFLICT (queue_name) DO NOTHING"
64
- )
65
- # Keep the in-process cache consistent with the write so a subsequent
66
- # stream? check reflects this registration without a re-query. Only
67
- # update an ALREADY-LOADED cache — if @all_names is still nil (this
68
- # process hasn't queried the registry yet), seeding it here would
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
66
+ connection_pool.with_connection do |conn|
67
+ conn.execute(
68
+ "INSERT INTO #{conn.quote_table_name(table_name)} (queue_name) " \
69
+ "VALUES (#{conn.quote(queue_name)}) ON CONFLICT (queue_name) DO NOTHING"
70
+ )
71
+ # Keep the in-process cache consistent with the write so a subsequent
72
+ # stream? check reflects this registration without a re-query. Only
73
+ # update an ALREADY-LOADED cache — if @all_names is still nil (this
74
+ # process hasn't queried the registry yet), seeding it here would
75
+ # fabricate a one-entry set and silently hide every other
76
+ # already-registered stream until the next reset_cache!. Leaving it
77
+ # nil lets the next all_names call do a real load, which already
78
+ # includes this row since the insert above has committed. Taken
79
+ # while the connection is held; all_names loads outside the lock.
80
+ @names_lock.synchronize do
81
+ @names_generation += 1
82
+ @all_names = (@all_names | [queue_name]).freeze if @all_names
83
+ end
76
84
  end
77
85
  true
78
86
  rescue ActiveRecord::ActiveRecordError => e
@@ -117,13 +125,16 @@ module Pgbus
117
125
  # (`a_<queue>_msg_id_idx`). Job queues never get this index. Safe to call
118
126
  # when pgmq is absent — returns an empty set rather than raising.
119
127
  def fingerprint_matched_names
120
- Set.new(connection.select_values(<<~SQL.squish))
121
- SELECT m.queue_name
122
- FROM pgmq.meta m
123
- INNER JOIN pg_indexes i
124
- ON i.schemaname = 'pgmq'
125
- AND i.indexname = 'a_' || m.queue_name || '_msg_id_idx'
126
- SQL
128
+ names = connection_pool.with_connection do |conn|
129
+ conn.select_values(<<~SQL.squish)
130
+ SELECT m.queue_name
131
+ FROM pgmq.meta m
132
+ INNER JOIN pg_indexes i
133
+ ON i.schemaname = 'pgmq'
134
+ AND i.indexname = 'a_' || m.queue_name || '_msg_id_idx'
135
+ SQL
136
+ end
137
+ Set.new(names)
127
138
  rescue StandardError => e
128
139
  Pgbus.logger.debug { "[Pgbus] Failed to discover stream queue fingerprints: #{e.message}" }
129
140
  Set.new
@@ -167,7 +178,7 @@ module Pgbus
167
178
  def table_exists?
168
179
  return @table_exists if defined?(@table_exists) && @table_exists
169
180
 
170
- @table_exists = connection.table_exists?(table_name)
181
+ @table_exists = connection_pool.with_connection { |conn| conn.table_exists?(table_name) }
171
182
  rescue StandardError => e
172
183
  Pgbus.logger.debug { "[Pgbus] Failed to check stream queue table: #{e.message}" }
173
184
  false
@@ -190,7 +201,8 @@ module Pgbus
190
201
  def load_names
191
202
  return Set.new unless table_exists?
192
203
 
193
- Set.new(all.pluck(:queue_name))
204
+ # pluck leases through `connection` on Rails 7.1 (issue #694).
205
+ Set.new(connection_pool.with_connection { all.pluck(:queue_name) })
194
206
  rescue StandardError => e
195
207
  Pgbus.logger.debug { "[Pgbus] Failed to load stream queues: #{e.message}" }
196
208
  Set.new
@@ -26,15 +26,20 @@ module Pgbus
26
26
  # Records a stream event. Called from the Dispatcher when the
27
27
  # `streams_stats_enabled` flag is set. Errors are swallowed so a
28
28
  # missing table or a connection blip cannot kill the dispatcher.
29
+ # The dispatcher records off-request, where no Rails executor returns a
30
+ # lease, so the write takes its own through `with_connection` and gives
31
+ # it back (issue #694); create! leases through `connection` on Rails 7.1.
29
32
  def self.record!(stream_name:, event_type:, duration_ms: 0, fanout: nil)
30
33
  return unless table_exists?
31
34
 
32
- create!(
33
- stream_name: stream_name,
34
- event_type: event_type,
35
- duration_ms: duration_ms.to_i,
36
- fanout: fanout
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 = connection.table_exists?(table_name)
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
@@ -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
 
@@ -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 Concurrent::ScheduledTask-backed scheduler.
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 || ScheduledTaskScheduler.new
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
@@ -60,7 +61,19 @@ module Pgbus
60
61
  end
61
62
  end
62
63
 
63
- @scheduler.schedule(window_ms / 1000.0) { flush_key(key, stream_name, target) } if schedule
64
+ return unless schedule
65
+
66
+ begin
67
+ @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
75
+ raise
76
+ end
64
77
  end
65
78
 
66
79
  private
@@ -81,14 +94,37 @@ module Pgbus
81
94
  ErrorReporter.report(e, { component: "streams.coalescer", stream: stream_name, target: target })
82
95
  end
83
96
 
84
- # Default scheduler backed by Concurrent::ScheduledTask. Kept as a
85
- # tiny adapter so the Coalescer can be unit-tested with a synchronous
86
- # fake scheduler (no real timers, no sleeps).
97
+ # The timer: a Concurrent::ScheduledTask on the global IO executor.
98
+ # Kept as a tiny adapter so the Coalescer can be unit-tested with a
99
+ # synchronous fake scheduler (no real timers, no sleeps).
87
100
  class ScheduledTaskScheduler
88
101
  def schedule(delay_seconds, &)
89
102
  Concurrent::ScheduledTask.execute(delay_seconds, &)
90
103
  end
91
104
  end
105
+
106
+ # Runs the flush at once, on the thread that submitted it (issue #694).
107
+ # For tests: the flush then writes on that thread's own connection, with
108
+ # no IO thread sharing a pinned connection across the test boundary.
109
+ # Pgbus::Testing.fake! / inline! select it. It removes the coalescing
110
+ # itself: every submit is broadcast.
111
+ class InlineScheduler
112
+ def schedule(_delay_seconds) = yield
113
+ end
114
+
115
+ # The default: `config.streams_coalesce_scheduler`, read when a window's
116
+ # flush is scheduled (its first submit) so a scheduler set after boot (an
117
+ # initializer, a test mode) takes effect on the process-wide coalescer,
118
+ # else the timer.
119
+ class ConfiguredScheduler
120
+ def initialize
121
+ @timer = ScheduledTaskScheduler.new
122
+ end
123
+
124
+ def schedule(delay_seconds, &)
125
+ (Pgbus.configuration.streams_coalesce_scheduler || @timer).schedule(delay_seconds, &)
126
+ end
127
+ end
92
128
  end
93
129
  end
94
130
  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
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pgbus
4
- VERSION = "1.1.0"
4
+ VERSION = "1.1.1"
5
5
  end
@@ -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
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.0
4
+ version: 1.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson