pgbus 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ module Web
5
+ module Streamer
6
+ # The streamer's signal sink in a web process (issue #674): the Listener
7
+ # (or the HubClient, under :master scope) hands it each process-signal
8
+ # NOTIFY and each LISTEN gap; one thread of its own runs the subscribers
9
+ # (Pgbus::Signals.deliver / deliver_gap), so a slow or raising block
10
+ # never stalls the LISTEN loop or the stream dispatcher.
11
+ #
12
+ # The thread starts on the first signal for a registered name (or the
13
+ # first gap with an on_gap registered): a process without subscribers
14
+ # never has one. Messages still queued at #stop are dropped, as a NOTIFY
15
+ # to a stopped process is.
16
+ class SignalDelivery
17
+ STOP_JOIN_SECONDS = 2
18
+ # Signals waiting behind a slow or stuck subscriber. Past this, a
19
+ # signal is dropped and reported as a gap instead (on_gap is the
20
+ # recovery for a missed signal), so the backlog never grows unbounded.
21
+ BACKLOG_LIMIT = 1_000
22
+
23
+ def initialize(logger: Pgbus.logger, signals: Pgbus::Signals)
24
+ @logger = logger
25
+ @signals = signals
26
+ @queue = Queue.new
27
+ # Guards @thread, @stopped and @gap_pending: the first signal starts
28
+ # the thread, #stop ends it, from different threads.
29
+ @lock = Mutex.new
30
+ @thread = nil
31
+ @stopped = false
32
+ # A gap queued and not yet run: a second gap before it runs (a
33
+ # failover during the first LISTEN, say) adds nothing.
34
+ @gap_pending = false
35
+ end
36
+
37
+ # Sink API, called on the listener (or hub reader) thread: a queue
38
+ # push and nothing else.
39
+ def signal(channel, payload)
40
+ name = @signals.name_for(channel)
41
+ return unless name
42
+ return overflow(name) if @queue.size >= BACKLOG_LIMIT
43
+
44
+ enqueue([:signal, name, payload])
45
+ end
46
+
47
+ def gap
48
+ return unless @signals.gap_handlers?
49
+
50
+ already_queued = @lock.synchronize do
51
+ pending = @gap_pending
52
+ @gap_pending = true
53
+ pending
54
+ end
55
+ return if already_queued
56
+
57
+ begin
58
+ enqueue([:gap])
59
+ rescue StandardError
60
+ # Never queued (the delivery thread could not start): a later gap
61
+ # must not be coalesced into this one.
62
+ @lock.synchronize { @gap_pending = false }
63
+ raise
64
+ end
65
+ end
66
+
67
+ def threads
68
+ @lock.synchronize { [@thread].compact }
69
+ end
70
+
71
+ def stop
72
+ # Under @lock with enqueue's push: nothing lands behind the sentinel,
73
+ # and what is still queued is dropped rather than run at shutdown.
74
+ thread = @lock.synchronize do
75
+ @stopped = true
76
+ @queue.clear
77
+ @queue << [:stop] if @thread
78
+ @thread
79
+ end
80
+ return unless thread
81
+
82
+ joined = thread.join(STOP_JOIN_SECONDS)
83
+ if joined
84
+ @lock.synchronize { @thread = nil }
85
+ else
86
+ @logger.warn do
87
+ "[Pgbus::Streamer::SignalDelivery] a signal subscriber is still running after #{STOP_JOIN_SECONDS}s"
88
+ end
89
+ end
90
+ nil
91
+ end
92
+
93
+ private
94
+
95
+ def enqueue(message)
96
+ @lock.synchronize do
97
+ return if @stopped
98
+
99
+ # The delivery thread, owned by this object: started once, on the
100
+ # first message, under @lock; #stop ends and joins it.
101
+ @thread ||= Thread.new { run_loop } # rubocop:disable ThreadSafety/NewThread
102
+ @queue << message
103
+ end
104
+ end
105
+
106
+ # One warning per overflow episode: while a gap is already pending it
107
+ # covers every signal dropped behind it.
108
+ def overflow(name)
109
+ return gap if @lock.synchronize { @gap_pending }
110
+
111
+ @logger.warn do
112
+ "[Pgbus::Streamer::SignalDelivery] #{BACKLOG_LIMIT} signals waiting on a slow subscriber; " \
113
+ "dropped #{name.inspect} and reporting a gap"
114
+ end
115
+ gap
116
+ end
117
+
118
+ def run_loop
119
+ loop do
120
+ kind, name, payload = @queue.pop
121
+ case kind
122
+ when :stop then break
123
+ when :signal then @signals.deliver(name, payload)
124
+ when :gap
125
+ @lock.synchronize { @gap_pending = false }
126
+ @signals.deliver_gap
127
+ end
128
+ rescue StandardError => e
129
+ # deliver never raises; a bug here must not end delivery.
130
+ @logger.error { "[Pgbus::Streamer::SignalDelivery] delivery failed: #{e.class}: #{e.message}" }
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -37,6 +37,14 @@ module Pgbus
37
37
  @current_mutex.synchronize { @current = instance }
38
38
  end
39
39
 
40
+ # A signal registered after this process's streamer started (issue
41
+ # #674): LISTEN on its channel now. No streamer yet: nothing to do, a
42
+ # streamer started later subscribes every registered channel.
43
+ def listen_signal(channel)
44
+ instance = @current_mutex.synchronize { @current }
45
+ instance&.listen_signal(channel)
46
+ end
47
+
40
48
  def stream_counter
41
49
  @current_mutex.synchronize { @current&.stream_counter }
42
50
  end
@@ -50,6 +58,8 @@ module Pgbus
50
58
  instance = @current
51
59
  @current = nil
52
60
  end
61
+ # A later request must start a fresh streamer for process signals.
62
+ Pgbus::Signals.streamer_reset! if instance
53
63
  instance&.shutdown!
54
64
  end
55
65
  end
data/lib/pgbus.rb CHANGED
@@ -335,6 +335,27 @@ module Pgbus
335
335
  EventBus::Publisher.publish_later(routing_key, payload, delay: delay, headers: headers)
336
336
  end
337
337
 
338
+ # Run a block in every web process when any process sends +name+ (issue
339
+ # #674) — see Pgbus::Signals. Register in an initializer. `on_gap:` runs
340
+ # once after a LISTEN gap (reconnect, hub failover), when signals may have
341
+ # been missed.
342
+ #
343
+ # Pgbus.on_signal(:widgets_changed, on_gap: -> { WIDGETS.clear }) { |_payload| WIDGETS.clear }
344
+ def on_signal(name, on_gap: nil, &)
345
+ Signals.subscribe(name, on_gap: on_gap, &)
346
+ end
347
+
348
+ # Send +name+ to every process's on_signal blocks. Inside an open
349
+ # ActiveRecord transaction it is sent at COMMIT, never on rollback (a
350
+ # `transaction(joinable: false)` block sends at once). +payload+ is an
351
+ # optional String under NOTIFY's 7999-byte cap.
352
+ #
353
+ # Pgbus.signal(:widgets_changed)
354
+ # Pgbus.signal(:widgets_changed, "id=42")
355
+ def signal(name, payload = nil)
356
+ Signals.publish(name, payload)
357
+ end
358
+
338
359
  # A fresh configuration (never nil, so readers need no lock) and no client.
339
360
  def reset!
340
361
  @state_lock.synchronize do
data/sig/pgbus/client.rbs CHANGED
@@ -37,6 +37,7 @@ module Pgbus
37
37
  def native_ready?: (String full_name) -> bool
38
38
  def notify_enabled?: (untyped queue_name) -> bool
39
39
  def notify_stream: (untyped stream_name, untyped payload) -> untyped
40
+ def notify_signal: (Symbol | String name, ?String? payload) -> untyped
40
41
  def oldest_claimable_ages: (?untyped queue_name) -> untyped
41
42
  def pgmq: () -> untyped
42
43
  def pgmq_installed?: () -> bool
data/sig/pgbus.rbs CHANGED
@@ -49,6 +49,15 @@ module Pgbus
49
49
  end
50
50
  end
51
51
 
52
+ # Partial: only the type Pgbus.on_signal returns.
53
+ module Signals
54
+ class Subscriber
55
+ attr_reader name: String
56
+ attr_reader callback: Proc
57
+ attr_reader on_gap: untyped
58
+ end
59
+ end
60
+
52
61
  # Partial: only the types Pgbus.batch names. Batch's own methods are not
53
62
  # covered by spec/pgbus/rbs_spec.rb yet.
54
63
  class Batch
@@ -113,6 +122,10 @@ module Pgbus
113
122
  # delay: seconds, as a Numeric or an ActiveSupport::Duration (1.hour).
114
123
  def self.publish: (String routing_key, untyped payload, ?headers: Hash[String, untyped]?, ?delay: Numeric | _ToI) -> untyped
115
124
  def self.publish_later: (String routing_key, untyped payload, delay: Numeric | _ToI, ?headers: Hash[String, untyped]?) -> untyped
125
+ # Process signals (issue #674): on_signal registers a block run in every web
126
+ # process when any process calls signal(name); on_gap runs after a LISTEN gap.
127
+ def self.on_signal: (Symbol | String name, ?on_gap: (^() -> void)?) { (String? payload) -> void } -> Signals::Subscriber
128
+ def self.signal: (Symbol | String name, ?String? payload) -> nil
116
129
  def self.reset!: () -> void
117
130
  def self.reset_client!: () -> void
118
131
  def self.stopping: () -> 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: 0.26.0
4
+ version: 0.27.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson
@@ -368,6 +368,7 @@ files:
368
368
  - lib/pgbus/client/notify_stream.rb
369
369
  - lib/pgbus/client/read_after.rb
370
370
  - lib/pgbus/client/resizable_pool.rb
371
+ - lib/pgbus/client/session_gucs.rb
371
372
  - lib/pgbus/concurrency.rb
372
373
  - lib/pgbus/concurrency/blocked_execution.rb
373
374
  - lib/pgbus/concurrency/semaphore.rb
@@ -462,6 +463,7 @@ files:
462
463
  - lib/pgbus/metrics/prometheus_exporter.rb
463
464
  - lib/pgbus/metrics/subscriber.rb
464
465
  - lib/pgbus/metrics/workflow_metrics.rb
466
+ - lib/pgbus/open_transaction.rb
465
467
  - lib/pgbus/outbox.rb
466
468
  - lib/pgbus/outbox/poller.rb
467
469
  - lib/pgbus/pgmq_schema.rb
@@ -506,6 +508,8 @@ files:
506
508
  - lib/pgbus/ruby_jit.rb
507
509
  - lib/pgbus/serializer.rb
508
510
  - lib/pgbus/shareable.rb
511
+ - lib/pgbus/signals.rb
512
+ - lib/pgbus/signals/middleware.rb
509
513
  - lib/pgbus/stat_buffer.rb
510
514
  - lib/pgbus/streams.rb
511
515
  - lib/pgbus/streams/broadcast_opts.rb
@@ -580,6 +584,7 @@ files:
580
584
  - lib/pgbus/web/streamer/peer_close_watcher.rb
581
585
  - lib/pgbus/web/streamer/presence_tracker.rb
582
586
  - lib/pgbus/web/streamer/registry.rb
587
+ - lib/pgbus/web/streamer/signal_delivery.rb
583
588
  - lib/pgbus/web/streamer/stream_counter.rb
584
589
  - lib/pgbus/web/streamer/stream_event_dispatcher.rb
585
590
  - lib/pgbus/web/time_format.rb