pgque 0.3.0.rc.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e9f672944ce942abdda5d3f3dc31588d93854451cceff22471fc47bc7c3cb066
4
+ data.tar.gz: dd9660e4c51a94356eb9dbdb43c3593ca2be1170b40eb416303a2eddca11cd79
5
+ SHA512:
6
+ metadata.gz: 1f035242e640be5abb50f1a00bca4cd4bc18f3bb71aaac921f9d42fca47aa2f292bba44c5767218971a3004499a3c816ad0a282d37ca8f2bdd3ca5145289c6f9
7
+ data.tar.gz: 0c2b7d8c2993be8d4e59636e4474d97111ca589b916b52de477230a267eb5a1841d4b29d2d99c60b0c7c86b0f9df042de33c01103061300072459ab34154f189
data/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 Nikolay Samokhvalov
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # pgque
2
+
3
+ Ruby client for [PgQue](https://github.com/NikolayS/pgque) — the PgQ-based
4
+ universal PostgreSQL queue. Thin wrapper over `pgque-api` SQL functions:
5
+ `send`, `receive`, `ack`, `nack`, `force_next_tick`, plus a polling
6
+ `Consumer` with `LISTEN`/`NOTIFY` wakeup.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ gem install pgque --pre
12
+ ```
13
+
14
+ `--pre` is required while v0.3.0 is in release-candidate; the latest
15
+ published version is `0.3.0.rc.1`. Pin the exact version if you prefer:
16
+
17
+ ```ruby
18
+ gem "pgque", "0.3.0.rc.1"
19
+ ```
20
+
21
+ Requires Ruby 3.1+ and PostgreSQL 14+ with the PgQue schema installed
22
+ (`\i pgque.sql` — no extension required).
23
+
24
+ ## Database permissions
25
+
26
+ The connecting database role needs `pgque_reader` to consume (`receive`,
27
+ `ack`, `nack`) and `pgque_writer` to produce (`send`, `send_batch`). The
28
+ two are **siblings** — neither inherits the other. An app that both
29
+ produces and consumes must be granted **both** roles:
30
+
31
+ ```sql
32
+ grant pgque_reader to your_app_user;
33
+ grant pgque_writer to your_app_user;
34
+ ```
35
+
36
+ See [`docs/reference.md` — Roles and grants](../../docs/reference.md#roles-and-grants).
37
+
38
+ ## Quickstart
39
+
40
+ Run the one-time setup once (typically in a migration), then produce
41
+ and consume from any process:
42
+
43
+ ```ruby
44
+ require "pgque"
45
+
46
+ Pgque.connect("postgresql://localhost/mydb") do |client|
47
+ # one-time setup
48
+ client.conn.exec("select pgque.create_queue('orders')")
49
+ client.conn.exec("select pgque.subscribe('orders', 'order_worker')")
50
+
51
+ # produce
52
+ client.send("orders", { "order_id" => 42 }, type: "order.created")
53
+ end
54
+
55
+ # consume (separate process)
56
+ consumer = Pgque::Consumer.new(
57
+ "postgresql://localhost/mydb",
58
+ queue: "orders",
59
+ name: "order_worker",
60
+ )
61
+ consumer.on("order.created") { |msg| process_order(msg.payload) }
62
+ consumer.start # blocks until SIGTERM / SIGINT
63
+ ```
64
+
65
+ The consumer only sees events after `pgque.ticker()` has materialized
66
+ a batch. With `pg_cron` available, run `select pgque.start();` once
67
+ to schedule the default 10 ticks/sec. Without `pg_cron`, drive
68
+ ticking from your application or an external scheduler — see the
69
+ project [Installation](https://github.com/NikolayS/pgque#installation)
70
+ section for both paths.
71
+
72
+ ## A note on `Pgque::Client#send`
73
+
74
+ The producer method is called `send` to mirror the SQL surface
75
+ (`pgque.send(queue, payload)`) and the Python/TS clients. That name
76
+ shadows Ruby's `Object#send`, which is widely used for reflective
77
+ method invocation. This means `client.send(:close)` calls the SQL
78
+ `send`, **not** the `close` method.
79
+
80
+ Two well-known Ruby escape hatches restore reflective dispatch on a
81
+ `Pgque::Client` instance:
82
+
83
+ ```ruby
84
+ client.__send__(:close) # canonical "always works" form
85
+ client.public_send(:close) # safer: respects visibility
86
+ ```
87
+
88
+ Use `__send__` or `public_send` whenever you need to call a method on
89
+ a `Pgque::Client` by name. The Pgque API itself never calls these
90
+ internally.
91
+
92
+ ## Tests
93
+
94
+ Integration tests require a running PostgreSQL with the PgQue schema
95
+ installed. Set `PGQUE_TEST_DSN` and run rake:
96
+
97
+ ```bash
98
+ PGQUE_TEST_DSN=postgresql://postgres:pgque_test@localhost/pgque_test \
99
+ bundle exec rake test
100
+ ```
101
+
102
+ Without `PGQUE_TEST_DSN`, the tests skip.
103
+
104
+ ## License
105
+
106
+ Apache-2.0. Copyright 2026 Nikolay Samokhvalov.
@@ -0,0 +1,283 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+ # PgQue includes code derived from PgQ (ISC license,
3
+ # Marko Kreen / Skype Technologies OU).
4
+
5
+ module Pgque
6
+ # Thin wrapper over the pgque SQL functions.
7
+ #
8
+ # Note: Pgque::Client#send mirrors the SQL `pgque.send(queue, payload)`
9
+ # primitive and the Python/TS client surface. That name shadows
10
+ # Ruby's Object#send, so use #__send__ or #public_send when you need
11
+ # to invoke a method on a Pgque::Client instance reflectively.
12
+ class Client
13
+ attr_reader :conn
14
+
15
+ def self.connect(dsn)
16
+ conn = PG.connect(dsn)
17
+ new(conn, owns_conn: true)
18
+ rescue PG::ConnectionBad => e
19
+ raise ConnectionError, e.message
20
+ end
21
+
22
+ def initialize(conn, owns_conn: false)
23
+ @conn = conn
24
+ @owns_conn = owns_conn
25
+ end
26
+
27
+ def close
28
+ return unless @owns_conn
29
+ return if @conn.finished?
30
+ @conn.close
31
+ end
32
+
33
+ def send(queue, payload, type: "default")
34
+ if payload.is_a?(Event)
35
+ type = payload.type
36
+ payload = payload.payload
37
+ end
38
+ encoded = encode_payload(payload)
39
+ result =
40
+ if custom_type?(type)
41
+ @conn.exec_params(
42
+ "select pgque.send($1, $2, $3::jsonb)",
43
+ [queue, type, encoded],
44
+ )
45
+ else
46
+ @conn.exec_params(
47
+ "select pgque.send($1, $2::jsonb)",
48
+ [queue, encoded],
49
+ )
50
+ end
51
+ integer_scalar(result)
52
+ rescue PG::Error => e
53
+ raise_wrapped_sql_error(e)
54
+ end
55
+
56
+ def send_batch(queue, type, payloads)
57
+ encoded = payloads.map { |p| encode_payload(p) }
58
+ array_literal = pg_text_array(encoded)
59
+ result = @conn.exec_params(
60
+ "select unnest(pgque.send_batch($1, $2, $3::jsonb[]))",
61
+ [queue, type, array_literal],
62
+ )
63
+ integer_column(result)
64
+ rescue PG::Error => e
65
+ raise_wrapped_sql_error(e)
66
+ end
67
+
68
+ def receive(queue, consumer, max_messages = 100)
69
+ result = @conn.exec_params(
70
+ "select * from pgque.receive($1, $2, $3)",
71
+ [queue, consumer, max_messages],
72
+ )
73
+ result.each_row.map { |row| row_to_message(row) }
74
+ rescue PG::Error => e
75
+ raise_wrapped_sql_error(e)
76
+ end
77
+
78
+ def ack(batch_id)
79
+ result = @conn.exec_params("select pgque.ack($1)", [batch_id])
80
+ integer_scalar(result)
81
+ rescue PG::Error => e
82
+ raise_wrapped_sql_error(e)
83
+ end
84
+
85
+ def subscribe(queue, consumer)
86
+ result = @conn.exec_params(
87
+ "select pgque.subscribe($1, $2)", [queue, consumer]
88
+ )
89
+ integer_scalar(result)
90
+ rescue PG::Error => e
91
+ raise_wrapped_sql_error(e)
92
+ end
93
+
94
+ def unsubscribe(queue, consumer)
95
+ result = @conn.exec_params(
96
+ "select pgque.unsubscribe($1, $2)", [queue, consumer]
97
+ )
98
+ integer_scalar(result)
99
+ rescue PG::Error => e
100
+ raise_wrapped_sql_error(e)
101
+ end
102
+
103
+ def force_next_tick(queue)
104
+ result = @conn.exec_params("select pgque.force_next_tick($1)", [queue])
105
+ v = scalar(result)
106
+ v.nil? || v.empty? ? nil : v.to_i
107
+ rescue PG::Error => e
108
+ raise_wrapped_sql_error(e)
109
+ end
110
+
111
+ def ticker(queue)
112
+ result = @conn.exec_params("select pgque.ticker($1)", [queue])
113
+ v = scalar(result)
114
+ v.nil? || v.empty? ? nil : v.to_i
115
+ rescue PG::Error => e
116
+ raise_wrapped_sql_error(e)
117
+ end
118
+
119
+ def ticker_all
120
+ result = @conn.exec_params("select pgque.ticker()", [])
121
+ integer_scalar(result)
122
+ rescue PG::Error => e
123
+ raise_wrapped_sql_error(e)
124
+ end
125
+
126
+ # Experimental: function names, edge-case behavior, and signatures may
127
+ # change before the cooperative API is marked stable.
128
+ def subscribe_subconsumer(queue, consumer, subconsumer)
129
+ result = @conn.exec_params(
130
+ "select pgque.subscribe_subconsumer($1, $2, $3)",
131
+ [queue, consumer, subconsumer],
132
+ )
133
+ integer_scalar(result)
134
+ rescue PG::Error => e
135
+ raise_wrapped_sql_error(e)
136
+ end
137
+
138
+ def unsubscribe_subconsumer(queue, consumer, subconsumer, batch_handling: 0)
139
+ result = @conn.exec_params(
140
+ "select pgque.unsubscribe_subconsumer($1, $2, $3, $4)",
141
+ [queue, consumer, subconsumer, batch_handling],
142
+ )
143
+ integer_scalar(result)
144
+ rescue PG::Error => e
145
+ raise_wrapped_sql_error(e)
146
+ end
147
+
148
+ def receive_coop(queue, consumer, subconsumer, max_messages: 100,
149
+ dead_interval: nil)
150
+ result = @conn.exec_params(
151
+ "select * from pgque.receive_coop($1, $2, $3, $4, $5::interval)",
152
+ [queue, consumer, subconsumer, max_messages, dead_interval],
153
+ )
154
+ result.each_row.map { |row| row_to_message(row) }
155
+ rescue PG::Error => e
156
+ raise_wrapped_sql_error(e)
157
+ end
158
+
159
+ def touch_subconsumer(queue, consumer, subconsumer)
160
+ result = @conn.exec_params(
161
+ "select pgque.touch_subconsumer($1, $2, $3)",
162
+ [queue, consumer, subconsumer],
163
+ )
164
+ integer_scalar(result)
165
+ rescue PG::Error => e
166
+ raise_wrapped_sql_error(e)
167
+ end
168
+
169
+ def nack(batch_id, msg, retry_after: 60, reason: nil)
170
+ payload_str = case msg.payload
171
+ when Hash, Array then JSON.dump(msg.payload)
172
+ when nil then "null"
173
+ else msg.payload.to_s
174
+ end
175
+ created_at_str = format_created_at(msg.created_at)
176
+
177
+ @conn.exec_params(
178
+ "select pgque.nack($1, " \
179
+ "ROW($2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11)::pgque.message, " \
180
+ "$12::interval, $13)",
181
+ [
182
+ batch_id, msg.msg_id, msg.batch_id, msg.type, payload_str,
183
+ msg.retry_count, created_at_str,
184
+ msg.extra1, msg.extra2, msg.extra3, msg.extra4,
185
+ "#{retry_after} seconds", reason,
186
+ ],
187
+ )
188
+ nil
189
+ rescue PG::Error => e
190
+ raise_wrapped_sql_error(e)
191
+ end
192
+
193
+ private
194
+
195
+ # Hash/Array: JSON-encoded.
196
+ # nil: literal "null" so ::jsonb yields JSON null (not SQL NULL).
197
+ # String: passed through verbatim; caller must supply valid JSON text.
198
+ # Anything else (Integer, Float, true, false, Symbol, ...): coerced
199
+ # via #to_s so numerics and booleans round-trip naturally
200
+ # (42 -> "42", true -> "true"). Symbols and other objects whose
201
+ # to_s isn't valid JSON will surface a SQL error from the ::jsonb
202
+ # cast -- callers who care should pre-encode with JSON.dump.
203
+ def encode_payload(payload)
204
+ case payload
205
+ when Hash, Array then JSON.dump(payload)
206
+ when nil then "null"
207
+ when String then payload
208
+ else payload.to_s
209
+ end
210
+ end
211
+
212
+ def pg_text_array(strings)
213
+ escaped = strings.map do |s|
214
+ inner = s.to_s.gsub('\\') { '\\\\' }.gsub('"') { '\\"' }
215
+ "\"#{inner}\""
216
+ end
217
+ "{#{escaped.join(',')}}"
218
+ end
219
+
220
+ def row_to_message(row)
221
+ Message.new(
222
+ msg_id: row[0].to_i,
223
+ batch_id: row[1].to_i,
224
+ type: row[2],
225
+ payload: parse_jsonb(row[3]),
226
+ retry_count: row[4].nil? ? nil : row[4].to_i,
227
+ created_at: row[5].nil? ? nil : Time.parse(row[5]),
228
+ extra1: row[6],
229
+ extra2: row[7],
230
+ extra3: row[8],
231
+ extra4: row[9],
232
+ )
233
+ end
234
+
235
+ def parse_jsonb(text)
236
+ return nil if text.nil?
237
+ JSON.parse(text)
238
+ rescue JSON::ParserError
239
+ text
240
+ end
241
+
242
+ def wrap_sql_error(error)
243
+ msg = error.message.to_s
244
+ low = msg.downcase
245
+ if low.include?("queue not found")
246
+ QueueNotFound.new(msg)
247
+ elsif low.include?("batch not found")
248
+ BatchNotFound.new(msg)
249
+ else
250
+ Error.new(msg)
251
+ end
252
+ end
253
+
254
+ def raise_wrapped_sql_error(error)
255
+ wrapped = wrap_sql_error(error)
256
+ wrapped.set_backtrace(error.backtrace) if error.backtrace
257
+ raise wrapped, cause: error
258
+ end
259
+
260
+ def scalar(result)
261
+ result.getvalue(0, 0)
262
+ end
263
+
264
+ def integer_scalar(result)
265
+ scalar(result).to_i
266
+ end
267
+
268
+ def integer_column(result)
269
+ result.column_values(0).map(&:to_i)
270
+ end
271
+
272
+ def custom_type?(type)
273
+ !type.to_s.empty? && type != "default"
274
+ end
275
+
276
+ def format_created_at(value)
277
+ case value
278
+ when Time then value.iso8601(6)
279
+ else value
280
+ end
281
+ end
282
+ end
283
+ end
@@ -0,0 +1,273 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+ # PgQue includes code derived from PgQ (ISC license,
3
+ # Marko Kreen / Skype Technologies OU).
4
+
5
+ require "logger"
6
+
7
+ module Pgque
8
+ class Consumer
9
+ DEFAULT_MAX_MESSAGES = 2_147_483_647
10
+ WAIT_SLICE_SECONDS = 0.5
11
+
12
+ attr_reader :dsn, :queue, :name, :poll_interval, :max_messages,
13
+ :retry_after, :subconsumer, :dead_interval
14
+
15
+ attr_accessor :logger
16
+
17
+ def initialize(dsn, queue:, name:, poll_interval: 30,
18
+ max_messages: DEFAULT_MAX_MESSAGES, retry_after: 60,
19
+ unknown_handler_policy: "nack", subconsumer: nil,
20
+ dead_interval: nil, logger: nil)
21
+ @dsn = dsn
22
+ @queue = queue
23
+ @name = name
24
+ @poll_interval = poll_interval
25
+ @max_messages = max_messages
26
+ @retry_after = retry_after
27
+
28
+ unless ["nack", "ack"].include?(unknown_handler_policy.to_s)
29
+ raise ArgumentError,
30
+ "unknown_handler_policy must be 'nack' or 'ack', " \
31
+ "got #{unknown_handler_policy.inspect}"
32
+ end
33
+ @unknown_handler_policy = unknown_handler_policy.to_s
34
+
35
+ if dead_interval && subconsumer.nil?
36
+ raise ArgumentError,
37
+ "dead_interval is only valid in cooperative mode " \
38
+ "(set subconsumer:)"
39
+ end
40
+ @subconsumer = subconsumer
41
+ @dead_interval = dead_interval
42
+
43
+ @handlers = {}
44
+ @default_handler = nil
45
+ # @running is a plain boolean. Ruby integer/boolean assignment
46
+ # is atomic, and the only cross-thread interactions are the
47
+ # signal trap and Consumer#stop flipping it false while the
48
+ # main loop polls running? -- no ordering dependencies, so a
49
+ # mutex would be overkill (and unsafe to enter from a signal
50
+ # trap, which raises ThreadError on Mutex#synchronize).
51
+ @running = false
52
+ @stop_signum = nil
53
+ @logger = logger || default_logger
54
+ end
55
+
56
+ def on(event_type, &block)
57
+ raise ArgumentError, "block required for Consumer#on" unless block
58
+
59
+ if event_type == "*"
60
+ @default_handler = block
61
+ else
62
+ @handlers[event_type] = block
63
+ end
64
+ block
65
+ end
66
+
67
+ def start
68
+ @running = true
69
+ @stop_signum = nil
70
+
71
+ in_main_thread = (Thread.current == Thread.main)
72
+ original_handlers = {}
73
+
74
+ # Signal traps run in a restricted context: Mutex#synchronize,
75
+ # Logger#info, and most blocking code raise ThreadError. Keep
76
+ # this proc to plain instance-variable writes; the main loop
77
+ # logs the signal number after waking up.
78
+ stop_proc = ->(signum) {
79
+ @stop_signum = signum
80
+ @running = false
81
+ }
82
+
83
+ if in_main_thread
84
+ ["TERM", "INT"].each do |sig|
85
+ original_handlers[sig] = Signal.trap(sig) { stop_proc.call(sig) }
86
+ end
87
+ end
88
+
89
+ begin
90
+ conn = PG.connect(@dsn)
91
+ begin
92
+ channel = "pgque_#{@queue}"
93
+ conn.exec("LISTEN #{conn.escape_identifier(channel)}")
94
+ @logger.info(
95
+ "consumer #{@name} listening on #{@queue} (poll=#{@poll_interval}s)"
96
+ )
97
+
98
+ while running?
99
+ poll_once(conn)
100
+ break unless running?
101
+ wait_for_notify_or_stop(conn)
102
+ end
103
+
104
+ if @stop_signum
105
+ @logger.info("received signal #{@stop_signum}, shutting down")
106
+ end
107
+ ensure
108
+ conn.close unless conn.finished?
109
+ end
110
+ ensure
111
+ # Clear running? before logging so callers observing the flag
112
+ # see "stopped" by the time the log line is written -- and so
113
+ # an exception during PG.connect, LISTEN, or the poll loop
114
+ # leaves the consumer in a consistent state instead of a
115
+ # ghost "running" with no live worker. Plain instance-var
116
+ # write -- not the trap-context-unsafe pattern.
117
+ @running = false
118
+ if in_main_thread
119
+ original_handlers.each { |sig, h| Signal.trap(sig, h || "DEFAULT") }
120
+ end
121
+ @logger.info("consumer #{@name} stopped")
122
+ end
123
+ end
124
+
125
+ def stop
126
+ @running = false
127
+ end
128
+
129
+ def running?
130
+ @running
131
+ end
132
+
133
+ # Public for testability; not part of the stable API.
134
+ def poll_once(conn)
135
+ conn.transaction do
136
+ client = Client.new(conn)
137
+ msgs =
138
+ if @subconsumer
139
+ client.receive_coop(
140
+ @queue, @name, @subconsumer,
141
+ max_messages: @max_messages,
142
+ dead_interval: @dead_interval,
143
+ )
144
+ else
145
+ client.receive(@queue, @name, @max_messages)
146
+ end
147
+
148
+ next if msgs.empty?
149
+
150
+ batch_id = msgs[0].batch_id
151
+ @logger.debug("batch #{batch_id}: #{msgs.size} message(s)")
152
+
153
+ nack_failed = dispatch_batch(client, batch_id, msgs)
154
+
155
+ next if nack_failed
156
+
157
+ rowcount = client.ack(batch_id)
158
+ if rowcount == 0
159
+ @logger.warn(
160
+ "pgque: ack batch #{batch_id} returned 0 -- stale or " \
161
+ "double ack (batch already finished or not found)",
162
+ )
163
+ end
164
+ end
165
+ end
166
+
167
+ private
168
+
169
+ def dispatch_batch(client, batch_id, msgs)
170
+ nack_failed = false
171
+ msgs.each do |msg|
172
+ handler = @handlers[msg.type] || @default_handler
173
+
174
+ if handler.nil?
175
+ if @unknown_handler_policy == "ack"
176
+ @logger.warn(
177
+ "no handler for event type=#{msg.type} ev_id=#{msg.msg_id}; " \
178
+ "acking",
179
+ )
180
+ next
181
+ end
182
+ @logger.warn(
183
+ "no handler for event type=#{msg.type} ev_id=#{msg.msg_id}; " \
184
+ "nacking",
185
+ )
186
+ begin
187
+ client.nack(batch_id, msg, retry_after: @retry_after,
188
+ reason: "no handler for type=#{msg.type}")
189
+ rescue StandardError => e
190
+ nack_failed = true
191
+ @logger.error(
192
+ "nack failed for unhandled msg_id=#{msg.msg_id}: " \
193
+ "#{e.class}: #{e.message}",
194
+ )
195
+ end
196
+ next
197
+ end
198
+
199
+ begin
200
+ handler.call(msg)
201
+ rescue StandardError => e
202
+ @logger.error(
203
+ "handler failed for msg_id=#{msg.msg_id}: " \
204
+ "#{e.class}: #{e.message}",
205
+ )
206
+ begin
207
+ client.nack(batch_id, msg, retry_after: @retry_after)
208
+ rescue StandardError => e2
209
+ nack_failed = true
210
+ @logger.error(
211
+ "nack failed for msg_id=#{msg.msg_id}: " \
212
+ "#{e2.class}: #{e2.message}",
213
+ )
214
+ end
215
+ end
216
+ end
217
+ nack_failed
218
+ end
219
+
220
+ def wait_for_notify_or_stop(conn)
221
+ drained = false
222
+ while conn.notifies
223
+ drained = true
224
+ end
225
+ return if drained
226
+
227
+ deadline = monotonic + @poll_interval
228
+ while running?
229
+ remaining = deadline - monotonic
230
+ return if remaining <= 0
231
+
232
+ slice = [WAIT_SLICE_SECONDS, remaining].min
233
+ notification = conn.wait_for_notify(slice)
234
+ return unless running?
235
+
236
+ if notification
237
+ while conn.notifies
238
+ # drain any queued notifications
239
+ end
240
+ return
241
+ end
242
+ end
243
+ end
244
+
245
+ def monotonic
246
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
247
+ end
248
+
249
+ # The default logger is effectively silent: it targets $stderr (so
250
+ # messages never collide with application stdout) and ships at level
251
+ # FATAL, which the consumer never emits. Set PGQUE_LOG_LEVEL=warn (or
252
+ # info, debug, error) to see warnings/info from the consumer, or
253
+ # pass logger: Logger.new(...) to Consumer.new for full control.
254
+ def default_logger
255
+ log = Logger.new($stderr)
256
+ log.progname = "pgque.consumer.#{@name}"
257
+ log.level = env_log_level || Logger::FATAL
258
+ log
259
+ end
260
+
261
+ def env_log_level
262
+ raw = ENV["PGQUE_LOG_LEVEL"]
263
+ return nil if raw.nil?
264
+
265
+ normalized = raw.strip.upcase
266
+ return nil if normalized.empty?
267
+
268
+ Logger.const_get(normalized)
269
+ rescue NameError
270
+ nil
271
+ end
272
+ end
273
+ end
@@ -0,0 +1,13 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+
3
+ module Pgque
4
+ class Error < StandardError; end
5
+
6
+ class ConnectionError < Error; end
7
+
8
+ class QueueNotFound < Error; end
9
+
10
+ class BatchNotFound < Error; end
11
+
12
+ class ConsumerNotFound < Error; end
13
+ end
@@ -0,0 +1,13 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+
3
+ module Pgque
4
+ class Event
5
+ attr_reader :payload, :type, :extra
6
+
7
+ def initialize(payload:, type: "default", extra: {})
8
+ @payload = payload
9
+ @type = type
10
+ @extra = extra
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,23 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+
3
+ module Pgque
4
+ class Message
5
+ attr_reader :msg_id, :batch_id, :type, :payload, :retry_count,
6
+ :created_at, :extra1, :extra2, :extra3, :extra4
7
+
8
+ def initialize(msg_id:, batch_id:, type:, payload:, retry_count:,
9
+ created_at:, extra1: nil, extra2: nil, extra3: nil,
10
+ extra4: nil)
11
+ @msg_id = msg_id
12
+ @batch_id = batch_id
13
+ @type = type
14
+ @payload = payload
15
+ @retry_count = retry_count
16
+ @created_at = created_at
17
+ @extra1 = extra1
18
+ @extra2 = extra2
19
+ @extra3 = extra3
20
+ @extra4 = extra4
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,5 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+
3
+ module Pgque
4
+ VERSION = "0.3.0.rc.1"
5
+ end
data/lib/pgque.rb ADDED
@@ -0,0 +1,35 @@
1
+ # Copyright 2026 Nikolay Samokhvalov. Apache-2.0 license.
2
+ # PgQue includes code derived from PgQ (ISC license,
3
+ # Marko Kreen / Skype Technologies OU).
4
+
5
+ require "json"
6
+ require "time"
7
+ require "pg"
8
+
9
+ require "pgque/version"
10
+ require "pgque/errors"
11
+ require "pgque/event"
12
+ require "pgque/message"
13
+ require "pgque/client"
14
+ require "pgque/consumer"
15
+
16
+ module Pgque
17
+ # Open a connection and return a Pgque::Client.
18
+ #
19
+ # Ruby's pg gem runs each statement in its own implicit transaction
20
+ # by default -- the equivalent of psycopg's autocommit=True. To group
21
+ # statements into one transaction, use conn.transaction { ... } on the
22
+ # underlying PG::Connection (client.conn). There is no autocommit
23
+ # flag because Ruby pg has no per-connection autocommit attribute to
24
+ # toggle; transaction control is per-call via the transaction block.
25
+ def self.connect(dsn)
26
+ client = Client.connect(dsn)
27
+ return client unless block_given?
28
+
29
+ begin
30
+ yield client
31
+ ensure
32
+ client.close
33
+ end
34
+ end
35
+ end
metadata ADDED
@@ -0,0 +1,108 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pgque
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0.rc.1
5
+ platform: ruby
6
+ authors:
7
+ - Nikolay Samokhvalov
8
+ - Dalto Curvelano Jr
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2026-05-26 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: pg
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: '1.5'
21
+ - - "<"
22
+ - !ruby/object:Gem::Version
23
+ version: '2.0'
24
+ type: :runtime
25
+ prerelease: false
26
+ version_requirements: !ruby/object:Gem::Requirement
27
+ requirements:
28
+ - - ">="
29
+ - !ruby/object:Gem::Version
30
+ version: '1.5'
31
+ - - "<"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ - !ruby/object:Gem::Dependency
35
+ name: minitest
36
+ requirement: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '5.0'
41
+ type: :development
42
+ prerelease: false
43
+ version_requirements: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ - !ruby/object:Gem::Dependency
49
+ name: rake
50
+ requirement: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '13.0'
55
+ type: :development
56
+ prerelease: false
57
+ version_requirements: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ description: 'Thin Ruby wrapper over the pgque SQL API: send, send_batch, receive,
63
+ ack, nack, force_next_tick, plus a polling Consumer with LISTEN/NOTIFY wakeup.'
64
+ email:
65
+ - nik@postgres.ai
66
+ - daltojr@gmail.com
67
+ executables: []
68
+ extensions: []
69
+ extra_rdoc_files: []
70
+ files:
71
+ - LICENSE
72
+ - README.md
73
+ - lib/pgque.rb
74
+ - lib/pgque/client.rb
75
+ - lib/pgque/consumer.rb
76
+ - lib/pgque/errors.rb
77
+ - lib/pgque/event.rb
78
+ - lib/pgque/message.rb
79
+ - lib/pgque/version.rb
80
+ homepage: https://github.com/NikolayS/pgque
81
+ licenses:
82
+ - Apache-2.0
83
+ metadata:
84
+ homepage_uri: https://github.com/NikolayS/pgque
85
+ source_code_uri: https://github.com/NikolayS/pgque
86
+ bug_tracker_uri: https://github.com/NikolayS/pgque/issues
87
+ documentation_uri: https://github.com/NikolayS/pgque/blob/main/docs/reference.md
88
+ changelog_uri: https://github.com/NikolayS/pgque/releases
89
+ post_install_message:
90
+ rdoc_options: []
91
+ require_paths:
92
+ - lib
93
+ required_ruby_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: 3.1.0
98
+ required_rubygems_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: '0'
103
+ requirements: []
104
+ rubygems_version: 3.5.3
105
+ signing_key:
106
+ specification_version: 4
107
+ summary: Ruby client for PgQue -- PgQ Universal Edition
108
+ test_files: []