pgbus 0.13.6 → 0.13.7

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: 65404b35486048a6edc37551a47d482d4e92e76f462ba930196b81473f5f304e
4
- data.tar.gz: 90bb9c64bc3fbc9b7a920da9f2bf5b8c3caaa0ff273ae05fecdbf5bc0f8a35f0
3
+ metadata.gz: 36e4016b7a3103001ac29bb75d10c949b7cc8866a1ef511ad64a1ca61643e14a
4
+ data.tar.gz: 96897f60545b8ac14ec13d1cf267fecf408e690badb41973e0c9f7a9eb6967c3
5
5
  SHA512:
6
- metadata.gz: 68bbec64ec3e81a979caf0b5e6bb2fda4aef6b658084aa47041b33e25f1c0a6d84d7643780e0c9c9f50db3fc18a5f437778bcf5159c45328046568a4bc3c899c
7
- data.tar.gz: 40847bed714c4de82160d1ade8ca7c992612d363f8c59ee0c5d1eb30c4fccb1ac98b8e099e723247e9758474a2bd60864dac98eabc611ec9a466ba3ac89020f2
6
+ metadata.gz: 64601019ee0ffebe7babed1295b471aed0a116ee68efa25e11216c0709a3e217a31020e0d4f99abee78b17891f794d679db54bef293b2b1193815cc4df3cb721
7
+ data.tar.gz: 1524b6c8e4434d81e433c1a550259c44e5e47c308fbd594ae1777ae22472040504b97e173e9d4a2b11102ba1a7a79ab52ad7dd7c9efcc12c16f007cd48f779fb
data/CHANGELOG.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  ### Fixed
4
4
 
5
+ - **The schema-install transaction framing no longer commits or destroys a caller's open transaction (#398 review follow-up).** The #397 fix wrapped check+install in `BEGIN`…`COMMIT`/`ROLLBACK` unconditionally. On the Proc-supplied shared-connection path (the Rails lambda), the connection can arrive **mid-transaction** — e.g. `perform_later` inside an application `transaction do` block — where `BEGIN` is a warning-level no-op and the matching `COMMIT`/`ROLLBACK` then commits half of, or destroys, the *caller's* transaction. The framing is now `transaction_status`-aware: an idle connection gets the owned `BEGIN`…`COMMIT` as before; a connection already inside a transaction rides it via `SAVEPOINT pgbus_pgmq_install` / `RELEASE` (`ROLLBACK TO SAVEPOINT` on failure), so the caller's transaction is never touched. On the savepoint path the advisory lock joins the caller's transaction and is held until it ends — over-holding only delays a concurrent installer, never corrupts it — and `@schema_ensured` is NOT cached there: the install is only durable once the caller commits, so a cached true after an outer rollback would skip every future check against a missing schema. The same durability rule now governs `@queues_created`: queue DDL on the shared Proc-supplied connection joins the caller's open transaction, so queue creation there runs uncached (idempotent `CREATE IF NOT EXISTS`) and the next ensure re-checks — a cache write outliving a caller rollback would make later message operations fail against a missing queue. All shared-connection access in these paths — including the transaction-status probe and the schema install itself — holds the per-instance connection mutex, restoring the single-owner invariant the #397 fix had narrowed. Refs #398.
6
+
5
7
  - **PGMQ schema installation is now race-safe across clients and processes (issue #397).** `ensure_pgmq_schema` guarded check+install with `@schema_ensured` + `synchronized` — both per-instance, and `synchronized` is a no-op on the dedicated-connection path — so two Client instances (or two threads on the dedicated path) could install concurrently. The loser's `PG::UniqueViolation` (`Key (nspname)=(pgmq) already exists`) surfaced as `SchemaNotReady` even though the schema was fine, and on the shared-AR Proc path — where two instances each hold their *own* mutex around one shared libpq connection — the concurrent install traffic desynced the protocol (`message type 0x… arrived from server while idle`) and left a thread blocked on a socket read forever (downstream forensics: a CI shard going silent until the merge queue's timeout evicted the PR, getzazu/app#3413). Three changes: **(1)** schema bootstrap is serialized process-wide through a class-level mutex, not per-instance state; **(2)** check+install runs inside one explicit transaction holding `pg_advisory_xact_lock` on a fixed key (`Pgbus::Client::PGMQ_INSTALL_LOCK_KEY`), serializing installers across processes — xact-scoped so the lock releases itself at COMMIT/ROLLBACK and stays safe through transaction-pooling poolers, where a session lock's unlock could land on a different server connection; **(3)** a duplicate-object install failure (`PG::UniqueViolation`, `PG::DuplicateSchema`, `PG::DuplicateTable`, `PG::DuplicateObject`, `PG::DuplicateFunction` — a process without the advisory lock, e.g. older pgbus or the extension path, won the race) is rescued by re-checking `pgmq.meta`: present means proceed as installed, absent means the original error is re-raised wrapped in `SchemaNotReady`. Refs #397.
6
8
 
7
9
  - **SSE delivery no longer strips newlines from broadcast payloads — multiline payloads are framed as consecutive `data:` lines per the SSE spec (issue #392).** `Streams::Envelope.message` collapsed `\r`/`\n` in the payload to nothing before writing the single `data:` line, silently corrupting any whitespace-significant broadcast (pre-formatted `<pre>` content, textarea seeds, JSON-in-data frames) on **both** the ephemeral and durable delivery paths — HTML's whitespace tolerance is why it went unnoticed. A multiline payload is now split on `\r\n`/`\r`/`\n` into consecutive `data:` lines, which EventSource clients rejoin with `\n`, making delivery lossless (a trailing newline survives via an empty final `data:` line; `\r` variants normalize to `\n` — SSE line terminators cannot be carried raw). The original injection defense is preserved: every payload line carries the `data:` prefix followed by one space, so a crafted payload still cannot forge `id:`/`event:` fields, and single-line fields (event names, comments) still strip newlines. The `<pgbus-stream-source>` element's fetch-path parser had the matching client-side bug — it joined `data:` lines without `\n` *and* `trim()`ed payload whitespace — and now follows EventSource semantics (join with `\n`, strip only the single leading space). Refs #392.
data/lib/pgbus/client.rb CHANGED
@@ -28,6 +28,9 @@ module Pgbus
28
28
  PGMQ_META_CHECK_SQL = "SELECT 1 FROM pg_tables WHERE schemaname = 'pgmq' AND tablename = 'meta' LIMIT 1"
29
29
  private_constant :PGMQ_META_CHECK_SQL
30
30
 
31
+ PGMQ_INSTALL_SAVEPOINT = "pgbus_pgmq_install"
32
+ private_constant :PGMQ_INSTALL_SAVEPOINT
33
+
31
34
  # Install-race losers see the winner's DDL as one of these. Matched by
32
35
  # class NAME so the check works whether or not the pg gem's generated
33
36
  # error classes are loaded in this process (mirrors the defined?(PG::…)
@@ -320,12 +323,13 @@ module Pgbus
320
323
  dlq_name = config.dead_letter_queue_name(name)
321
324
  return if @queues_created[dlq_name]
322
325
 
323
- @queues_created.compute_if_absent(dlq_name) do
324
- synchronized do
325
- @pgmq.create(dlq_name)
326
- tune_autovacuum(dlq_name)
326
+ if queue_ddl_rides_caller_transaction?
327
+ create_dead_letter_queue_physically(dlq_name)
328
+ else
329
+ @queues_created.compute_if_absent(dlq_name) do
330
+ create_dead_letter_queue_physically(dlq_name)
331
+ true
327
332
  end
328
- true
329
333
  end
330
334
  end
331
335
 
@@ -976,8 +980,29 @@ module Pgbus
976
980
  self.class.pgmq_install_mutex.synchronize do
977
981
  return if @schema_ensured
978
982
 
979
- with_raw_connection { |raw_conn| install_pgmq_schema_serialized(raw_conn) }
980
- @schema_ensured = true
983
+ # Cache only a durable result: true only when this call owned the
984
+ # COMMIT. A savepoint-path ensure rides the CALLER's transaction — if
985
+ # that later rolls back the schema is gone (and even a schema found
986
+ # already-present there may be the caller's own uncommitted work), so
987
+ # a cached true would skip every future check (#399 review).
988
+ #
989
+ # synchronized (the per-instance connection mutex) nests INSIDE the
990
+ # class-level install mutex — that lock order is safe because no path
991
+ # acquires them the other way round — so the shared Proc connection is
992
+ # never touched while another thread of this instance is mid-operation
993
+ # on it (single-owner invariant; #399 review).
994
+ durable = synchronized do
995
+ with_raw_connection do |raw_conn|
996
+ if inside_caller_transaction?(raw_conn)
997
+ install_pgmq_schema_in_savepoint(raw_conn)
998
+ false
999
+ else
1000
+ install_pgmq_schema_in_own_transaction(raw_conn)
1001
+ true
1002
+ end
1003
+ end
1004
+ end
1005
+ @schema_ensured = true if durable
981
1006
  end
982
1007
  rescue StandardError => e
983
1008
  raise Pgbus::SchemaNotReady,
@@ -985,30 +1010,64 @@ module Pgbus
985
1010
  "Ensure the pgbus database exists and migrations have been run."
986
1011
  end
987
1012
 
988
- # Check-and-install inside one transaction holding a fixed advisory lock:
989
- # pg_advisory_xact_lock serializes installers across processes and releases
990
- # itself at COMMIT/ROLLBACK — safe through transaction-pooling poolers,
991
- # where a session-level lock could be released on a different server
992
- # connection than the one that acquired it (issue #397).
993
- def install_pgmq_schema_serialized(conn)
1013
+ # Check-and-install under a fixed advisory lock: pg_advisory_xact_lock
1014
+ # serializes installers across processes and releases itself when its
1015
+ # transaction ends — safe through transaction-pooling poolers, where a
1016
+ # session-level lock could be released on a different server connection
1017
+ # than the one that acquired it (issue #397).
1018
+ #
1019
+ # The transactional framing must respect who owns the transaction. A
1020
+ # Proc-supplied shared connection (the Rails-lambda path) can arrive
1021
+ # mid-transaction — e.g. perform_later inside an application
1022
+ # `transaction do` block. BEGIN there is a warning-level no-op, and the
1023
+ # matching COMMIT/ROLLBACK would then commit or destroy the CALLER's
1024
+ # transaction (#398 review). So: own the transaction only when the
1025
+ # connection is idle; ride the caller's transaction via a savepoint
1026
+ # otherwise.
1027
+ #
1028
+ # respond_to? guard: a Proc can hand back any connection-shaped object;
1029
+ # only a real PG::Connection reports transaction_status (and its presence
1030
+ # guarantees the PG constants below are loaded).
1031
+ def inside_caller_transaction?(conn)
1032
+ conn.respond_to?(:transaction_status) && conn.transaction_status != PG::PQTRANS_IDLE
1033
+ end
1034
+
1035
+ def install_pgmq_schema_in_own_transaction(conn)
994
1036
  conn.exec("BEGIN")
995
1037
  conn.exec("SELECT pg_advisory_xact_lock(#{PGMQ_INSTALL_LOCK_KEY})")
996
1038
  install_pgmq_schema(conn) if conn.exec(PGMQ_META_CHECK_SQL).ntuples.zero?
997
1039
  conn.exec("COMMIT")
998
1040
  rescue StandardError => e
1041
+ recover_from_install_failure(conn, e, "ROLLBACK")
1042
+ end
1043
+
1044
+ # The advisory lock joins the CALLER's transaction here, so it is held
1045
+ # until that transaction ends — longer than the install needs, but xact
1046
+ # locks cannot be released early by design, and over-holding only delays
1047
+ # a concurrent installer, never corrupts it.
1048
+ def install_pgmq_schema_in_savepoint(conn)
1049
+ conn.exec("SAVEPOINT #{PGMQ_INSTALL_SAVEPOINT}")
1050
+ conn.exec("SELECT pg_advisory_xact_lock(#{PGMQ_INSTALL_LOCK_KEY})")
1051
+ install_pgmq_schema(conn) if conn.exec(PGMQ_META_CHECK_SQL).ntuples.zero?
1052
+ conn.exec("RELEASE SAVEPOINT #{PGMQ_INSTALL_SAVEPOINT}")
1053
+ rescue StandardError => e
1054
+ recover_from_install_failure(conn, e, "ROLLBACK TO SAVEPOINT #{PGMQ_INSTALL_SAVEPOINT}")
1055
+ end
1056
+
1057
+ def recover_from_install_failure(conn, error, rollback_sql)
999
1058
  begin
1000
- conn.exec("ROLLBACK")
1059
+ conn.exec(rollback_sql)
1001
1060
  rescue StandardError
1002
- # A connection broken enough to refuse ROLLBACK also fails the
1061
+ # A connection broken enough to refuse the rollback also fails the
1003
1062
  # re-check below, which surfaces the state honestly; re-raising the
1004
- # ROLLBACK error here would mask the original install failure.
1063
+ # rollback error here would mask the original install failure.
1005
1064
  end
1006
- raise e unless duplicate_install_error?(e)
1065
+ raise error unless duplicate_install_error?(error)
1007
1066
 
1008
1067
  # A process without the advisory lock (older pgbus, or the extension
1009
1068
  # path) won the install race — re-check instead of failing on its
1010
1069
  # success.
1011
- raise e if conn.exec(PGMQ_META_CHECK_SQL).ntuples.zero?
1070
+ raise error if conn.exec(PGMQ_META_CHECK_SQL).ntuples.zero?
1012
1071
  end
1013
1072
 
1014
1073
  def duplicate_install_error?(error)
@@ -1095,14 +1154,52 @@ module Pgbus
1095
1154
  def ensure_single_queue(full_name)
1096
1155
  return if @queues_created[full_name]
1097
1156
 
1098
- @queues_created.compute_if_absent(full_name) do
1099
- synchronized do
1100
- @pgmq.create(full_name)
1101
- tune_autovacuum(full_name)
1102
- enable_notify_if_needed(full_name, NOTIFY_THROTTLE_MS)
1103
- create_fifo_index_if_needed(full_name)
1157
+ if queue_ddl_rides_caller_transaction?
1158
+ create_queue_physically(full_name)
1159
+ else
1160
+ @queues_created.compute_if_absent(full_name) do
1161
+ create_queue_physically(full_name)
1162
+ true
1104
1163
  end
1105
- true
1164
+ end
1165
+ end
1166
+
1167
+ def create_queue_physically(full_name)
1168
+ synchronized do
1169
+ create_queue_table(full_name)
1170
+ enable_notify_if_needed(full_name, NOTIFY_THROTTLE_MS)
1171
+ create_fifo_index_if_needed(full_name)
1172
+ end
1173
+ end
1174
+
1175
+ def create_dead_letter_queue_physically(dlq_name)
1176
+ synchronized { create_queue_table(dlq_name) }
1177
+ end
1178
+
1179
+ # Runs inside synchronized — callers own the connection mutex.
1180
+ def create_queue_table(name)
1181
+ @pgmq.create(name)
1182
+ tune_autovacuum(name)
1183
+ end
1184
+
1185
+ # Queue DDL on the shared Proc-supplied connection joins any transaction
1186
+ # the caller has open, so a @queues_created cache write there outlives a
1187
+ # caller rollback — later ensures would skip recreation and message
1188
+ # operations would fail (#399 review; same durability rule as
1189
+ # @schema_ensured). Create the queue (idempotent CREATE IF NOT EXISTS)
1190
+ # but let the next ensure re-check. Dedicated String/Hash paths run DDL
1191
+ # on pgmq-ruby's own pool connections, never inside an application
1192
+ # transaction, so they always cache.
1193
+ #
1194
+ # The probe itself must hold the connection mutex: even the local
1195
+ # transaction_status read honors the single-owner invariant on the
1196
+ # shared PG::Connection (#399 review). Sequential with — never nested
1197
+ # inside — the create's own synchronized block.
1198
+ def queue_ddl_rides_caller_transaction?
1199
+ return false unless @shared_connection
1200
+
1201
+ synchronized do
1202
+ with_raw_connection { |conn| inside_caller_transaction?(conn) }
1106
1203
  end
1107
1204
  end
1108
1205
 
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.13.6"
4
+ VERSION = "0.13.7"
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.13.6
4
+ version: 0.13.7
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson