pgmq-ruby 0.8.2 → 0.10.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +50 -1
- data/README.md +33 -19
- data/lib/pgmq/client/producer.rb +1 -9
- data/lib/pgmq/client/topics.rb +7 -2
- data/lib/pgmq/client.rb +32 -9
- data/lib/pgmq/connection.rb +52 -16
- data/lib/pgmq/contractable/contract.rb +12 -9
- data/lib/pgmq/contractable/result.rb +1 -1
- data/lib/pgmq/version.rb +1 -1
- data/lib/pgmq.rb +2 -2
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: f22badf745600819d32d04a0af17955b3517a40bdb9b0a4c9a553e642d84747e
|
|
4
|
+
data.tar.gz: 6c82b75ec212a69f2aee957a03879ddd8dd448b3716d2e2a5cf747b9a014666e
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: e0b1e5e2a8a37fa92f03d0b92749390a39750e9477fc71217b4c92e2ce3930d2853719c210c2318013dea4df884f5648961a025f9a399a13cfe278c43ad89858
|
|
7
|
+
data.tar.gz: b201e1c734639cd358cb77c23e494bc761f49699ac34c2ec9685e52da55b1396b1e8698935f989360a65674f961e2d3f11aabcc77caaccb804e709f9cec0092b
|
data/CHANGELOG.md
CHANGED
|
@@ -1,12 +1,61 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.0 (2026-11-24)
|
|
4
|
+
|
|
5
|
+
### Infrastructure
|
|
6
|
+
- **[Fix]** The release job installs its gems into `vendor/bundle` instead of the Ruby install, so json 3.x from `Gemfile.lock` does not reach `sigstore-cli 0.2.3` (run outside the bundle by `rubygems/release-gem`), which crashed with it and made the gem go out without a Sigstore attestation. `rubygems/release-gem` is bumped to v1.4.2, which fixes the release wait that failed the job under Ruby 4.0.
|
|
7
|
+
- **[Change]** Drop PostgreSQL 14 from CI and the README requirements: PGMQ v1.13.2 supports PostgreSQL 15-18 and no longer rebuilds the `pg14-pgmq` image. PostgreSQL 14 reached end of life on 2026-11-12.
|
|
8
|
+
|
|
9
|
+
### Documentation
|
|
10
|
+
- **[Fix]** The `with_connection` docs said a block that loses its connection still raises
|
|
11
|
+
`PGMQ::Errors::ConnectionError` (README, 0.9.0 entry) and that the retry happens only before any SQL is sent (YARD of
|
|
12
|
+
`PGMQ::Client#with_connection`). With `auto_reconnect: true` (the default), a lost-connection error makes the whole
|
|
13
|
+
block run once more, also after it sent SQL, and a retry that succeeds raises nothing. The README and YARD now say so
|
|
14
|
+
and ask for a block that is safe to run twice, or `auto_reconnect: false`.
|
|
15
|
+
- **[Fix]** The README and YARD connection-hash examples passed the hash without braces, so `PGMQ::Client.new` and
|
|
16
|
+
`PGMQ::Connection.new` raised `ArgumentError`. They now wrap the hash in braces. The YARD auto-reconnect example
|
|
17
|
+
passed no connection parameters and raised `PGMQ::Errors::ConfigurationError`; it now passes a connection string.
|
|
18
|
+
|
|
19
|
+
## 0.9.0 (2026-11-10)
|
|
20
|
+
|
|
21
|
+
### Producer
|
|
22
|
+
- **[Breaking]** `produce_topic` and `produce_batch_topic` raise `PGMQ::Errors::MessageInvalidError` when a message is
|
|
23
|
+
not a String or its headers are neither a String nor `nil`, like `produce` and `produce_batch`. Most such calls
|
|
24
|
+
succeeded before and now raise: non-String messages and headers were stored as JSON (Integer, Float, `true`, `false`
|
|
25
|
+
and Array values) or as NULL (a `nil` message; Hash headers in `produce_topic` with an integer delay), and
|
|
26
|
+
`produce_topic` with an integer delay dropped `false` headers. The other `nil` and Hash cases raised
|
|
27
|
+
`PGMQ::Errors::ConnectionError`.
|
|
28
|
+
|
|
29
|
+
### Validation
|
|
30
|
+
- **[Change]** A contract check allocates its errors Array on the first error only, so valid input allocates one
|
|
31
|
+
object less per validated message in `produce`, `produce_batch`, `produce_topic` and `produce_batch_topic`.
|
|
32
|
+
Until then a `PGMQ::Contractable::Contract` rule gets a frozen empty `errors` Array: a custom rule that appends to it
|
|
33
|
+
raises `FrozenError`.
|
|
34
|
+
|
|
35
|
+
### Connection Management
|
|
36
|
+
- **[Fix]** `PGMQ::Connection#verify_connection!` resets a pooled connection whose status is anything other than
|
|
37
|
+
`PG::CONNECTION_OK` (#217). It reset only `CONNECTION_BAD` before, so a connection left in an intermediate state
|
|
38
|
+
(`CONNECTION_STARTED`, `CONNECTION_MADE`, ...) by a reset or connect interrupted before it completed (a
|
|
39
|
+
`Thread#raise` during `PG::Connection#reset`, a `reset_start` never polled to completion) passed the health check,
|
|
40
|
+
and every call on it, the `auto_reconnect` retry included, raised `PGMQ::Errors::ConnectionError` (`PG::UnableToSend:
|
|
41
|
+
no connection to the server`) until `reload` or a process restart. The next checkout now resets it.
|
|
42
|
+
- **[Fix]** `PGMQ::Connection#with_connection` resets a pooled connection when the block raises `PG::ConnectionBad`
|
|
43
|
+
or `PG::UnableToSend`, before the connection goes back to the pool. A connection can pass the checkout health check
|
|
44
|
+
and still fail on the next send; it went back to the pool broken, and with `auto_reconnect: false` (or when it still
|
|
45
|
+
reported `PG::CONNECTION_OK`) every later checkout failed the same way until `reload`. The caller still gets
|
|
46
|
+
`PGMQ::Errors::ConnectionError`. When the reset fails too, the connection is closed: with `auto_reconnect` the next
|
|
47
|
+
checkout resets it; without it, the next operation on it fails once and that failure resets it. Connections returned
|
|
48
|
+
by a callable (e.g. ActiveRecord's raw connection) are not reset or closed.
|
|
49
|
+
|
|
3
50
|
## 0.8.2 (2026-11-02)
|
|
4
51
|
|
|
5
52
|
### Queue Naming
|
|
6
53
|
- **[Fix]** The `InvalidQueueNameError` message for a too-long queue name states the real limit: "exceeds maximum
|
|
7
54
|
length of 47 characters" (was 48; a 48-character name was already rejected). The README now gives 47 as the maximum
|
|
8
55
|
and no longer calls queue names case-sensitive: names differing only in case share one table (PGMQ lower-cases
|
|
9
|
-
table names) but get separate `pgmq.meta` rows, so use one spelling per queue
|
|
56
|
+
table names) but get separate `pgmq.meta` rows, so use one spelling per queue.
|
|
57
|
+
|
|
58
|
+
### Documentation
|
|
10
59
|
- **[Fix]** The README `wait_for_notify` example said the call returns the notification payload; it returns the
|
|
11
60
|
channel name (`nil` on timeout).
|
|
12
61
|
|
data/README.md
CHANGED
|
@@ -93,12 +93,12 @@ This gem provides complete support for all core PGMQ SQL functions. Based on the
|
|
|
93
93
|
| | Consumer | Minimal single-threaded `PGMQ::Consumer` loop over one or more queues with ack on success | ✅ |
|
|
94
94
|
| | Queue Validation | 47-character limit and name validation | ✅ |
|
|
95
95
|
| | Connection Pooling | Thread-safe connection pool for concurrency | ✅ |
|
|
96
|
-
| | Pluggable Serializers | JSON (default) with custom serializer support | ✅ |
|
|
97
96
|
|
|
98
97
|
## Requirements
|
|
99
98
|
|
|
100
99
|
- Ruby 3.3+
|
|
101
|
-
- PostgreSQL
|
|
100
|
+
- PostgreSQL 15-18 with PGMQ extension installed
|
|
101
|
+
- PGMQ v1.13.1 or newer recommended: earlier versions have a high-severity privilege escalation ([GHSA-mwqf-p4r3-798v](https://github.com/pgmq/pgmq/security/advisories/GHSA-mwqf-p4r3-798v))
|
|
102
102
|
|
|
103
103
|
### Installing PGMQ Extension
|
|
104
104
|
|
|
@@ -183,13 +183,13 @@ gem install pgmq-ruby
|
|
|
183
183
|
require 'pgmq'
|
|
184
184
|
|
|
185
185
|
# Connect to database
|
|
186
|
-
client = PGMQ::Client.new(
|
|
186
|
+
client = PGMQ::Client.new({
|
|
187
187
|
host: 'localhost',
|
|
188
188
|
port: 5432,
|
|
189
189
|
dbname: 'mydb',
|
|
190
190
|
user: 'postgres',
|
|
191
191
|
password: 'secret'
|
|
192
|
-
)
|
|
192
|
+
})
|
|
193
193
|
|
|
194
194
|
# Create a queue
|
|
195
195
|
client.create('orders')
|
|
@@ -246,16 +246,21 @@ PGMQ-Ruby supports multiple ways to connect:
|
|
|
246
246
|
|
|
247
247
|
```ruby
|
|
248
248
|
client = PGMQ::Client.new(
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
249
|
+
{
|
|
250
|
+
host: 'localhost',
|
|
251
|
+
port: 5432,
|
|
252
|
+
dbname: 'mydb',
|
|
253
|
+
user: 'postgres',
|
|
254
|
+
password: 'secret'
|
|
255
|
+
},
|
|
254
256
|
pool_size: 5, # Default: 5
|
|
255
257
|
pool_timeout: 5 # Default: 5 seconds
|
|
256
258
|
)
|
|
257
259
|
```
|
|
258
260
|
|
|
261
|
+
Wrap the connection hash in braces. Without them, Ruby passes `host:`, `port:` and the other keys as keyword
|
|
262
|
+
arguments, and `PGMQ::Client.new` raises `ArgumentError` (unknown keywords).
|
|
263
|
+
|
|
259
264
|
### Connection String
|
|
260
265
|
|
|
261
266
|
```ruby
|
|
@@ -308,6 +313,19 @@ Every PGMQ operation checks out a pooled connection through `client.with_connect
|
|
|
308
313
|
The method is public, so you can run PostgreSQL statements PGMQ does not wrap
|
|
309
314
|
without standing up a second connection pool. The connection is health-checked
|
|
310
315
|
(when `auto_reconnect` is enabled) and returned to the pool when the block exits.
|
|
316
|
+
If the block raises `PG::ConnectionBad` or `PG::UnableToSend`, the connection is
|
|
317
|
+
reset before it goes back to the pool (connections from a callable are left as
|
|
318
|
+
they are).
|
|
319
|
+
|
|
320
|
+
With `auto_reconnect: true` (the default), a lost-connection error (see
|
|
321
|
+
[Extending the lost-connection error matchers](#extending-the-lost-connection-error-matchers))
|
|
322
|
+
makes `with_connection` run the **whole block** once more, on whichever
|
|
323
|
+
connection the pool hands out next. If that run succeeds, the call returns
|
|
324
|
+
normally and you see no error. You get `PGMQ::Errors::ConnectionError` only
|
|
325
|
+
when the second run fails too, or right away with `auto_reconnect: false`.
|
|
326
|
+
Statements that ran before the connection was lost (e.g. a `pg_notify`) can
|
|
327
|
+
therefore run twice: keep the block safe to run twice, or disable
|
|
328
|
+
`auto_reconnect`.
|
|
311
329
|
|
|
312
330
|
```ruby
|
|
313
331
|
# Fire a custom NOTIFY alongside your queues
|
|
@@ -366,11 +384,10 @@ pattern) raise `PGMQ::Errors::ConfigurationError` immediately so
|
|
|
366
384
|
misconfiguration can't silently disable retries.
|
|
367
385
|
|
|
368
386
|
> **Reserve these options for connection-level failures.** A "reconnectable"
|
|
369
|
-
> error
|
|
370
|
-
>
|
|
371
|
-
>
|
|
372
|
-
>
|
|
373
|
-
> mask bugs.
|
|
387
|
+
> error should mean the socket is dead. Do **not** add patterns or classes for
|
|
388
|
+
> query-level errors (deadlocks, constraint violations, statement timeouts) -
|
|
389
|
+
> those will replay your operation against a healthy connection and may cause
|
|
390
|
+
> duplicate work or mask bugs.
|
|
374
391
|
|
|
375
392
|
**Connection Pool Benefits:**
|
|
376
393
|
- **Thread-safe** - Multiple threads can safely share a single client
|
|
@@ -1230,8 +1247,8 @@ end
|
|
|
1230
1247
|
|
|
1231
1248
|
Invalid arguments are rejected by a contract before they reach PostgreSQL, with a validation error:
|
|
1232
1249
|
|
|
1233
|
-
- `PGMQ::Errors::MessageInvalidError` from `produce`, `produce_batch` and `produce_batch_topic`, for
|
|
1234
|
-
message is not a String or its headers are neither a String nor `nil`
|
|
1250
|
+
- `PGMQ::Errors::MessageInvalidError` from `produce`, `produce_batch`, `produce_topic` and `produce_batch_topic`, for
|
|
1251
|
+
example when a message is not a String or its headers are neither a String nor `nil`
|
|
1235
1252
|
- `PGMQ::Errors::MultiQueueInvalidError` from the multi-queue operations (`read_multi`, `read_multi_with_poll`,
|
|
1236
1253
|
`pop_multi`, `delete_multi`, `archive_multi`, `set_vt_multi`)
|
|
1237
1254
|
- `PGMQ::Errors::AutovacuumSettingsInvalidError` from `tune_autovacuum` for an unknown storage parameter or a
|
|
@@ -1268,9 +1285,6 @@ bin/integrations
|
|
|
1268
1285
|
|
|
1269
1286
|
# Run a specific integration spec
|
|
1270
1287
|
bin/integrations spec/integration/basic_produce_consume_spec.rb
|
|
1271
|
-
|
|
1272
|
-
# Run console
|
|
1273
|
-
bundle exec bin/console
|
|
1274
1288
|
```
|
|
1275
1289
|
|
|
1276
1290
|
## Author
|
data/lib/pgmq/client/producer.rb
CHANGED
|
@@ -103,17 +103,9 @@ module PGMQ
|
|
|
103
103
|
delay: 0
|
|
104
104
|
)
|
|
105
105
|
validate_queue_name!(queue_name)
|
|
106
|
-
|
|
106
|
+
validate_messages!(messages, headers)
|
|
107
107
|
return [] if messages.empty?
|
|
108
108
|
|
|
109
|
-
messages.each_with_index do |message, index|
|
|
110
|
-
MESSAGE_CONTRACT.validate!(
|
|
111
|
-
{ message: message, headers: headers && headers[index] },
|
|
112
|
-
Errors::MessageInvalidError,
|
|
113
|
-
scope: ["messages", index]
|
|
114
|
-
)
|
|
115
|
-
end
|
|
116
|
-
|
|
117
109
|
result = with_connection do |conn|
|
|
118
110
|
encoder = PG::TextEncoder::Array.new
|
|
119
111
|
encoded_messages = encoder.encode(messages)
|
data/lib/pgmq/client/topics.rb
CHANGED
|
@@ -73,6 +73,8 @@ module PGMQ
|
|
|
73
73
|
# @param delay [Numeric, ActiveSupport::Duration] delay in seconds before message becomes visible (integer,
|
|
74
74
|
# float or Duration; a float such as 1.5 needs PGMQ v1.10.0+)
|
|
75
75
|
# @return [Integer] count of queues the message was delivered to
|
|
76
|
+
# @raise [PGMQ::Errors::MessageInvalidError] if message is not a String, or headers is neither a String nor
|
|
77
|
+
# nil
|
|
76
78
|
#
|
|
77
79
|
# @example Basic topic send
|
|
78
80
|
# count = client.produce_topic("orders.new", '{"order_id":123}')
|
|
@@ -83,6 +85,8 @@ module PGMQ
|
|
|
83
85
|
# headers: '{"trace_id":"abc"}',
|
|
84
86
|
# delay: 30)
|
|
85
87
|
def produce_topic(routing_key, message, headers: nil, delay: 0)
|
|
88
|
+
MESSAGE_CONTRACT.validate!({ message: message, headers: headers }, Errors::MessageInvalidError)
|
|
89
|
+
|
|
86
90
|
# send_topic takes whole seconds only, so a fractional delay goes through send_batch_topic
|
|
87
91
|
if delay.is_a?(Numeric) && !delay.integer?
|
|
88
92
|
return produce_batch_topic(routing_key, [message], headers: headers && [headers], delay: delay).size
|
|
@@ -122,7 +126,8 @@ module PGMQ
|
|
|
122
126
|
# become visible, including ActiveSupport::TimeWithZone (PGMQ v1.10.0+)
|
|
123
127
|
# @return [Array<Hash>] array of hashes with :queue_name and :msg_id
|
|
124
128
|
# @raise [PGMQ::Errors::MessageInvalidError] if messages is not an Array, headers is neither an Array nor nil,
|
|
125
|
-
#
|
|
129
|
+
# headers length doesn't match messages length, a message is not a String, or a header is neither a String
|
|
130
|
+
# nor nil
|
|
126
131
|
#
|
|
127
132
|
# @example Batch topic send
|
|
128
133
|
# results = client.produce_batch_topic("orders.new", [
|
|
@@ -131,7 +136,7 @@ module PGMQ
|
|
|
131
136
|
# ])
|
|
132
137
|
# # => [{ queue_name: "new_orders", msg_id: "1" }, ...]
|
|
133
138
|
def produce_batch_topic(routing_key, messages, headers: nil, delay: 0)
|
|
134
|
-
|
|
139
|
+
validate_messages!(messages, headers)
|
|
135
140
|
return [] if messages.empty?
|
|
136
141
|
|
|
137
142
|
result = with_connection do |conn|
|
data/lib/pgmq/client.rb
CHANGED
|
@@ -7,12 +7,12 @@ module PGMQ
|
|
|
7
7
|
# integration), use pgmq-framework.
|
|
8
8
|
#
|
|
9
9
|
# @example Basic usage
|
|
10
|
-
# client = PGMQ::Client.new(
|
|
10
|
+
# client = PGMQ::Client.new({
|
|
11
11
|
# host: 'localhost',
|
|
12
12
|
# dbname: 'mydb',
|
|
13
13
|
# user: 'postgres',
|
|
14
14
|
# password: 'postgres'
|
|
15
|
-
# )
|
|
15
|
+
# })
|
|
16
16
|
# client.create('my_queue')
|
|
17
17
|
# msg_id = client.produce('my_queue', '{"data":"value"}')
|
|
18
18
|
# msg = client.read('my_queue', vt: 30)
|
|
@@ -64,13 +64,13 @@ module PGMQ
|
|
|
64
64
|
# client = PGMQ::Client.new('postgres://user:pass@localhost/db')
|
|
65
65
|
#
|
|
66
66
|
# @example Connection hash
|
|
67
|
-
# client = PGMQ::Client.new(host: 'localhost', dbname: 'mydb', user: 'postgres')
|
|
67
|
+
# client = PGMQ::Client.new({ host: 'localhost', dbname: 'mydb', user: 'postgres' })
|
|
68
68
|
#
|
|
69
69
|
# @example Inject existing connection (for Rails)
|
|
70
70
|
# client = PGMQ::Client.new(-> { ActiveRecord::Base.connection.raw_connection })
|
|
71
71
|
#
|
|
72
72
|
# @example Disable auto-reconnect
|
|
73
|
-
# client = PGMQ::Client.new(auto_reconnect: false)
|
|
73
|
+
# client = PGMQ::Client.new('postgres://user:pass@localhost/db', auto_reconnect: false)
|
|
74
74
|
def initialize(
|
|
75
75
|
conn_params = nil,
|
|
76
76
|
pool_size: Connection::DEFAULT_POOL_SIZE,
|
|
@@ -118,9 +118,10 @@ module PGMQ
|
|
|
118
118
|
# Checks out a pooled connection and yields the raw +PG::Connection+ for arbitrary SQL.
|
|
119
119
|
#
|
|
120
120
|
# All PGMQ operations run through this method internally, so it carries the same guarantees: a connection is taken
|
|
121
|
-
# from the pool, health-checked when +auto_reconnect+ is enabled, and
|
|
122
|
-
#
|
|
123
|
-
#
|
|
121
|
+
# from the pool, health-checked when +auto_reconnect+ is enabled, and returned to the pool when the block exits.
|
|
122
|
+
# With +auto_reconnect+ (the default), a lost-connection error makes the whole block run once more, on whichever
|
|
123
|
+
# connection the pool hands out next, also when the block already sent SQL: keep the block safe to run twice (see
|
|
124
|
+
# {PGMQ::Connection#with_connection}).
|
|
124
125
|
#
|
|
125
126
|
# Exposed so callers can issue PostgreSQL statements PGMQ does not wrap without standing up a second pool: ad-hoc
|
|
126
127
|
# +NOTIFY+, +LISTEN+, advisory locks, custom monitoring queries, or DDL that lives alongside your queue tables.
|
|
@@ -128,8 +129,8 @@ module PGMQ
|
|
|
128
129
|
#
|
|
129
130
|
# @yield [PG::Connection] a pooled, health-checked database connection
|
|
130
131
|
# @return [Object] the return value of the block
|
|
131
|
-
# @raise [PGMQ::Errors::ConnectionError] if the block raises any `PG::Error` (the original is in `#cause`)
|
|
132
|
-
# connection cannot be obtained
|
|
132
|
+
# @raise [PGMQ::Errors::ConnectionError] if the block raises any `PG::Error` (the original is in `#cause`) and it is
|
|
133
|
+
# not retried or the retry fails too, or a connection cannot be obtained
|
|
133
134
|
#
|
|
134
135
|
# @example Fire a custom NOTIFY on the PGMQ pool
|
|
135
136
|
# client.with_connection do |conn|
|
|
@@ -173,6 +174,28 @@ module PGMQ
|
|
|
173
174
|
nil
|
|
174
175
|
end
|
|
175
176
|
|
|
177
|
+
# Validates a batch of messages and their headers before they are bound
|
|
178
|
+
#
|
|
179
|
+
# @param messages [Array<String>] message payloads as JSON strings
|
|
180
|
+
# @param headers [Array<String, nil>, nil] headers as JSON strings, one per message
|
|
181
|
+
# @return [void]
|
|
182
|
+
# @raise [PGMQ::Errors::MessageInvalidError] if messages is not an Array, headers is neither an Array nor nil,
|
|
183
|
+
# headers length doesn't match messages length, a message is not a String, or a header is neither a String nor
|
|
184
|
+
# nil
|
|
185
|
+
def validate_messages!(messages, headers)
|
|
186
|
+
BATCH_CONTRACT.validate!({ messages: messages, headers: headers }, Errors::MessageInvalidError)
|
|
187
|
+
|
|
188
|
+
messages.each_with_index do |message, index|
|
|
189
|
+
MESSAGE_CONTRACT.validate!(
|
|
190
|
+
{ message: message, headers: headers && headers[index] },
|
|
191
|
+
Errors::MessageInvalidError,
|
|
192
|
+
scope: ["messages", index]
|
|
193
|
+
)
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
nil
|
|
197
|
+
end
|
|
198
|
+
|
|
176
199
|
# Builds the SQL argument and bind value for a +delay:+ given in seconds or as an absolute Time
|
|
177
200
|
#
|
|
178
201
|
# PostgreSQL rejects a Float such as +1.5+ for an +integer+ bind, so a non-Integer Numeric is passed to the
|
data/lib/pgmq/connection.rb
CHANGED
|
@@ -15,7 +15,7 @@ module PGMQ
|
|
|
15
15
|
# conn = PGMQ::Connection.new("postgres://localhost/mydb")
|
|
16
16
|
#
|
|
17
17
|
# @example With connection hash
|
|
18
|
-
# conn = PGMQ::Connection.new(host: 'localhost', dbname: 'mydb')
|
|
18
|
+
# conn = PGMQ::Connection.new({ host: 'localhost', dbname: 'mydb' })
|
|
19
19
|
#
|
|
20
20
|
# @example With Rails ActiveRecord (reuses Rails connection pool)
|
|
21
21
|
# conn = PGMQ::Connection.new(-> { ActiveRecord::Base.connection.raw_connection })
|
|
@@ -32,9 +32,10 @@ module PGMQ
|
|
|
32
32
|
private_constant :CONTRACT
|
|
33
33
|
|
|
34
34
|
class << self
|
|
35
|
-
# Additional error message patterns (String or Regexp) that mean the connection is dead
|
|
36
|
-
#
|
|
37
|
-
# built-in LOST_CONNECTION_MESSAGES are always checked first -
|
|
35
|
+
# Additional error message patterns (String or Regexp) that mean the connection is dead. With +auto_reconnect+, a
|
|
36
|
+
# match makes {PGMQ::Connection#with_connection} run its block once more. Strings are matched as case-insensitive
|
|
37
|
+
# substrings; Regexps match the original message. The built-in LOST_CONNECTION_MESSAGES are always checked first -
|
|
38
|
+
# this list is appended to them.
|
|
38
39
|
#
|
|
39
40
|
# Thread-safe: reads are lock-free (frozen array swap); writes should be done at boot time before forking workers.
|
|
40
41
|
#
|
|
@@ -116,15 +117,25 @@ module PGMQ
|
|
|
116
117
|
@pool_size = pool_size
|
|
117
118
|
@pool_timeout = pool_timeout
|
|
118
119
|
@auto_reconnect = auto_reconnect
|
|
120
|
+
# A callable hands us connections it may share with its owner (e.g. ActiveRecord's raw connection), so we never
|
|
121
|
+
# reset or close them after a failure; only connections we open ourselves are reset.
|
|
122
|
+
@owns_connections = !conn_params.respond_to?(:call)
|
|
119
123
|
@pool = create_pool
|
|
120
124
|
end
|
|
121
125
|
|
|
122
126
|
# Executes a block with a connection from the pool
|
|
123
127
|
#
|
|
128
|
+
# When the block raises `PG::ConnectionBad` or `PG::UnableToSend`, the connection is reset before it goes back to
|
|
129
|
+
# the pool, so the next checkout gets a working one. Connections from a callable are left as they are.
|
|
130
|
+
#
|
|
131
|
+
# With `auto_reconnect`, a lost-connection error (see {#connection_lost_error?}) raised by the health check or the
|
|
132
|
+
# block makes the whole block run once more, on whichever connection the pool hands out next. Statements the first
|
|
133
|
+
# run already sent can run twice. A retry that succeeds returns normally.
|
|
134
|
+
#
|
|
124
135
|
# @yield [PG::Connection] database connection
|
|
125
136
|
# @return [Object] result of the block
|
|
126
|
-
# @raise [PGMQ::Errors::ConnectionError] if the block raises any `PG::Error` (the original is in `#cause`)
|
|
127
|
-
# connection cannot be obtained
|
|
137
|
+
# @raise [PGMQ::Errors::ConnectionError] if the block raises any `PG::Error` (the original is in `#cause`) and it is
|
|
138
|
+
# not retried or the retry fails too, or a connection cannot be obtained
|
|
128
139
|
def with_connection
|
|
129
140
|
retries = @auto_reconnect ? 1 : 0
|
|
130
141
|
attempts = 0
|
|
@@ -134,7 +145,12 @@ module PGMQ
|
|
|
134
145
|
# Health check: verify connection is alive
|
|
135
146
|
verify_connection!(conn) if @auto_reconnect
|
|
136
147
|
|
|
137
|
-
|
|
148
|
+
begin
|
|
149
|
+
yield conn
|
|
150
|
+
rescue *LOST_CONNECTION_ERRORS
|
|
151
|
+
reset_lost_connection(conn) if @owns_connections
|
|
152
|
+
raise
|
|
153
|
+
end
|
|
138
154
|
end
|
|
139
155
|
rescue PG::Error => e
|
|
140
156
|
attempts += 1
|
|
@@ -161,8 +177,8 @@ module PGMQ
|
|
|
161
177
|
#
|
|
162
178
|
# Use this to recover from a connection that libpq still reports as +CONNECTION_OK+ but which is in fact wedged -
|
|
163
179
|
# e.g. after a wall-clock timeout (+Timeout.timeout+) interrupted a query mid-flight, leaving the socket poisoned so
|
|
164
|
-
# it re-hangs on reuse. {#verify_connection!} cannot catch that case (the connection
|
|
165
|
-
# +
|
|
180
|
+
# it re-hangs on reuse. {#verify_connection!} cannot catch that case (the connection still reports
|
|
181
|
+
# +CONNECTION_OK+), so the caller must discard it explicitly; +reload+ is the safe, pool-wide way to do so.
|
|
166
182
|
#
|
|
167
183
|
# @return [void]
|
|
168
184
|
# @example Discard the pool after a query had to be force-interrupted
|
|
@@ -191,6 +207,10 @@ module PGMQ
|
|
|
191
207
|
|
|
192
208
|
private
|
|
193
209
|
|
|
210
|
+
# libpq's dedicated connection-failure classes. A pooled connection that raises one of them mid-operation is reset.
|
|
211
|
+
LOST_CONNECTION_ERRORS = [PG::ConnectionBad, PG::UnableToSend].freeze
|
|
212
|
+
private_constant :LOST_CONNECTION_ERRORS
|
|
213
|
+
|
|
194
214
|
# Messages libpq raises when the server/pooler has already torn down the socket. The list has grown organically with
|
|
195
215
|
# each pooler/TLS variant we see in the wild; the class check below catches future variants that libpq raises as
|
|
196
216
|
# `PG::ConnectionBad` or `PG::UnableToSend` without waiting for a new message to hit production.
|
|
@@ -217,10 +237,9 @@ module PGMQ
|
|
|
217
237
|
# patterns (strings matched as case-insensitive substrings, Regexps matched against the original message).
|
|
218
238
|
#
|
|
219
239
|
# @param error [PG::Error] the error to check
|
|
220
|
-
# @return [Boolean] true if the connection was lost and a retry
|
|
221
|
-
# fresh connection is appropriate
|
|
240
|
+
# @return [Boolean] true if the connection was lost and a retry is appropriate
|
|
222
241
|
def connection_lost_error?(error)
|
|
223
|
-
return true if
|
|
242
|
+
return true if LOST_CONNECTION_ERRORS.any? { |klass| error.is_a?(klass) }
|
|
224
243
|
|
|
225
244
|
extra_classes = self.class.reconnectable_error_classes
|
|
226
245
|
return true if extra_classes.any? { |klass| error.is_a?(klass) }
|
|
@@ -240,19 +259,36 @@ module PGMQ
|
|
|
240
259
|
|
|
241
260
|
# Verifies a connection is alive and working.
|
|
242
261
|
#
|
|
243
|
-
# Also resets when the connection reports `PG::CONNECTION_BAD
|
|
244
|
-
# pooler such as PgBouncer)
|
|
245
|
-
#
|
|
262
|
+
# Also resets when the connection reports any status other than `PG::CONNECTION_OK`: `CONNECTION_BAD` when the
|
|
263
|
+
# server (or an intermediate pooler such as PgBouncer) closed the socket while the client-side `PG::Connection`
|
|
264
|
+
# object still exists, and an intermediate state (`CONNECTION_STARTED`, `CONNECTION_MADE`, ...) when a previous
|
|
265
|
+
# reset or connect was interrupted before it completed. libpq refuses to send on either. `#finished?` alone only
|
|
266
|
+
# catches connections closed explicitly from the client side.
|
|
246
267
|
#
|
|
247
268
|
# @param conn [PG::Connection] connection to verify
|
|
248
269
|
# @raise [PG::Error] if the reset itself fails
|
|
249
270
|
def verify_connection!(conn)
|
|
250
271
|
return conn.reset if conn.finished?
|
|
251
|
-
return conn.reset
|
|
272
|
+
return conn.reset unless conn.status == PG::CONNECTION_OK
|
|
252
273
|
|
|
253
274
|
nil
|
|
254
275
|
end
|
|
255
276
|
|
|
277
|
+
# Resets a connection that failed mid-operation so it does not go back to the pool broken. A connection can pass
|
|
278
|
+
# {#verify_connection!} at checkout (`CONNECTION_OK`) and still fail on the next send.
|
|
279
|
+
#
|
|
280
|
+
# A failing reset must not replace the error the caller sees, so it is swallowed and the connection is closed
|
|
281
|
+
# instead. With `auto_reconnect`, the next checkout sees it as `finished?` and resets it. Without it, the next
|
|
282
|
+
# operation on it fails with `PG::ConnectionBad` ("connection is closed"), and that failure resets it.
|
|
283
|
+
#
|
|
284
|
+
# @param conn [PG::Connection] connection the failed operation used
|
|
285
|
+
# @return [void]
|
|
286
|
+
def reset_lost_connection(conn)
|
|
287
|
+
conn.reset
|
|
288
|
+
rescue
|
|
289
|
+
conn.close unless conn.finished?
|
|
290
|
+
end
|
|
291
|
+
|
|
256
292
|
# Normalizes various connection parameter formats
|
|
257
293
|
# @param params [String, Hash, Proc]
|
|
258
294
|
# @return [Hash, Proc]
|
|
@@ -21,7 +21,8 @@ module PGMQ
|
|
|
21
21
|
DIG_MISS = Object.new
|
|
22
22
|
|
|
23
23
|
# Empty array for scope default to avoid allocating a new Array on each `#call` / `#validate!` invocation. Safe
|
|
24
|
-
# because scope is never mutated - it is only used in `scope + rule.path` which creates a new Array.
|
|
24
|
+
# because scope is never mutated - it is only used in `scope + rule.path` which creates a new Array. Also passed
|
|
25
|
+
# to validators as `errors` until the first error.
|
|
25
26
|
EMPTY_ARRAY = [].freeze
|
|
26
27
|
|
|
27
28
|
private_constant :DIG_MISS, :EMPTY_ARRAY
|
|
@@ -77,7 +78,7 @@ module PGMQ
|
|
|
77
78
|
#
|
|
78
79
|
# @param block [Proc] validation rule, called with `(data, errors, contract)`. It must return either a
|
|
79
80
|
# non-Array (`true`/`nil`/`false`) for "no errors", or an `Array` of `[path, message]` error pairs (where
|
|
80
|
-
# `path` is itself an `Array` of symbols).
|
|
81
|
+
# `path` is itself an `Array` of symbols). `errors` holds the errors found so far and must not be mutated.
|
|
81
82
|
#
|
|
82
83
|
# @note The returned error `Array` is owned by the contract: `#call` prepends the current scope onto each pair
|
|
83
84
|
# in place and collects them, so a rule must return a freshly built `Array` on every call.
|
|
@@ -102,39 +103,41 @@ module PGMQ
|
|
|
102
103
|
# needed if contract starts from root
|
|
103
104
|
# @return [Result] validation result
|
|
104
105
|
def call(data, scope: EMPTY_ARRAY)
|
|
105
|
-
|
|
106
|
+
# Allocated on the first error, so valid data allocates no Array
|
|
107
|
+
errors = nil
|
|
106
108
|
|
|
107
109
|
# A non-Hash root has no keys to dig, so every required rule reports missing
|
|
108
110
|
data_is_hash = data.is_a?(Hash)
|
|
109
111
|
|
|
110
112
|
self.class.rules.each do |rule|
|
|
111
113
|
if rule.type == :virtual
|
|
112
|
-
result = rule.validator.call(data, errors, self)
|
|
114
|
+
result = rule.validator.call(data, errors || EMPTY_ARRAY, self)
|
|
113
115
|
|
|
114
116
|
# Any non-Array result (true, but also nil/false) means "no errors"
|
|
115
117
|
next unless result.is_a?(Array)
|
|
118
|
+
next if result.empty?
|
|
116
119
|
|
|
117
120
|
result.each do |sub_result|
|
|
118
121
|
sub_result[0] = scope + sub_result[0]
|
|
119
122
|
end
|
|
120
123
|
|
|
121
|
-
errors.push(*result)
|
|
124
|
+
(errors ||= []).push(*result)
|
|
122
125
|
else
|
|
123
126
|
for_checking = data_is_hash ? dig(data, rule.path) : DIG_MISS
|
|
124
127
|
|
|
125
128
|
if DIG_MISS.equal?(for_checking)
|
|
126
|
-
errors << [scope + rule.path, :missing] if rule.type == :required
|
|
129
|
+
(errors ||= []) << [scope + rule.path, :missing] if rule.type == :required
|
|
127
130
|
else
|
|
128
|
-
result = rule.validator.call(for_checking, data, errors, self)
|
|
131
|
+
result = rule.validator.call(for_checking, data, errors || EMPTY_ARRAY, self)
|
|
129
132
|
|
|
130
133
|
next if result == true
|
|
131
134
|
|
|
132
|
-
errors << [scope + rule.path, result || :format]
|
|
135
|
+
(errors ||= []) << [scope + rule.path, result || :format]
|
|
133
136
|
end
|
|
134
137
|
end
|
|
135
138
|
end
|
|
136
139
|
|
|
137
|
-
return Result.success
|
|
140
|
+
return Result.success unless errors
|
|
138
141
|
|
|
139
142
|
Result.new(errors, self)
|
|
140
143
|
end
|
|
@@ -34,7 +34,7 @@ module PGMQ
|
|
|
34
34
|
hashed = {}
|
|
35
35
|
|
|
36
36
|
errors.each do |error|
|
|
37
|
-
scope = error.first.
|
|
37
|
+
scope = error.first.join(".").to_sym
|
|
38
38
|
|
|
39
39
|
# This will allow for usage of custom messages instead of yaml keys if needed
|
|
40
40
|
hashed[scope] = if error.last.is_a?(String)
|
data/lib/pgmq/version.rb
CHANGED
data/lib/pgmq.rb
CHANGED
|
@@ -19,13 +19,13 @@ loader.setup
|
|
|
19
19
|
# require 'pgmq'
|
|
20
20
|
#
|
|
21
21
|
# # Create client with connection parameters
|
|
22
|
-
# client = PGMQ::Client.new(
|
|
22
|
+
# client = PGMQ::Client.new({
|
|
23
23
|
# host: 'localhost',
|
|
24
24
|
# port: 5432,
|
|
25
25
|
# dbname: 'mydb',
|
|
26
26
|
# user: 'postgres',
|
|
27
27
|
# password: 'postgres'
|
|
28
|
-
# )
|
|
28
|
+
# })
|
|
29
29
|
#
|
|
30
30
|
# # Or with connection string
|
|
31
31
|
# client = PGMQ::Client.new('postgres://localhost/mydb')
|