pgbus 0.27.1 → 1.0.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.
@@ -308,6 +308,12 @@ module Pgbus
308
308
  # marks only its queues unavailable.
309
309
  :web_queue_metrics_chunk_size
310
310
 
311
+ # Held jobs after which a Pgbus.coalesce scope (and the one Pgbus.batch
312
+ # opens for its block) sends what it holds before the block ends (issue
313
+ # #683), so a huge block stays bounded in memory. A built batch's scope
314
+ # holds past it while a transaction is open on the batch's connection.
315
+ attr_accessor :coalesce_chunk_size
316
+
311
317
  # The MCP server's workflow write tools (issue #550): pgbus_workflow_resume,
312
318
  # _cancel, _skip_step, _resume_at, _run_now and _signal. Off by default, and
313
319
  # then they are never built, so tools/list cannot show them. Read once, when
@@ -510,6 +516,7 @@ module Pgbus
510
516
  @web_filter_parameters = nil # nil = auto-detect from Rails, then fall back to defaults
511
517
  @web_filter_sensitive = true
512
518
  @web_queue_metrics_chunk_size = 100
519
+ @coalesce_chunk_size = 1_000
513
520
  @deprecation_warned = Set.new
514
521
 
515
522
  # HTTP health endpoints — nil port disables the standalone server.
@@ -1133,6 +1140,10 @@ module Pgbus
1133
1140
  raise Pgbus::ConfigurationError, "web_queue_metrics_chunk_size must be a positive integer"
1134
1141
  end
1135
1142
 
1143
+ unless coalesce_chunk_size.is_a?(Integer) && coalesce_chunk_size.positive?
1144
+ raise Pgbus::ConfigurationError, "coalesce_chunk_size must be a positive integer"
1145
+ end
1146
+
1136
1147
  raise Pgbus::ConfigurationError, "require_primary must be true or false" unless [true, false].include?(require_primary)
1137
1148
  raise Pgbus::ConfigurationError, "mcp_write_tools must be true or false" unless [true, false].include?(mcp_write_tools)
1138
1149
 
data/lib/pgbus/engine.rb CHANGED
@@ -6,6 +6,14 @@ module Pgbus
6
6
  class Engine < ::Rails::Engine
7
7
  isolate_namespace Pgbus
8
8
 
9
+ # config.pgbus.* in the application (issue #682). coalesce_requests
10
+ # inserts Pgbus::ActiveJob::Coalesce::Middleware after
11
+ # ActionDispatch::Executor, with coalesce_requests_on_failure as its
12
+ # on_failure.
13
+ config.pgbus = ActiveSupport::OrderedOptions.new
14
+ config.pgbus.coalesce_requests = false
15
+ config.pgbus.coalesce_requests_on_failure = :raise
16
+
9
17
  # When pgbus was loaded before Rails, a separate Zeitwerk loader manages
10
18
  # app/models. Tear it down before Rails' autoloader claims the same paths.
11
19
  initializer "pgbus.release_models_loader", before: :set_autoload_paths do
@@ -168,6 +176,17 @@ module Pgbus
168
176
  app.middleware.use Pgbus::Signals::Middleware if Pgbus.configuration.streams_enabled
169
177
  end
170
178
 
179
+ # Opt-in (issue #682): each request's enqueues go out together before
180
+ # the response is returned.
181
+ # After the app's initializers, so the flag may be set there too.
182
+ initializer "pgbus.coalesce.middleware", after: :load_config_initializers do |app|
183
+ options = app.config.pgbus
184
+ if options.coalesce_requests
185
+ app.middleware.insert_after ActionDispatch::Executor, Pgbus::ActiveJob::Coalesce::Middleware,
186
+ on_failure: options.coalesce_requests_on_failure
187
+ end
188
+ end
189
+
171
190
  # Make the <pgbus-stream-source> element available to the host app's
172
191
  # asset pipeline (Propshaft or Sprockets). The importmap pin points at
173
192
  # the minified build (rake frontend:js). Propshaft rewrites its
@@ -102,6 +102,7 @@ module Pgbus
102
102
  add_processed_event_completion: "pgbus:add_processed_event_completion",
103
103
  add_batch_executions: "pgbus:add_batch_executions",
104
104
  add_batch_callback_jobs: "pgbus:add_batch_callback_jobs",
105
+ add_batch_owner: "pgbus:add_batch_owner",
105
106
  tune_autovacuum: "pgbus:tune_autovacuum",
106
107
  tune_fillfactor: "pgbus:tune_fillfactor",
107
108
  fold_queue_name_case: "pgbus:fold_queue_name_case"
@@ -130,6 +131,7 @@ module Pgbus
130
131
  add_processed_event_completion: "completed_at on pgbus_processed_events (two-phase idempotency claim)",
131
132
  add_batch_executions: "batch execution-row tracking (self-healing completion, on_failure rename)",
132
133
  add_batch_callback_jobs: "batch callback-job columns (configured ActiveJob instances as batch callbacks)",
134
+ add_batch_owner: "batch owner column (a batch built by a pgbus process; its perform_later calls sent together)",
133
135
  tune_autovacuum: "autovacuum tuning for PGMQ queue and archive tables",
134
136
  tune_fillfactor: "fillfactor=70 on PGMQ queue tables (reduces page density during update churn)",
135
137
  fold_queue_name_case: "lower-case spelling for queues created in mixed case (PGMQ's table names are lower case)"
@@ -169,6 +171,7 @@ module Pgbus
169
171
  *processed_event_completion_migrations,
170
172
  *batch_executions_migrations,
171
173
  *batch_callback_jobs_migrations,
174
+ *batch_owner_migrations,
172
175
  *autovacuum_migrations,
173
176
  *fillfactor_migrations
174
177
  ]
@@ -339,6 +342,15 @@ module Pgbus
339
342
  [:add_batch_callback_jobs]
340
343
  end
341
344
 
345
+ # The process that builds a batch (issue #683): without the column a
346
+ # batch is never built, and its members are sent one at a time.
347
+ def batch_owner_migrations
348
+ return [] unless table_exists?("pgbus_batches")
349
+ return [] if column_names("pgbus_batches").include?("owner_process_id")
350
+
351
+ [:add_batch_owner]
352
+ end
353
+
342
354
  # Autovacuum tuning: check if any PGMQ queue table already has
343
355
  # custom autovacuum settings applied. If not, queue the migration.
344
356
  def autovacuum_migrations
@@ -11,6 +11,28 @@ module Pgbus
11
11
 
12
12
  attr_reader :process_entry
13
13
 
14
+ # The pgbus_processes row this OS process heartbeats under (issue
15
+ # #683): a batch built here records it as its owner, and the sweep
16
+ # reaps the build only once that row is gone or its heartbeat is older
17
+ # than ALIVE_THRESHOLD. [pid, id], so a forked child never reports its
18
+ # parent's row; the last registration wins.
19
+ @owner_lock = Mutex.new
20
+ @owner = nil
21
+
22
+ class << self
23
+ def current_process_id
24
+ @owner_lock.synchronize { @owner[1] if @owner && @owner[0] == ::Process.pid }
25
+ end
26
+
27
+ def note_registered(id)
28
+ @owner_lock.synchronize { @owner = [::Process.pid, id].freeze }
29
+ end
30
+
31
+ def note_deregistered(id)
32
+ @owner_lock.synchronize { @owner = nil if @owner && @owner[1] == id }
33
+ end
34
+ end
35
+
14
36
  # config: the owning process's configuration, for the app revision.
15
37
  def initialize(kind:, metadata: {}, on_beat: nil, loop_tick_supplier: nil, metadata_supplier: nil,
16
38
  config: Pgbus.configuration)
@@ -93,6 +115,9 @@ module Pgbus
93
115
  return if ProcessEntry.where(id: @process_id).update_all(updates).positive? || @stopped
94
116
 
95
117
  old_id = @process_id
118
+ # A batch built while this process re-registers must not name the
119
+ # row that is gone (issue #683).
120
+ self.class.note_deregistered(old_id)
96
121
  Pgbus.logger.warn do
97
122
  "[Pgbus] Process row id=#{old_id} kind=#{@kind} pid=#{::Process.pid} is gone " \
98
123
  "(stale-process reaper, manual cleanup, or clock skew?) — re-registering"
@@ -110,6 +135,7 @@ module Pgbus
110
135
  last_heartbeat_at: Time.current
111
136
  )
112
137
  @process_id = record.id
138
+ self.class.note_registered(@process_id)
113
139
  rescue StandardError => e
114
140
  Pgbus.logger.warn { "[Pgbus] Process registration failed: #{e.message}" }
115
141
  end
@@ -117,6 +143,7 @@ module Pgbus
117
143
  def deregister_process
118
144
  return unless @process_id
119
145
 
146
+ self.class.note_deregistered(@process_id)
120
147
  ProcessEntry.where(id: @process_id).delete_all
121
148
  rescue StandardError => e
122
149
  Pgbus.logger.warn { "[Pgbus] Process deregistration failed: #{e.message}" }
data/lib/pgbus/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pgbus
4
- VERSION = "0.27.1"
4
+ VERSION = "1.0.0"
5
5
  end
@@ -20,6 +20,12 @@ module Pgbus
20
20
  # this, and a redelivery means a dead worker only while it is true.
21
21
  def self.pgbus_visibility_heartbeat_enabled = true # rubocop:disable Naming/PredicateMethod -- JobMixin's reader
22
22
 
23
+ # Sent at once inside Pgbus.coalesce (issue #682): a step enqueue that
24
+ # fails is reported and swept (WorkflowStep#enqueue_step_job), so it
25
+ # must not become the scope's on_failure. Internal to pgbus, not an
26
+ # opt-out for application jobs.
27
+ def self.pgbus_coalesce? = false
28
+
23
29
  def perform(step_id)
24
30
  StepExecution.new(step_id).call
25
31
  end
data/lib/pgbus.rb CHANGED
@@ -317,6 +317,21 @@ module Pgbus
317
317
  Batch.start(**, &)
318
318
  end
319
319
 
320
+ # Hold the block's enqueues and send them together when it ends (issue
321
+ # #682): one send_batch per (queue, priority, delay) group instead of one send
322
+ # per perform_later. See Pgbus::ActiveJob::Coalesce for what is held, the
323
+ # optimistic return value and the failure modes. on_failure: :raise
324
+ # (default) raises Pgbus::EnqueueError for a job that could not be sent,
325
+ # :report reports it, a callable receives (jobs, error).
326
+ #
327
+ # Pgbus.coalesce do
328
+ # EventJob.perform_later("a")
329
+ # EventJob.perform_later("b")
330
+ # end # one send here
331
+ def coalesce(on_failure: :raise, &)
332
+ Pgbus::ActiveJob::Coalesce.open(on_failure: on_failure, &)
333
+ end
334
+
320
335
  # Publish an event to the bus — the top-level shortcut for
321
336
  # `Pgbus::EventBus::Publisher.publish`, symmetric with `Pgbus.stream`.
322
337
  #
@@ -5,6 +5,8 @@ module Pgbus
5
5
  def enqueue: (untyped active_job) -> untyped
6
6
  def enqueue_at: (untyped active_job, Numeric timestamp) -> untyped
7
7
  def enqueue_all: (Array[untyped] active_jobs) -> Integer
8
+ # A Coalesce scope's buffer, as [job, payload serialized at perform_later, due_at] entries (issues #682, #686).
9
+ def deliver_coalesced: (Array[[untyped, Hash[String, untyped], Numeric?]] entries, ?counted: bool) -> Coalesce::Result
8
10
  end
9
11
  end
10
12
 
@@ -0,0 +1,54 @@
1
+ module Pgbus
2
+ module ActiveJob
3
+ # A unit of work's enqueues, held at the adapter and sent together when
4
+ # the unit ends (issue #682). Opened by Pgbus.coalesce and Middleware.
5
+ class Coalesce
6
+ interface _OnFailure
7
+ def call: (Array[untyped] jobs, Pgbus::EnqueueError error) -> void
8
+ end
9
+
10
+ type on_failure = :raise | :report | _OnFailure
11
+
12
+ interface _CountIn
13
+ def call: (Array[Hash[String, untyped]] payloads, final: bool) -> void
14
+ end
15
+
16
+ interface _OnFailed
17
+ def call: (Array[untyped] jobs) -> void
18
+ end
19
+
20
+ KEY: Symbol
21
+ FAILURE_MODES: Array[Symbol]
22
+
23
+ class Result
24
+ attr_reader buffered: Integer
25
+ attr_reader sent: Integer
26
+ attr_reader retried: Integer
27
+ attr_reader failed: Array[untyped]
28
+ attr_reader error: StandardError?
29
+
30
+ def initialize: (buffered: Integer, sent: Integer, retried: Integer, failed: Array[untyped], error: StandardError?) -> void
31
+ end
32
+
33
+ def self.current: () -> Coalesce?
34
+ # batch_id: (Pgbus.batch, issue #683) a scope of the batch's own that holds only its members;
35
+ # count_in.call(payloads, final:) counts each chunk in before it is sent, the final one closing the build.
36
+ def self.open: [T] (?on_failure: on_failure, ?batch_id: String?, ?count_in: _CountIn?, ?on_failed: _OnFailed?) { () -> T } -> T
37
+ def self.validate_on_failure!: (untyped on_failure) -> void
38
+
39
+ attr_reader on_failure: on_failure
40
+ attr_reader batch_id: String?
41
+
42
+ def initialize: (?on_failure: on_failure, ?batch_id: String?, ?count_in: _CountIn?, ?on_failed: _OnFailed?, ?chunk_size: Integer) -> void
43
+ def push: (Adapter adapter, untyped job, Hash[String, untyped] payload, ?Numeric? due_at) -> bool
44
+ def finish!: (?block_error: Exception?) -> Result
45
+
46
+ # Runs the request inside Pgbus.coalesce; the buffer is sent before the
47
+ # response tuple is returned.
48
+ class Middleware
49
+ def initialize: (untyped app, ?on_failure: Coalesce::on_failure) -> void
50
+ def call: (Hash[String, untyped] env) -> untyped
51
+ end
52
+ end
53
+ end
54
+ end
@@ -30,6 +30,8 @@ module Pgbus
30
30
  def capsule_named: (untyped name) -> untyped
31
31
  def circuit_breaker_enabled: () -> bool
32
32
  def circuit_breaker_enabled=: (untyped) -> untyped
33
+ def coalesce_chunk_size: () -> Integer
34
+ def coalesce_chunk_size=: (untyped) -> untyped
33
35
  def completed_jobs: () -> (:archive | :delete)
34
36
  def completed_jobs=: (untyped value) -> (:archive | :delete)
35
37
  def completion_batch_size: () -> Integer
data/sig/pgbus.rbs CHANGED
@@ -119,6 +119,9 @@ module Pgbus
119
119
  def self.stream_name_budget: () -> Integer
120
120
  # Keywords go to Pgbus::Batch.new (description:, properties:, on_complete:, uniqueness_key:, …).
121
121
  def self.batch: (**untyped options) { (Batch::Builder) -> void } -> Batch
122
+ # Holds the block's bulk-eligible enqueues and sends them together when it
123
+ # ends (issue #682); on_failure: :raise | :report | ^(jobs, error) -> void.
124
+ def self.coalesce: [T] (?on_failure: ActiveJob::Coalesce::on_failure) { () -> T } -> T
122
125
  # delay: seconds, as a Numeric or an ActiveSupport::Duration (1.hour).
123
126
  def self.publish: (String routing_key, untyped payload, ?headers: Hash[String, untyped]?, ?delay: Numeric | _ToI) -> untyped
124
127
  def self.publish_later: (String routing_key, untyped payload, delay: Numeric | _ToI, ?headers: Hash[String, 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: 0.27.1
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson
@@ -285,6 +285,7 @@ files:
285
285
  - lib/active_job/queue_adapters/pgbus_adapter.rb
286
286
  - lib/generators/pgbus/add_batch_callback_jobs_generator.rb
287
287
  - lib/generators/pgbus/add_batch_executions_generator.rb
288
+ - lib/generators/pgbus/add_batch_owner_generator.rb
288
289
  - lib/generators/pgbus/add_deploy_task_run_outcomes_generator.rb
289
290
  - lib/generators/pgbus/add_deploy_tasks_generator.rb
290
291
  - lib/generators/pgbus/add_failed_events_index_generator.rb
@@ -309,6 +310,7 @@ files:
309
310
  - lib/generators/pgbus/migration_path.rb
310
311
  - lib/generators/pgbus/templates/add_batch_callback_jobs.rb.erb
311
312
  - lib/generators/pgbus/templates/add_batch_executions.rb.erb
313
+ - lib/generators/pgbus/templates/add_batch_owner.rb.erb
312
314
  - lib/generators/pgbus/templates/add_deploy_task_run_outcomes.rb.erb
313
315
  - lib/generators/pgbus/templates/add_deploy_tasks_tables.rb.erb
314
316
  - lib/generators/pgbus/templates/add_failed_events_source_queue.rb.erb
@@ -344,6 +346,8 @@ files:
344
346
  - lib/pgbus.rb
345
347
  - lib/pgbus/active_job/adapter.rb
346
348
  - lib/pgbus/active_job/batch_id.rb
349
+ - lib/pgbus/active_job/coalesce.rb
350
+ - lib/pgbus/active_job/coalesce/middleware.rb
347
351
  - lib/pgbus/active_job/current_attributes.rb
348
352
  - lib/pgbus/active_job/delivery.rb
349
353
  - lib/pgbus/active_job/deploy_task_run_id.rb
@@ -632,6 +636,7 @@ files:
632
636
  - lib/tasks/pgbus_streams.rake
633
637
  - sig/pgbus.rbs
634
638
  - sig/pgbus/active_job/adapter.rbs
639
+ - sig/pgbus/active_job/coalesce.rbs
635
640
  - sig/pgbus/active_job/quiet_logs.rbs
636
641
  - sig/pgbus/client.rbs
637
642
  - sig/pgbus/configuration.rbs