pgbus 0.25.1 → 0.26.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: d2e222e8f30d9e69de08103ecf574c4166a4804d90aff9db01df780451255b0f
4
- data.tar.gz: 8744453ae4652d2dc6e163b81c5104b5e25e62bf6c7dff57c5b4e5a5c5807208
3
+ metadata.gz: 8b69998354e78e47fc483f2c03b2fd2d4856031ad0a1e2db00d4ba7da7f40547
4
+ data.tar.gz: 3bfad5779917d58b0afd88da6b6cb680c3086f879a76de66aa139c318476bbcc
5
5
  SHA512:
6
- metadata.gz: e0f35bcb78c6f707f6adb837f6845c21143543050891bc5dd677d935d571b2dfb93fe6e3d048ceecd2a4d75596c5f811cee2fa6076dba0c51c5b030a1ad527bb
7
- data.tar.gz: c4d933bc1d90cae70c82888f31a6bbc73d83cc1a8e1ca9beccd754c310d03289e4edce4170a11a85f05c6310ecb95ec6a005c50cf9791fc5ab0b594252f0c5a3
6
+ metadata.gz: 48fffb0b444afea7ba76f4d53e65426cbfe9cea96af16f1aa674586dc1141106e246f51b117da7d533ad153185a3189d3d6b730521eed7c21ce5acec3d3c3df9
7
+ data.tar.gz: 7e580515d3b53981e973556c1fd440dfe91700a30f554b650cc82c4843d7286161a1f7ff07c73799a7988303e04bf6d433e88bd37951ef47d1e1ae5d7b42c417
data/CHANGELOG.md CHANGED
@@ -1,8 +1,16 @@
1
1
  ## [Unreleased]
2
2
 
3
- ### Added
3
+ ### Changed
4
4
 
5
- - **Deploy tasks: `after:` makes a task wait until the tasks it names have completed, and every run records its outcome (issue #660).** `after:` takes a task key or a list of keys declared in the loaded configuration (any of `deploy_tasks_files`). The scheduler keeps such a task armed, and does not enqueue it, until each named task has a run with `completed_at` at its current version (any revision; an `every_deploy` dependency needs one on this revision). A rollover run and a Run now run both count, so a failed dependency that an operator fixes and runs again with Run now unblocks its dependents without a new deploy. A waiting task records no failure and no backoff, and fires on the first tick after its last dependency completes; the check is one query per tick, made only while an armed task has dependencies. At scheduler boot a task whose `after:` names an unknown key (`after: unknown task 'x'`), sits on a cycle (`after: cycle a → b → a`, a self-reference included), or names a task that is itself skipped (`after: 'x' is skipped`) is skipped with a warning. Run outcomes: `Deploy::Runner#enqueue` now creates the `pgbus_deploy_task_runs` row before the enqueue and passes its id in the job payload under `pgbus_deploy_task_run_id` (`Pgbus::ActiveJob::DeployTaskRunId`, included on `ActiveJob::Base` next to `BatchId`; an unmarked job's payload is unchanged), fills in `queue_name` and `msg_id` after it, and deletes the row when the enqueue fails. The executor stamps `completed_at` when `perform` returned having done its work without re-enqueuing the job (a `retry_on` attempt whose retry is queued, or a `discard_on` block that queues one, leaves it to the retry; a job that rescues inside `perform` and returns has completed) and `failed_at` when ActiveJob discarded the job without queuing a retry (`discard_on`, with or without a block, or a `retry_on` that gave up through its block, where one without a block re-raises and ends dead-lettered as before; `Pgbus::ActiveJob::DeployTaskRunId` marks the instance in ActiveJob's `run_after_discard_procs`, after the job's own `after_discard` procs, so a discarded dependency reads `failed` and its dependents keep waiting, issue #662), when the job is dead-lettered, discarded as a `:while_executing` duplicate, or its retry never left (dropped by its own concurrency limit, `on_conflict: :discard`, or aborted by a `before_enqueue` callback); a failed write is reported and never fails the job, and a job without the key pays one Hash lookup. An enqueue the job's own `on_conflict: :discard` / `:log` drops now counts as a failed enqueue (the run is deleted and the task re-armed with backoff). A run row without `queue_name` (its enqueue never finished) does not count as a run, so the version stays owed. The dispatcher's pruning keeps the newest completed run per task and version. Dashboard: a task's state says "Waiting for N dependencies to complete" and lists each one as `not run`, `running` or `failed`; the task page shows `after:` and an Outcome column in the run history; Run now on a waiting task is refused with a flash naming the dependencies (`DataSource#enqueue_deploy_task_now(id, ignore_dependencies: false)` returns `:blocked`) unless "Ignore dependencies" is ticked on the task page. `pgbus_deploy_tasks` (MCP) lists `dependencies` and `waiting_on`. New generator `pgbus:add_deploy_task_run_outcomes` adds `pgbus_deploy_task_runs.completed_at` / `failed_at`, `pgbus_deploy_tasks.dependencies` and an index on `(task_key, completed_at)`; `pgbus:update` queues it, and fresh `pgbus:install` / `pgbus:add_deploy_tasks` include the columns. Until it is migrated, a task with `after:` is skipped with a warning naming the generator and no outcome is written. **Upgrade note:** runs recorded before the migration have no outcome and satisfy nothing, so when an `after:` names a task whose only runs predate the upgrade, Run now that task once (or bump its version; an `every_deploy` dependency needs a run on the current revision, so only Run now helps). Delivery stays at-least-once: a scheduler that dies between claiming a task and enqueuing it leaves the task unarmed until the next scheduler boot re-arms it, and a run whose enqueue could not be recorded runs again after one, so deploy tasks must be idempotent. Refs #660.
5
+ - **A member-keyed presence `touch` no longer probes `information_schema` on a table without the seat columns, and a forced re-check no longer restarts the backoff (issue #666).** On a `pgbus_presence_members` table where `rails g pgbus:add_presence_seats` has not run, every member-keyed `touch`, `leave` and `sweep!` re-probed a cached "no seats" answer before it ran and restarted the #665 backoff at 30 s. The streamer touches once per connection per heartbeat, so a process with N member-keyed connections sent N catalog queries every `streams_heartbeat_interval` (15 s by default), and its backoff never took effect. A member-keyed `touch` now uses the cached answer and re-checks only on the backoff's schedule: three touches after a reset send one probe instead of four, and none while a "no" is cached. Assumed: on a table migrated under a running process, such a `touch` can also refresh that member's seat rows until the next re-check (at most 10 minutes, `SCHEMA_RECHECK_MAX_SECONDS`); it is an `UPDATE` of `last_seen_at`, so nothing is deleted. A member-keyed `leave` and `sweep!` still re-check a cached "no" before they delete, so they never delete seat rows on a migrated table (#515), now with one probe instead of up to two, answered from that probe. That re-check leaves the backoff alone: over a fresh "no" it changes neither the step nor the schedule however many disconnects force one, and over a "no" already due it is the timed re-check, one step. `reset_schema_cache!` still re-probes at once and starts again from 30 s. Refs #666.
6
+
7
+ - **pgmq-ruby 0.9.0 (was 0.8.2); the gemspec now requires `~> 0.9.0` (issue #656).** What reaches pgbus users is the connection pool: pgmq-ruby's checkout health check now resets a pooled connection in any state other than `CONNECTION_OK`, so a connection a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`) is recovered on the next checkout. Before, the checkout handed it out again, libpq refused every send (`no connection to the server`), and pgbus's stale-connection retry only recovered it on its last attempt by dropping both pools (#645): now the call succeeds on the first attempt, with no retry, no pool reload and no warning. pgmq-ruby also resets a connection whose call raised `PG::ConnectionBad` or `PG::UnableToSend` before it goes back to the pool (not a connection pgbus hands it through a callable, which it neither resets nor closes: the shared ActiveRecord connection, and dedicated connections in `connection_guc_mode = :session` with database.yml `variables`); native statements re-prepare on the new backend as on any reconnect. pgbus keeps its reload before the last stale retry for a connection that still fails after the health check passed it. A checkout reset of a connection in `connection_guc_mode = :session` with `variables` applies its `SET`s again (#671). `produce_topic` and `produce_batch_topic` now raise `PGMQ::Errors::MessageInvalidError` for a message that is not a String or headers that are neither a String nor nil, as `produce` has since 0.8.0. `Client#publish_to_topic` (what `Pgbus.publish` and the outbox poller call; `Pgbus::Testing`'s fake and inline modes never reach PGMQ) serializes the payload and headers to JSON Strings first, so it is unaffected; `headers: false`, which pgmq-ruby dropped before with an integer delay (and stored as JSON `false` with a fractional one) and now rejects, is passed as nil, so it is dropped at any delay. `spec/integration/connection_failure_spec.rb` now asserts the mid-reset connection is recovered at checkout (it failed on 0.8.2), in place of the two examples that pinned the old last-retry recovery. Refs #656.
8
+
9
+ ### Fixed
10
+
11
+ - **A pooled connection in `connection_guc_mode = :session` keeps its database.yml `variables` when it is reset (issue #671).** In `:session` mode the `variables` (`statement_timeout`, `lock_timeout` and the like) are applied with `SET` after connect, and `PG::Connection#reset` opens a new backend without them. pgmq-ruby's checkout health check resets an unhealthy pooled connection (`finished?` or `CONNECTION_BAD` since #332, and an intermediate state such as `CONNECTION_STARTED` since pgmq-ruby 0.9.0), so that connection went on serving the job or streams pool with the server's defaults. Each connection the `:session` connect lambda opens now re-applies its `SET`s when it is reset, whoever resets it. A connection whose `SET`s do not all complete, after a connect or a reset, is closed before the error reaches the caller, so it is never pooled without them; with pg 1.5.9 or later the next checkout resets it and applies the `SET`s again (an older pg cannot reset a closed connection, so it is replaced when the pool is reloaded before the last stale-connection retry; the call itself is retried only for a stale-connection error, so a `SET` that always fails, such as an invalid value, fails each time). The completion pipeline's own reset (#619) no longer applies the `SET`s itself (they ran twice), and a `SET` that fails there is now logged as `Resetting the connection or re-applying its session variables failed` and leaves the connection closed, where before the session carried on without its `variables`. `:options` mode, a String URL and the shared ActiveRecord connection are unaffected. Refs #671.
12
+
13
+ ## [0.25.1] - 2026-11-15
6
14
 
7
15
  ### Changed
8
16
 
@@ -12,6 +20,12 @@
12
20
 
13
21
  - **A presence table without the seat columns is reported, and its schema probe backs off (issue #665).** `Pgbus::Streams::Presence.seats_supported?` kept a "no seats" answer for 30 s, so an app that upgraded without running `rails g pgbus:add_presence_seats` queried `information_schema.columns` twice a minute per process, forever, and nothing said why. A "no" is now kept for 30 s, then twice as long after each further "no", up to 10 minutes (`SCHEMA_RECHECK_MAX_SECONDS = 600`); a true answer is still kept for the life of the process, `reset_schema_cache!` still re-probes at once and starts the backoff again from 30 s, and two threads that probe at the same moment count as one step. The backoff holds in a process that makes no member-keyed `leave`, `touch` or `sweep!`: each of those still re-probes a cached "no" before it runs, because it would delete or refresh seat rows on a table migrated under the process, and restarts the backoff at 30 s. Connection-driven presence on such a table still touches once per connection per heartbeat, unchanged here (#666). A member-keyed `join` that hits the migrated index still re-probes at once. The first "no" logs one warning per process naming the fix (`rails generate pgbus:add_presence_seats && rails db:migrate`). `pgbus doctor` has a fifteenth check, `Presence seats`: a warning with the same fix when `pgbus_presence_members` exists without `connection_id`, ok when the column exists or presence is not installed; it runs in the boot preflight and never blocks a strict boot. New `Pgbus::Streams::Presence.seats_state` (`:absent`, `:missing`, `:present`), read on the connection presence uses. Refs #665.
14
22
 
23
+ ## [0.25.0] - 2026-11-14
24
+
25
+ ### Added
26
+
27
+ - **Deploy tasks: `after:` makes a task wait until the tasks it names have completed, and every run records its outcome (issue #660).** `after:` takes a task key or a list of keys declared in the loaded configuration (any of `deploy_tasks_files`). The scheduler keeps such a task armed, and does not enqueue it, until each named task has a run with `completed_at` at its current version (any revision; an `every_deploy` dependency needs one on this revision). A rollover run and a Run now run both count, so a failed dependency that an operator fixes and runs again with Run now unblocks its dependents without a new deploy. A waiting task records no failure and no backoff, and fires on the first tick after its last dependency completes; the check is one query per tick, made only while an armed task has dependencies. At scheduler boot a task whose `after:` names an unknown key (`after: unknown task 'x'`), sits on a cycle (`after: cycle a → b → a`, a self-reference included), or names a task that is itself skipped (`after: 'x' is skipped`) is skipped with a warning. Run outcomes: `Deploy::Runner#enqueue` now creates the `pgbus_deploy_task_runs` row before the enqueue and passes its id in the job payload under `pgbus_deploy_task_run_id` (`Pgbus::ActiveJob::DeployTaskRunId`, included on `ActiveJob::Base` next to `BatchId`; an unmarked job's payload is unchanged), fills in `queue_name` and `msg_id` after it, and deletes the row when the enqueue fails. The executor stamps `completed_at` when `perform` returned having done its work without re-enqueuing the job (a `retry_on` attempt whose retry is queued, or a `discard_on` block that queues one, leaves it to the retry; a job that rescues inside `perform` and returns has completed) and `failed_at` when ActiveJob discarded the job without queuing a retry (`discard_on`, with or without a block, or a `retry_on` that gave up through its block, where one without a block re-raises and ends dead-lettered as before; `Pgbus::ActiveJob::DeployTaskRunId` marks the instance in ActiveJob's `run_after_discard_procs`, after the job's own `after_discard` procs, so a discarded dependency reads `failed` and its dependents keep waiting, issue #662), when the job is dead-lettered, discarded as a `:while_executing` duplicate, or its retry never left (dropped by its own concurrency limit, `on_conflict: :discard`, or aborted by a `before_enqueue` callback); a failed write is reported and never fails the job, and a job without the key pays one Hash lookup. An enqueue the job's own `on_conflict: :discard` / `:log` drops now counts as a failed enqueue (the run is deleted and the task re-armed with backoff). A run row without `queue_name` (its enqueue never finished) does not count as a run, so the version stays owed. The dispatcher's pruning keeps the newest completed run per task and version. Dashboard: a task's state says "Waiting for N dependencies to complete" and lists each one as `not run`, `running` or `failed`; the task page shows `after:` and an Outcome column in the run history; Run now on a waiting task is refused with a flash naming the dependencies (`DataSource#enqueue_deploy_task_now(id, ignore_dependencies: false)` returns `:blocked`) unless "Ignore dependencies" is ticked on the task page. `pgbus_deploy_tasks` (MCP) lists `dependencies` and `waiting_on`. New generator `pgbus:add_deploy_task_run_outcomes` adds `pgbus_deploy_task_runs.completed_at` / `failed_at`, `pgbus_deploy_tasks.dependencies` and an index on `(task_key, completed_at)`; `pgbus:update` queues it, and fresh `pgbus:install` / `pgbus:add_deploy_tasks` include the columns. Until it is migrated, a task with `after:` is skipped with a warning naming the generator and no outcome is written. **Upgrade note:** runs recorded before the migration have no outcome and satisfy nothing, so when an `after:` names a task whose only runs predate the upgrade, Run now that task once (or bump its version; an `every_deploy` dependency needs a run on the current revision, so only Run now helps). Delivery stays at-least-once: a scheduler that dies between claiming a task and enqueuing it leaves the task unarmed until the next scheduler boot re-arms it, and a run whose enqueue could not be recorded runs again after one, so deploy tasks must be idempotent. Refs #660.
28
+
15
29
  ## [0.24.0] - 2026-11-11
16
30
 
17
31
  ### Added
data/README.md CHANGED
@@ -553,7 +553,7 @@ A custom RuboCop cop, `Pgbus/NoRubyTimeout`, bans `Timeout.timeout` project-wide
553
553
 
554
554
  ### Stale connection retries
555
555
 
556
- A `PGMQ::Errors::ConnectionError` whose message says the pooled connection was dead before it was used (`no connection to the server`, `connection is closed`, a PgBouncer-closed socket and the like) is retried twice, after about 0.1 s and 0.5 s. Errors that may have reached the server (`server closed the connection unexpectedly`) and pool timeouts are never retried. The first retry relies on pgmq-ruby's checkout health check, which replaces a closed connection. On a dedicated connection (`database_url` or `connection_params`), before the last retry, pgbus drops the idle connections of both pools (job and streams) and logs `Dropping pooled connections before the last stale-connection retry`. This recovers a connection the health check keeps handing out, such as one a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`). A read interrupted by the Ruby `Timeout` fallback above reloads the job pool the same way. `Pgbus.client.reload` drops the idle connections of both pools by hand. None of these reload anything on the shared ActiveRecord `Proc` connection, whose socket pgbus does not own.
556
+ A `PGMQ::Errors::ConnectionError` whose message says the pooled connection was dead before it was used (`no connection to the server`, `connection is closed`, a PgBouncer-closed socket and the like) is retried twice, after about 0.1 s and 0.5 s. Errors that may have reached the server (`server closed the connection unexpectedly`) and pool timeouts are never retried. The first retry relies on pgmq-ruby's checkout health check, which resets a pooled connection that is not healthy: one the server closed, or one a `Thread#raise` left half-way through a reset (`CONNECTION_STARTED`, recovered at checkout since pgmq-ruby 0.9.0). On a dedicated connection (`database_url` or `connection_params`), before the last retry, pgbus drops the idle connections of both pools (job and streams) and logs `Dropping pooled connections before the last stale-connection retry`. This recovers a connection that still fails after the health check passed it. A read interrupted by the Ruby `Timeout` fallback above reloads the job pool the same way. `Pgbus.client.reload` drops the idle connections of both pools by hand. None of these reload anything on the shared ActiveRecord `Proc` connection, whose socket pgbus does not own. With `connection_guc_mode: :session` and database.yml `variables`, a connection the health check resets comes back without its session `SET`s (#671).
557
557
 
558
558
  ### Prefetch flow control
559
559
 
@@ -1962,7 +1962,7 @@ Pgbus.configure do |c|
1962
1962
  end
1963
1963
  ```
1964
1964
 
1965
- Keep each ttl above `streams_heartbeat_interval` (pgbus warns at boot otherwise): a shorter one expires live seats between touches. On a seat table `sweep!` only expires member-keyed rows; seats expire through the heartbeat. A process that probed the table before the migration re-checks after 30 seconds, then after twice as long each time it still finds no seats, up to every 10 minutes. A member-keyed `leave`, `touch` or `sweep!` re-checks before it runs and starts that backoff again at 30 seconds, and a member-keyed `join` outside a transaction re-checks at once if it hits the new index. The first time it finds no seats it logs one warning naming the migration, and `pgbus doctor` warns under `Presence seats`; restart the processes after migrating to pick the columns up at once. A raising hook is logged, not propagated. Library authors can probe for seat support with `Pgbus::Streams::Presence.instance_method(:join).parameters.include?([:key, :connection_id])` (the gem) and `Pgbus::Streams::Presence.seats_supported?` (the table).
1965
+ Keep each ttl above `streams_heartbeat_interval` (pgbus warns at boot otherwise): a shorter one expires live seats between touches. On a seat table `sweep!` only expires member-keyed rows; seats expire through the heartbeat. A process that probed the table before the migration re-checks after 30 seconds, then after twice as long each time it still finds no seats, up to every 10 minutes. A member-keyed `leave` or `sweep!` does not trust a cached "no": it re-checks once before it runs. Over a "no" that is not yet due, that re-check leaves the backoff's schedule alone; over one that is due, it is the timed re-check, and the wait doubles as usual. A member-keyed `touch` (the streamer's heartbeat touch included) only re-checks on that schedule: on a table migrated under a running process it can keep that member's seat rows fresh until the next re-check, at most 10 minutes later, and deletes nothing. A member-keyed `join` outside a transaction re-checks at once if it hits the new index. The first time it finds no seats it logs one warning naming the migration, and `pgbus doctor` warns under `Presence seats`; restart the processes after migrating to pick the columns up at once. A raising hook is logged, not propagated. Library authors can probe for seat support with `Pgbus::Streams::Presence.instance_method(:join).parameters.include?([:key, :connection_id])` (the gem) and `Pgbus::Streams::Presence.seats_supported?` (the table).
1966
1966
 
1967
1967
  ### Stream stats (opt-in)
1968
1968
 
@@ -103,8 +103,11 @@ module Pgbus
103
103
  # A connection back in the pool in pipeline mode would break the next
104
104
  # caller. A lost one is left as it is: pgmq-ruby resets a bad connection
105
105
  # at its next checkout, and a reset leaves pipeline mode. One that cannot
106
- # leave (results left unread by an interrupted read) is reset here.
106
+ # leave (results left unread by an interrupted read) is reset here. One
107
+ # a failed reset closed (its :session SETs failed, SessionGucs) is left
108
+ # closed too: pgmq-ruby resets it at the next checkout.
107
109
  def leave_pipeline(conn)
110
+ return if conn.finished?
108
111
  return if conn.pipeline_status == PG::PQ_PIPELINE_OFF || conn.status == PG::CONNECTION_BAD
109
112
 
110
113
  conn.exit_pipeline_mode
@@ -116,32 +119,24 @@ module Pgbus
116
119
  # fails (the server is gone) is logged and left there, so the error the
117
120
  # caller is already raising is the one that surfaces; pgmq-ruby resets a
118
121
  # bad connection at its next checkout.
119
- # A reset reconnects with the same conninfo (the read bounds ride in it)
120
- # but does not re-run the connect lambda, so the :session-mode SETs are
121
- # applied again here.
122
+ # A reset reconnects with the same conninfo (the read bounds ride in it);
123
+ # in :session GUC mode the connection's own reset applies the SETs again
124
+ # and closes it when they fail (SessionGucs, issue #671).
122
125
  def discard_session(conn, reason)
123
126
  Pgbus.logger.warn { "[Pgbus::Client] #{reason}, resetting the connection" }
124
- begin
125
- conn.reset
126
- rescue PG::Error => e
127
- Pgbus.logger.warn { "[Pgbus::Client] Resetting the connection failed: #{e.message}" }
128
- return
129
- end
130
- reapply_session_gucs(conn)
131
- end
132
-
133
- def reapply_session_gucs(conn)
134
- apply_session_gucs(conn, @session_gucs) if @session_gucs
127
+ conn.reset
135
128
  rescue PG::Error => e
136
129
  Pgbus.logger.warn do
137
- "[Pgbus::Client] Re-applying the session's database.yml variables after the reset failed: #{e.message}"
130
+ "[Pgbus::Client] Resetting the connection or re-applying its session variables failed: #{e.message}"
138
131
  end
139
132
  end
140
133
 
141
134
  # The failed BEGIN block (INERROR) is still open after the sync. A failed
142
135
  # COMMIT has already ended it (IDLE); a lost connection reports UNKNOWN
143
- # and has nothing to roll back.
136
+ # and has nothing to roll back, as does one a reset closed.
144
137
  def rollback_async_commit(conn)
138
+ return if conn.finished?
139
+
145
140
  conn.exec("ROLLBACK") if [PG::PQTRANS_INERROR, PG::PQTRANS_INTRANS].include?(conn.transaction_status)
146
141
  end
147
142
  end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pgbus
4
+ class Client
5
+ # The database.yml variables that connection_guc_mode :session applies with
6
+ # SET after connect (issue #332), on every session a pooled connection has.
7
+ #
8
+ # PG::Connection#reset opens a new backend from the same conninfo and does
9
+ # not replay the SETs. pgmq-ruby resets an unhealthy pooled connection at
10
+ # checkout (finished?, CONNECTION_BAD, and since 0.9.0 an intermediate
11
+ # state such as CONNECTION_STARTED), and AsyncCommit#discard_session resets
12
+ # one whose pipeline state cannot be trusted. So each connection #connect
13
+ # opens is extended with this module, whose #reset (and #async_reset,
14
+ # #sync_reset) applies the SETs again (issue #671).
15
+ #
16
+ # A connection whose SETs did not all complete is closed before the error
17
+ # propagates: it is never pooled CONNECTION_OK without them. The next
18
+ # checkout sees it finished? and resets it, which tries again (pg 1.5.9 and
19
+ # later reset a closed connection; an older pg raises, and the pool reload
20
+ # before the last stale-connection retry replaces it).
21
+ #
22
+ # One instance per pool, built at Client construction; it holds only the
23
+ # SET statements, in a frozen array nothing mutates, so concurrent
24
+ # connections share it safely.
25
+ class SessionGucs < Module
26
+ def initialize(variables)
27
+ super()
28
+ statements = variables.map { |name, value| "SET #{name} = '#{value}'" }.freeze
29
+
30
+ # Runs the block (a reset, or nothing after a connect), then the SETs.
31
+ # One ensure covers both, so an async raise between the reset and the
32
+ # first SET also closes the connection.
33
+ define_method(:pgbus_with_session_gucs) do |&before|
34
+ applied = false
35
+ before&.call
36
+ statements.each { |sql| exec(sql) }
37
+ applied = true
38
+ self
39
+ ensure
40
+ close unless applied || finished?
41
+ end
42
+
43
+ # pg's async_reset is an alias bound to PG::Connection#reset and its
44
+ # sync_reset is C, so a hook on reset alone would not see either. None
45
+ # of the three calls another, so each reset applies the SETs once.
46
+ %i[reset async_reset sync_reset].each do |name|
47
+ define_method(name) do
48
+ pgbus_with_session_gucs { super() }
49
+ end
50
+ end
51
+ end
52
+
53
+ def connect(pg_opts)
54
+ PG.connect(pg_opts).extend(self).pgbus_with_session_gucs
55
+ end
56
+ end
57
+ end
58
+ end
data/lib/pgbus/client.rb CHANGED
@@ -138,9 +138,6 @@ module Pgbus
138
138
  # safe on this dedicated-connection branch — never on the shared-AR Proc
139
139
  # path, where statement_timeout would leak into application queries.
140
140
  conn_opts = apply_connection_bounds(conn_opts)
141
- # What the connect lambda SETs per session (:session GUC mode), kept so
142
- # a session reset after a failed completion pipeline gets it again.
143
- @session_gucs = session_gucs(conn_opts)
144
141
  conn_opts = wrap_session_gucs(conn_opts)
145
142
  @pgmq = PGMQ::Client.new(conn_opts, pool_size: config.resolved_pool_size, pool_timeout: config.pool_timeout)
146
143
  @pgmq_mutex = nil
@@ -1123,7 +1120,9 @@ module Pgbus
1123
1120
  @pgmq.produce_topic(
1124
1121
  routing_key,
1125
1122
  serialize(payload),
1126
- headers: headers && serialize(headers),
1123
+ # pgmq-ruby 0.9.0 rejects headers that are neither a String nor
1124
+ # nil; `false` was dropped before and still is.
1125
+ headers: headers ? serialize(headers) : nil,
1127
1126
  delay: delay
1128
1127
  )
1129
1128
  end
@@ -1896,15 +1895,15 @@ module Pgbus
1896
1895
  # still gets a second, backed-off chance rather than failing an enqueue
1897
1896
  # the caller may never retry.
1898
1897
  #
1899
- # The last retry runs on freshly reloaded pools (issue #645). A reset that
1900
- # Thread#raise interrupted mid-poll leaves the pooled PG::Connection in
1901
- # CONNECTION_STARTED: neither finished? nor CONNECTION_BAD, so pgmq-ruby's
1902
- # checkout health check keeps handing it out and libpq refuses every send
1903
- # ("no connection to the server"). The first retry still goes through that
1904
- # health check alone, which replaces a socket the server closed without
1905
- # touching the rest of the pool; only when it fails too are both pools'
1906
- # idle connections dropped (reload_pools_before_last_stale_retry), as the
1907
- # #354 wedged-read path does.
1898
+ # The last retry runs on freshly reloaded pools (issue #645). The first
1899
+ # retry goes through pgmq-ruby's checkout health check alone, which resets
1900
+ # a socket the server closed without touching the rest of the pool, and
1901
+ # since pgmq-ruby 0.9.0 also a connection left in any other non-OK state,
1902
+ # such as the CONNECTION_STARTED a reset interrupted by Thread#raise leaves
1903
+ # (before 0.9.0 that one was handed out again and libpq refused every send,
1904
+ # "no connection to the server"). Only when the first retry fails too are
1905
+ # both pools' idle connections dropped
1906
+ # (reload_pools_before_last_stale_retry), as the #354 wedged-read path does.
1908
1907
  STALE_RETRY_ATTEMPTS = 2
1909
1908
  private_constant :STALE_RETRY_ATTEMPTS
1910
1909
 
@@ -1987,7 +1986,8 @@ module Pgbus
1987
1986
  # WEDGED-SOCKET RECOVERY (issue #354): when (3) fires on a genuinely
1988
1987
  # hung socket, libpq may leave the pooled PG::Connection reporting
1989
1988
  # CONNECTION_OK while it will in fact re-hang on reuse, and pgmq-ruby's
1990
- # checkout health check won't discard it (it isn't CONNECTION_BAD). So
1989
+ # checkout health check won't discard it (it still reports
1990
+ # CONNECTION_OK). So
1991
1991
  # the Timeout raises WedgedReadTimeout (a ReadTimeoutError subclass)
1992
1992
  # and the rescue below drops every pooled connection via @pgmq.reload
1993
1993
  # (pgmq-ruby >= 0.7.1) — the pool rebuilds lazily on next checkout.
@@ -2201,17 +2201,15 @@ module Pgbus
2201
2201
  # PG::Connection each call (pgmq guards against a shared object). Applies to
2202
2202
  # a Hash with `:variables` only — a String URL or no variables passes through
2203
2203
  # unchanged, as does :options mode (where forward_connection_variables
2204
- # already baked the GUCs into `options`). See issue #332.
2204
+ # already baked the GUCs into `options`). See issue #332. Each connection
2205
+ # re-applies the SETs when it is reset (issue #671, SessionGucs).
2205
2206
  def wrap_session_gucs(conn_opts)
2206
2207
  variables = session_gucs(conn_opts)
2207
2208
  return conn_opts unless variables
2208
2209
 
2209
2210
  pg_opts = conn_opts.except(:variables)
2210
- lambda do
2211
- conn = PG.connect(pg_opts)
2212
- apply_session_gucs(conn, variables)
2213
- conn
2214
- end
2211
+ gucs = SessionGucs.new(variables)
2212
+ -> { gucs.connect(pg_opts) }
2215
2213
  end
2216
2214
 
2217
2215
  # The database.yml variables :session GUC mode applies with SET after
@@ -2223,10 +2221,6 @@ module Pgbus
2223
2221
  variables unless variables.nil? || variables.empty?
2224
2222
  end
2225
2223
 
2226
- def apply_session_gucs(conn, variables)
2227
- variables.each { |name, value| conn.exec("SET #{name} = '#{value}'") }
2228
- end
2229
-
2230
2224
  def apply_connection_bounds(conn_opts)
2231
2225
  timeout = config.read_timeout
2232
2226
  return conn_opts unless timeout&.positive?
@@ -114,26 +114,31 @@ module Pgbus
114
114
  end
115
115
  return cached unless cached.nil?
116
116
 
117
- rows = exec_params(<<~SQL, [])
118
- SELECT 1 AS present FROM information_schema.columns
119
- WHERE table_name = 'pgbus_presence_members' AND column_name = 'connection_id'
120
- AND table_schema = ANY (current_schemas(false))
121
- SQL
122
- supported = !rows.to_a.empty?
123
- answer, warn = store_schema_answer(supported, generation)
124
- warn_seats_missing if warn
125
- answer
117
+ probe_seats(generation)
126
118
  end
127
119
 
128
- # seats_supported?, but a cached "no seats" is probed again first.
129
- # For the destructive member-keyed statements: on a table migrated
130
- # under this process their SQL without `connection_id IS NULL`
131
- # succeeds silently and deletes seat rows.
120
+ # seats_supported?, but a cached "no seats" is not trusted: anything
121
+ # short of a cached true is probed, once, and this probe's own answer
122
+ # is returned. For the destructive member-keyed statements (leave,
123
+ # sweep!): on a table migrated under this process their SQL without
124
+ # `connection_id IS NULL` succeeds silently and deletes seat rows.
125
+ #
126
+ # Its "no" is stored like any probe's (issue #666): over a fresh "no"
127
+ # it changes nothing, so the backoff keeps its step and its schedule
128
+ # however many calls force a probe; over a stale or missing answer it
129
+ # is the timed re-check, one step. A reset_schema_cache! during the
130
+ # probe (a join that hit the migrated index) means its "no" may
131
+ # predate the migration, so it probes again.
132
132
  def seats_supported_now?
133
- return true if seats_supported?
133
+ loop do
134
+ cached, generation = @schema_mutex.synchronize do
135
+ [@seats_supported == true && schema_answer_fresh?(true, @probed_at, @recheck_seconds), @schema_generation]
136
+ end
137
+ return true if cached
134
138
 
135
- reset_schema_cache!
136
- seats_supported?
139
+ answer = probe_seats(generation)
140
+ return answer if answer || @schema_mutex.synchronize { generation == @schema_generation }
141
+ end
137
142
  end
138
143
 
139
144
  def reset_schema_cache!
@@ -247,6 +252,20 @@ module Pgbus
247
252
  nil
248
253
  end
249
254
 
255
+ # Probes the schema (outside @schema_mutex, issue #566), stores the
256
+ # answer and returns the answer to give.
257
+ def probe_seats(generation)
258
+ rows = exec_params(<<~SQL, [])
259
+ SELECT 1 AS present FROM information_schema.columns
260
+ WHERE table_name = 'pgbus_presence_members' AND column_name = 'connection_id'
261
+ AND table_schema = ANY (current_schemas(false))
262
+ SQL
263
+ supported = !rows.to_a.empty?
264
+ answer, warn = store_schema_answer(supported, generation)
265
+ warn_seats_missing if warn
266
+ answer
267
+ end
268
+
250
269
  def schema_answer_fresh?(supported, probed_at, recheck_seconds)
251
270
  return false if supported.nil? || probed_at.nil?
252
271
 
@@ -257,9 +276,10 @@ module Pgbus
257
276
  # Returns the answer to give and whether to log the missing-seats
258
277
  # warning (the first "no" of the process).
259
278
  #
260
- # A "no" over a fresh "no" (two threads probed at once) keeps the
261
- # first one's time and step, so concurrent probes are one step. A
262
- # true answer is never taken back.
279
+ # A "no" over a fresh "no" (two threads probed at once, or a forced
280
+ # probe from seats_supported_now?) keeps the first one's time and
281
+ # step, so concurrent and forced probes add no step. A true answer is
282
+ # never taken back.
263
283
  def store_schema_answer(supported, generation)
264
284
  @schema_mutex.synchronize do
265
285
  next [supported, false] unless generation == @schema_generation
@@ -416,6 +436,12 @@ module Pgbus
416
436
  # to stay in the member list, and a sweeper expires anyone who
417
437
  # hasn't pinged in N seconds.
418
438
  #
439
+ # Member-keyed, it trusts the cached schema answer (issue #666): the
440
+ # streamer touches once per connection per heartbeat. On a table
441
+ # migrated under this process it may also refresh that member's seat
442
+ # rows until the answer is re-checked (at most
443
+ # SCHEMA_RECHECK_MAX_SECONDS); it never deletes anything.
444
+ #
419
445
  # With `connection_id:` (a String or an Array of them) it refreshes
420
446
  # those connections' seat rows in one statement and returns the ids
421
447
  # it found — a missing id means the row was expired while the
@@ -429,7 +455,7 @@ module Pgbus
429
455
  exec_params(<<~SQL, [@stream.name, member_id])
430
456
  UPDATE pgbus_presence_members
431
457
  SET last_seen_at = NOW()
432
- WHERE stream_name = $1 AND member_id = $2#{" AND connection_id IS NULL" if seats_now?}
458
+ WHERE stream_name = $1 AND member_id = $2#{" AND connection_id IS NULL" if seats?}
433
459
  SQL
434
460
  end
435
461
 
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.25.1"
4
+ VERSION = "0.26.1"
5
5
  end
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.25.1
4
+ version: 0.26.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson
@@ -63,14 +63,14 @@ dependencies:
63
63
  requirements:
64
64
  - - "~>"
65
65
  - !ruby/object:Gem::Version
66
- version: 0.8.2
66
+ version: 0.9.0
67
67
  type: :runtime
68
68
  prerelease: false
69
69
  version_requirements: !ruby/object:Gem::Requirement
70
70
  requirements:
71
71
  - - "~>"
72
72
  - !ruby/object:Gem::Version
73
- version: 0.8.2
73
+ version: 0.9.0
74
74
  - !ruby/object:Gem::Dependency
75
75
  name: railties
76
76
  requirement: !ruby/object:Gem::Requirement
@@ -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