lessormq 0.4.10

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: c98705d417270d83a9e0ffbaf97e029facaba7004cb0af53af67eab0bb7d4f92
4
+ data.tar.gz: d4ce2583368bcaad77ea9ab5981adb99ae7569d1eb377ddfc8d1ae4ae9e032a3
5
+ SHA512:
6
+ metadata.gz: fed44f6dcfa6b1f6c9b2b6d50e88ecb8849ce53472b9d8bc9b6a2c332fa2ca356e1d5a6d89fea7dd6369e0ae08100dd82042f96fa5dba04ce9bd75559379ef1a
7
+ data.tar.gz: d26401ebd4dfc494c19248a8a76cf9ccd47f1dfd84950ca01f3b78032b7378b27d466d98f41c4acff9f5306913a019fd7c4bf98cb33990a78299f8598cca4ed6
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # LessorMQ for Ruby
2
+
3
+ Client and worker for [LessorMQ](https://lessormq.dev), the message queue over HTTP where
4
+ the server decides and clients only claim, run, ack or fail. Retries, backoff, attempts
5
+ and the dead-letter set are the queue's settings; this library reports what happened and
6
+ leaves the rest to the server.
7
+
8
+ The gem is `lessormq`. It needs Ruby 3.3 or later and uses the standard library only
9
+ (`net/http`, `json`, `openssl`). For ActiveJob, see
10
+ [lessormq-rails](https://github.com/gsid-nl/lessormq/tree/main/clients/rails).
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ gem install lessormq
16
+ ```
17
+
18
+ or in a Gemfile:
19
+
20
+ ```ruby
21
+ gem "lessormq"
22
+ ```
23
+
24
+ ## Connect
25
+
26
+ ```ruby
27
+ require "lessormq"
28
+
29
+ client = LessorMQ::Client.new("https://mq.example.com", ENV.fetch("LESSORMQ_KEY"))
30
+ ```
31
+
32
+ The key needs the `publish` scope to publish and `consume` to work a queue (see
33
+ [tenants and keys](https://lessormq.dev/docs/protocol#tenants-and-keys)). Options:
34
+ `http_retries` (3), `retry_delay` (0.1 seconds, times the attempt), `timeout` (10
35
+ seconds per request; a claim gets its wait on top), `auto_dedup_key` (true),
36
+ `logger` (a `Logger` for the retries; nothing is logged by default), and `transport`
37
+ (anything that answers `request(method, path, headers, body, timeout)`, for a proxy or
38
+ a test). The client is thread-safe and keeps its connections alive.
39
+
40
+ ## Publish
41
+
42
+ ```ruby
43
+ client.publish("mail", { to: "ada@example.com", template: "welcome" })
44
+
45
+ client.publish(
46
+ "invoices",
47
+ { invoice: 1042 },
48
+ dedup_key: "invoice-1042", # one open message per key
49
+ delay_seconds: 600, # or available_at: Time
50
+ max_attempts: 3, # within the queue's max_attempts_limit
51
+ headers: { "type" => "InvoiceDue" }
52
+ )
53
+ ```
54
+
55
+ The body is any JSON value. Every publish carries a dedup key (your own, or one the client
56
+ makes up), so the client can safely retry it after a network error without creating a
57
+ second message. `publish` returns a `LessorMQ::Published` (`id`, `status`,
58
+ `available_at`, `duplicate?`).
59
+
60
+ ## Work
61
+
62
+ ```ruby
63
+ worker = LessorMQ::Worker.new(client, "mail", route: ENV["VPN_ID"], concurrency: 4) do |message, job|
64
+ raise LessorMQ::PermanentFailure, "no recipient" unless message.body["to"]
65
+
66
+ Mailer.deliver(message.body)
67
+ end
68
+
69
+ worker.run
70
+ ```
71
+
72
+ - The block returns: the message is acked.
73
+ - It raises: the message is failed with the exception's class and message. Raise
74
+ `LessorMQ::PermanentFailure`, or include `LessorMQ::Permanent` in your own error class
75
+ (or give it a `permanent?` method), when the input itself is unusable.
76
+ - What happens after a failure is not up to the worker. The queue's settings decide
77
+ whether and when the message comes back, and when it goes to the dead-letter set.
78
+ - While the block runs, a thread extends the lease every third of it. A block that
79
+ outlives its lease anyway is not reported: the message is someone else's by then.
80
+ `job.lease_lost?` tells a long job to stop early.
81
+ - `concurrency` runs that many messages side by side, each in a thread with its own
82
+ claims.
83
+ - SIGTERM and SIGINT stop the worker after the current messages. A claim that is already
84
+ waiting is not cut off: it ends within `wait_seconds`, and a message it brings is given
85
+ back unrun.
86
+
87
+ The handler can also be anything that responds to `call(message, job)`. `message` has
88
+ `id`, `queue`, `body`, `headers`, `attempt`, `max_attempts`, `created_at` and
89
+ `last_attempt?`; `job` has `lease`, `message`, `extend_lease` and `lease_lost?`.
90
+
91
+ `Worker` options: `consumer` (host:pid by default), `route`, `wait_seconds` (20),
92
+ `lease_seconds`, `extend_every`, `auto_extend`, `concurrency` (1), `handle_signals`,
93
+ `max_messages`, `max_seconds`, `error_pause` (1 second), `logger`. `worker.stop` stops
94
+ it from another thread.
95
+
96
+ ## Without the worker
97
+
98
+ ```ruby
99
+ lease = client.claim("mail", wait_seconds: 20)
100
+ if lease
101
+ begin
102
+ Mailer.deliver(lease.message.body)
103
+ client.ack(lease)
104
+ rescue StandardError => e
105
+ result = client.fail(lease, e) # result.outcome: retrying, dead_lettered or discarded
106
+ end
107
+ end
108
+ ```
109
+
110
+ `client.extend_lease(lease)` keeps a lease while a long job runs (it is not called
111
+ `extend`, which every Ruby object already has), and `client.release(lease)` hands a
112
+ message back without counting the attempt. All of them raise `LessorMQ::LeaseLost` once
113
+ the lease has ended: drop the message then, it is someone else's now.
114
+
115
+ `client.fail(lease, error, permanent: true)` reports a permanent failure; `details:` and
116
+ `type:` override what is taken from the exception, and a String works as the error too.
117
+ The answer says what the server did. It is for logging: the queue has decided already.
118
+
119
+ Many short jobs go faster in batches: `client.claim_batch("mail", 50)` leases up to 50
120
+ ready messages at once (each with its own lease), and `client.ack_batch(leases)` acks them
121
+ in one request, with an outcome per lease (`acked`, `lease_lost`, ...). A message that
122
+ fails is reported on its own with `fail`. `client.stats("mail")` reads a queue's counts.
123
+
124
+ ## Errors
125
+
126
+ Everything the library raises is a `LessorMQ::Error`: `LessorMQ::TransportError` when the
127
+ server cannot be reached, `LessorMQ::ApiError` (with `status`, `code`, `detail` and
128
+ `errors`) when it answers with a
129
+ [problem](https://lessormq.dev/docs/protocol#errors), in subclasses for the codes a
130
+ client acts on: `LeaseLost`, `ValidationFailed`, `Unauthorized`, `Forbidden` (also
131
+ `tenant_suspended` and `quota_exceeded`), `NotFound`, `Conflict`, `PayloadTooLarge`,
132
+ `RateLimited` (with `retry_after`) and `ServerError`.
133
+
134
+ Network errors, 5xx and 429 are retried (`http_retries: 3`, `retry_delay: 0.1` seconds
135
+ times the attempt, or the server's `Retry-After`), for every call that is safe to repeat:
136
+ all of them, given the automatic dedup key on publish. That is the only retrying the
137
+ library does.
138
+
139
+ ## Development
140
+
141
+ ```sh
142
+ cd clients/ruby
143
+ bundle install
144
+ bundle exec rake test
145
+ ```
146
+
147
+ The unit tests run against a scripted transport (`test/fake_transport.rb`), no server
148
+ needed. The library passes the
149
+ [conformance suite](https://github.com/gsid-nl/lessormq/tree/main/conformance) through
150
+ `test/conformance_adapter.rb`, from the repository root:
151
+
152
+ ```sh
153
+ LESSORMQ_ADAPTER_CMD="ruby clients/ruby/test/conformance_adapter.rb" conformance/run.sh
154
+ ```
155
+
156
+ See [writing a client](https://lessormq.dev/docs/writing-a-client) for the rules it follows.
@@ -0,0 +1,263 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "securerandom"
5
+
6
+ module LessorMQ
7
+ # The protocol calls of LessorMQ (https://lessormq.dev/docs/protocol), nothing more.
8
+ #
9
+ # The client never decides what happens to a message: no retry of a failed job, no
10
+ # delay, no dead-lettering. It reports, and the queue decides. It does retry its own
11
+ # HTTP calls when that is safe: network errors, 5xx and 429, for every call that can be
12
+ # repeated (all of them, given the automatic dedup key on publish).
13
+ #
14
+ # Thread-safe: a worker's keepalive thread shares it.
15
+ class Client
16
+ USER_AGENT = "lessormq-ruby/1"
17
+ MAX_ERROR_MESSAGE = 65_535
18
+ MAX_ERROR_TYPE = 255
19
+
20
+ # One protocol call as HTTP: what to send, whether it may be sent again, and how
21
+ # much longer than the timeout it may take.
22
+ Call = Struct.new(:verb, :path, :payload, :repeatable, :extra_timeout)
23
+ Response = Struct.new(:status, :body)
24
+ private_constant :Call, :Response
25
+
26
+ # http_retries:: retries after a network error, a 5xx or a 429, for calls that are
27
+ # safe to repeat (all but a publish without a dedup key)
28
+ # retry_delay:: base delay between retries in seconds, times the attempt number
29
+ # auto_dedup_key:: give every publish without a dedup key one of its own, so a retried
30
+ # publish can never create a second message
31
+ # timeout:: seconds per request; a claim gets its wait on top
32
+ # transport:: sends the requests; NetHTTPTransport by default
33
+ # logger:: a Logger for the retries; nothing is logged by default
34
+ def initialize(base_url, api_key, http_retries: 3, retry_delay: 0.1, auto_dedup_key: true, timeout: 10,
35
+ user_agent: USER_AGENT, transport: nil, logger: nil)
36
+ @base_url = base_url.to_s.chomp("/")
37
+ @api_key = api_key
38
+ @http_retries = http_retries
39
+ @retry_delay = retry_delay
40
+ @auto_dedup_key = auto_dedup_key
41
+ @timeout = timeout
42
+ @user_agent = user_agent
43
+ @transport = transport || NetHTTPTransport.new(@base_url)
44
+ @logger = logger
45
+ end
46
+
47
+ attr_reader :logger
48
+
49
+ # Never the key.
50
+ def inspect
51
+ "#<LessorMQ::Client #{@base_url}>"
52
+ end
53
+ alias to_s inspect
54
+
55
+ # Puts a message on a queue. +body+ is any JSON value.
56
+ #
57
+ # With a dedup key (yours, or the automatic one), an open message with that key is
58
+ # returned instead of a new one: Published#duplicate?.
59
+ def publish(queue, body, headers: nil, dedup_key: nil, delay_seconds: nil, available_at: nil, max_attempts: nil)
60
+ dedup_key = "lmq-auto-#{SecureRandom.hex(12)}" if dedup_key.nil? && @auto_dedup_key
61
+ payload = { "body" => body }
62
+ payload["headers"] = headers if headers && !headers.empty?
63
+ payload["dedup_key"] = dedup_key unless dedup_key.nil?
64
+ payload["delay_seconds"] = delay_seconds unless delay_seconds.nil?
65
+ payload["available_at"] = Times.format(available_at) unless available_at.nil?
66
+ payload["max_attempts"] = max_attempts unless max_attempts.nil?
67
+ # Without a dedup key a repeated publish could create a second message.
68
+ call = Call.new("POST", "/v1/queues/#{segment(queue)}/messages", payload, !dedup_key.nil?, 0)
69
+ Published.from_api(send_call(call).body)
70
+ end
71
+
72
+ # Leases the next message of a queue, waiting up to +wait_seconds+ (at most 20) for
73
+ # one. Nil when nothing became available, or the queue is paused.
74
+ def claim(queue, consumer: nil, route: nil, wait_seconds: 0, lease_seconds: nil)
75
+ response = send_call(claim_call(queue, consumer, route, wait_seconds, lease_seconds, nil))
76
+ response.status == 204 ? nil : Lease.from_api(response.body)
77
+ end
78
+
79
+ # Leases up to +max_messages+ (1 to 100) ready messages at once, oldest first, each
80
+ # with a receipt of its own. Waits up to +wait_seconds+ only while there is none; an
81
+ # empty array when nothing became available. Report each lease as usual, or ack them
82
+ # together with #ack_batch.
83
+ def claim_batch(queue, max_messages, consumer: nil, route: nil, wait_seconds: 0, lease_seconds: nil)
84
+ response = send_call(claim_call(queue, consumer, route, wait_seconds, lease_seconds, max_messages))
85
+ return [] if response.status == 204
86
+
87
+ Array(response.body["items"]).map { |item| Lease.from_api(item) }
88
+ end
89
+
90
+ # Moves the end of the lease to now plus +lease_seconds+ (or the queue's lease), and
91
+ # returns the lease. (Not +extend+: that is Object#extend.)
92
+ #
93
+ # Raises LeaseLost when the lease already ended.
94
+ def extend_lease(lease, lease_seconds: nil)
95
+ payload = { "receipt" => lease.receipt }
96
+ payload["lease_seconds"] = lease_seconds unless lease_seconds.nil?
97
+ response = send_call(Call.new("POST", message_path(lease, "extend"), payload, true, 0))
98
+ lease.lease_until = Times.parse(response.body["lease_until"])
99
+ lease
100
+ end
101
+
102
+ # Reports success. Raises LeaseLost when the lease already ended.
103
+ def ack(lease)
104
+ send_call(Call.new("POST", message_path(lease, "ack"), { "receipt" => lease.receipt }, true, 0))
105
+ nil
106
+ end
107
+
108
+ # Reports success for up to 100 leases in one request. The outcomes are in the order
109
+ # of +leases+: "acked" (also when acked before), "lease_lost", "not_found" or
110
+ # "forbidden"; one that cannot be acked does not hold up the others.
111
+ def ack_batch(leases)
112
+ items = leases.map { |lease| { "message" => lease.message.id, "receipt" => lease.receipt } }
113
+ response = send_call(Call.new("POST", "/v1/acks", { "leases" => items }, true, 0))
114
+ outcomes = Array(response.body["items"])
115
+ Array.new(leases.size) { |i| outcomes[i].is_a?(Hash) ? outcomes[i]["outcome"].to_s : "not_found" }
116
+ end
117
+
118
+ # Reports failure. The server decides what follows and says so in the FailResult.
119
+ #
120
+ # error:: the exception, or a message
121
+ # permanent:: the input itself cannot be processed; by default whether +error+ is
122
+ # marked permanent (LessorMQ.permanent?)
123
+ # details:: any JSON value with more context; by default where the exception was raised
124
+ # type:: the error type; by default the exception's class
125
+ #
126
+ # Raises LeaseLost when the lease already ended.
127
+ def fail(lease, error, permanent: nil, details: nil, type: nil)
128
+ if error.is_a?(Exception)
129
+ text = error.message
130
+ type ||= error.class.name || "Exception"
131
+ details ||= origin(error)
132
+ permanent = LessorMQ.permanent?(error) if permanent.nil?
133
+ else
134
+ text = error.to_s
135
+ end
136
+ report = { "message" => utf8(text)[0, MAX_ERROR_MESSAGE] }
137
+ report["message"] = "(no message)" if report["message"].empty?
138
+ report["type"] = utf8(type)[0, MAX_ERROR_TYPE] unless type.nil?
139
+ report["details"] = details unless details.nil?
140
+ payload = { "receipt" => lease.receipt, "error" => report, "permanent" => permanent ? true : false }
141
+ FailResult.from_api(send_call(Call.new("POST", message_path(lease, "fail"), payload, true, 0)).body)
142
+ end
143
+
144
+ # Gives the message back without an outcome; the attempt does not count. Raises
145
+ # LeaseLost when the lease already ended.
146
+ def release(lease, delay_seconds: 0)
147
+ payload = { "receipt" => lease.receipt }
148
+ payload["delay_seconds"] = delay_seconds if delay_seconds.positive?
149
+ send_call(Call.new("POST", message_path(lease, "release"), payload, true, 0))
150
+ nil
151
+ end
152
+
153
+ # A queue's counts. Needs the consume or admin scope. Not part of the protocol; for
154
+ # monitoring.
155
+ def stats(queue)
156
+ body = send_call(Call.new("GET", "/v1/queues/#{segment(queue)}", nil, true, 0)).body
157
+ Stats.from_api(body.is_a?(Hash) && body["stats"].is_a?(Hash) ? body["stats"] : {})
158
+ end
159
+
160
+ private
161
+
162
+ def claim_call(queue, consumer, route, wait_seconds, lease_seconds, max_messages)
163
+ payload = {}
164
+ payload["consumer"] = consumer unless consumer.nil?
165
+ payload["route"] = route unless route.nil?
166
+ payload["wait_seconds"] = wait_seconds if wait_seconds.positive?
167
+ payload["lease_seconds"] = lease_seconds unless lease_seconds.nil?
168
+ payload["max_messages"] = max_messages unless max_messages.nil?
169
+ # A claim whose answer got lost leaves a lease that simply expires and counts as an
170
+ # attempt, so claims are retried like the rest.
171
+ Call.new("POST", "/v1/queues/#{segment(queue)}/claims", payload, true, [wait_seconds, 0].max)
172
+ end
173
+
174
+ def send_call(call)
175
+ headers = {
176
+ "Authorization" => "Bearer #{@api_key}",
177
+ "Accept" => "application/json",
178
+ "User-Agent" => @user_agent
179
+ }
180
+ body = nil
181
+ unless call.payload.nil?
182
+ headers["Content-Type"] = "application/json"
183
+ body = JSON.generate(call.payload)
184
+ end
185
+
186
+ attempt = 0
187
+ loop do
188
+ attempt += 1
189
+ begin
190
+ status, response_headers, raw = @transport.request(
191
+ call.verb, call.path, headers, body, @timeout + call.extra_timeout
192
+ )
193
+ rescue TransportError => e
194
+ unless call.repeatable && attempt <= @http_retries
195
+ raise TransportError, "#{call.verb} #{call.path} failed: #{e.message}"
196
+ end
197
+
198
+ pause(attempt, nil, call.path, e.message)
199
+ next
200
+ end
201
+
202
+ parsed = parse(raw)
203
+ return Response.new(status, parsed) if status < 400
204
+
205
+ retry_after = retry_after(response_headers)
206
+ error = ApiError.from_response(status, parsed, retry_after)
207
+ # A 429 was not processed at all, so it is always safe to send again.
208
+ again = error.is_a?(RateLimited) || (call.repeatable && error.is_a?(ServerError))
209
+ raise error unless again && attempt <= @http_retries
210
+
211
+ pause(attempt, retry_after, call.path, error.message)
212
+ end
213
+ end
214
+
215
+ def pause(attempt, retry_after, path, reason)
216
+ delay = retry_after.nil? ? @retry_delay * attempt : retry_after
217
+ @logger&.warn("LessorMQ request failed, retrying (path=#{path} attempt=#{attempt} delay=#{delay} " \
218
+ "reason=#{reason})")
219
+ sleep(delay)
220
+ end
221
+
222
+ def parse(raw)
223
+ return nil if raw.nil? || raw.empty?
224
+
225
+ JSON.parse(raw)
226
+ rescue JSON::ParserError
227
+ # A proxy's error page, say: the status says enough.
228
+ nil
229
+ end
230
+
231
+ def retry_after(headers)
232
+ value = headers && headers["retry-after"]
233
+ Integer(value, 10) if value
234
+ rescue ArgumentError, TypeError
235
+ nil
236
+ end
237
+
238
+ def message_path(lease, action)
239
+ "/v1/messages/#{segment(lease.message.id)}/#{action}"
240
+ end
241
+
242
+ # A path segment, percent-encoded (a/b is a%2Fb).
243
+ def segment(value)
244
+ value.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |c| format("%%%02X", c.ord) }
245
+ end
246
+
247
+ # Where the exception was raised: the innermost frame of its backtrace.
248
+ def origin(error)
249
+ location = error.backtrace_locations&.first
250
+ return { "file" => location.path, "line" => location.lineno } if location
251
+
252
+ line = error.backtrace&.first
253
+ line && (match = line.match(/\A(.+?):(\d+)/)) ? { "file" => match[1], "line" => match[2].to_i } : nil
254
+ end
255
+
256
+ def utf8(text)
257
+ text = text.to_s
258
+ return text.scrub if text.encoding == Encoding::UTF_8
259
+
260
+ text.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
261
+ end
262
+ end
263
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ # Everything this library raises.
5
+ class Error < StandardError; end
6
+
7
+ # The server could not be reached, after the configured retries.
8
+ class TransportError < Error; end
9
+
10
+ # The server answered with an error (RFC 9457 problem details). +code+ is the stable
11
+ # problem code to branch on; the subclasses cover the ones a client acts on.
12
+ class ApiError < Error
13
+ attr_reader :status, :code, :detail, :errors
14
+
15
+ def initialize(status, code, detail = "", errors = [])
16
+ @status = status
17
+ @code = code
18
+ @detail = detail
19
+ @errors = errors
20
+ super(detail.empty? ? "LessorMQ error #{status} (#{code})" : detail)
21
+ end
22
+
23
+ # The error for an answer, of the subclass for its code.
24
+ def self.from_response(status, body, retry_after = nil)
25
+ problem = body.is_a?(Hash) ? body : {}
26
+ code = problem["code"].is_a?(String) ? problem["code"] : code_for(status)
27
+ detail = problem["detail"].is_a?(String) ? problem["detail"] : ""
28
+ errors = problem["errors"].is_a?(Array) ? problem["errors"] : []
29
+
30
+ return RateLimited.new(status, code, detail, errors, retry_after) if code == "rate_limited"
31
+
32
+ klass = BY_CODE.fetch(code) { status >= 500 ? ServerError : ApiError }
33
+ klass.new(status, code, detail, errors)
34
+ end
35
+
36
+ def self.code_for(status)
37
+ case status
38
+ when 401 then "unauthorized"
39
+ when 403 then "forbidden"
40
+ when 404 then "not_found"
41
+ when 413 then "payload_too_large"
42
+ when 429 then "rate_limited"
43
+ when 500.. then "internal"
44
+ else "validation_failed"
45
+ end
46
+ end
47
+ private_class_method :code_for
48
+ end
49
+
50
+ # The receipt is not the current lease of the message. The lease expired, was
51
+ # released, or the message was claimed again. Stop reporting on it: the server has
52
+ # already made it available again.
53
+ class LeaseLost < ApiError; end
54
+
55
+ # The request was rejected as invalid; +errors+ names each field.
56
+ class ValidationFailed < ApiError; end
57
+
58
+ # The API key is missing, unknown or revoked.
59
+ class Unauthorized < ApiError; end
60
+
61
+ # The key lacks the scope or the queue, or its tenant is suspended (code
62
+ # +tenant_suspended+), or a quota that waiting does not lift (+quota_exceeded+).
63
+ class Forbidden < ApiError; end
64
+
65
+ # No such queue or message for this tenant.
66
+ class NotFound < ApiError; end
67
+
68
+ # The message is in a state that does not allow this (+invalid_state+).
69
+ class Conflict < ApiError; end
70
+
71
+ # Body and headers exceed the queue's +max_message_bytes+.
72
+ class PayloadTooLarge < ApiError; end
73
+
74
+ # The tenant exceeded a rate limit or its open-message quota, after the configured
75
+ # retries. +retry_after+ is the server's Retry-After in seconds, or nil.
76
+ class RateLimited < ApiError
77
+ attr_reader :retry_after
78
+
79
+ def initialize(status, code, detail = "", errors = [], retry_after = nil)
80
+ @retry_after = retry_after
81
+ super(status, code, detail, errors)
82
+ end
83
+ end
84
+
85
+ # The server failed (5xx), after the configured retries.
86
+ class ServerError < ApiError; end
87
+
88
+ class ApiError
89
+ BY_CODE = {
90
+ "lease_lost" => LeaseLost,
91
+ "validation_failed" => ValidationFailed,
92
+ "unauthorized" => Unauthorized,
93
+ "forbidden" => Forbidden,
94
+ "tenant_suspended" => Forbidden,
95
+ "quota_exceeded" => Forbidden,
96
+ "not_found" => NotFound,
97
+ "invalid_state" => Conflict,
98
+ "payload_too_large" => PayloadTooLarge
99
+ }.freeze
100
+ end
101
+
102
+ # Marks an error as permanent: the message itself cannot be processed (it cannot be
103
+ # decoded, it fails validation), so another attempt would only fail again. Include it
104
+ # in your own error class, or raise PermanentFailure. A fact for the server: the
105
+ # queue's +on_permanent+ decides what it means.
106
+ #
107
+ # class BadInput < ArgumentError
108
+ # include LessorMQ::Permanent
109
+ # end
110
+ module Permanent; end
111
+
112
+ # Raise from a handler when the message itself cannot be processed.
113
+ class PermanentFailure < StandardError
114
+ include Permanent
115
+ end
116
+
117
+ # Whether an error is marked as permanent: it includes Permanent, or it has a
118
+ # +permanent?+ method that says so.
119
+ def self.permanent?(error)
120
+ return true if error.is_a?(Permanent)
121
+
122
+ error.respond_to?(:permanent?) && error.permanent? ? true : false
123
+ end
124
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module LessorMQ
6
+ # Times as the API writes them: RFC 3339, UTC, whole seconds.
7
+ module Times
8
+ module_function
9
+
10
+ def parse(value)
11
+ Time.iso8601(value.to_s).utc
12
+ end
13
+
14
+ def format(time)
15
+ time.getutc.strftime("%Y-%m-%dT%H:%M:%SZ")
16
+ end
17
+ end
18
+
19
+ # A delivered message: what a handler runs. +body+ is the JSON value as published
20
+ # (a Hash with string keys, an Array, a String, ...).
21
+ Message = Data.define(:id, :queue, :body, :headers, :attempt, :max_attempts, :created_at) do
22
+ # Whether this attempt is the last one the queue allows.
23
+ def last_attempt?
24
+ attempt >= max_attempts
25
+ end
26
+
27
+ def self.from_api(data)
28
+ headers = data["headers"]
29
+ new(
30
+ id: data["id"].to_s,
31
+ queue: data["queue"].to_s,
32
+ body: data["body"],
33
+ headers: headers.is_a?(Hash) ? headers : {},
34
+ attempt: Integer(data["attempt"]),
35
+ max_attempts: Integer(data["max_attempts"]),
36
+ created_at: Times.parse(data["created_at"])
37
+ )
38
+ end
39
+ end
40
+
41
+ # A claimed message and the proof of holding it. Extend, ack, fail and release take
42
+ # the lease; only its receipt is accepted, and only until +lease_until+, which
43
+ # Client#extend_lease moves.
44
+ class Lease
45
+ attr_reader :receipt, :message
46
+ attr_accessor :lease_until
47
+
48
+ def initialize(receipt, lease_until, message)
49
+ @receipt = receipt
50
+ @lease_until = lease_until
51
+ @message = message
52
+ end
53
+
54
+ def seconds_left
55
+ lease_until - Time.now
56
+ end
57
+
58
+ def self.from_api(data)
59
+ new(data["receipt"].to_s, Times.parse(data["lease_until"]), Message.from_api(data["message"]))
60
+ end
61
+
62
+ # Never the receipt: it is the proof of holding the message.
63
+ def inspect
64
+ "#<LessorMQ::Lease message=#{message.id} lease_until=#{Times.format(lease_until)}>"
65
+ end
66
+ end
67
+
68
+ # The answer to a publish: the message, or the open one with the same dedup key
69
+ # (+duplicate?+).
70
+ Published = Data.define(:id, :queue, :status, :created_at, :available_at, :duplicate) do
71
+ alias_method :duplicate?, :duplicate
72
+
73
+ def self.from_api(data)
74
+ new(
75
+ id: data["id"].to_s,
76
+ queue: data["queue"].to_s,
77
+ status: data["status"].to_s,
78
+ created_at: Times.parse(data["created_at"]),
79
+ available_at: Times.parse(data["available_at"]),
80
+ duplicate: data["duplicate"] == true
81
+ )
82
+ end
83
+ end
84
+
85
+ # What the server did with a failed attempt. For logging: a client never acts on it.
86
+ FailResult = Data.define(:outcome, :available_at, :attempt, :max_attempts) do
87
+ def self.from_api(data)
88
+ available_at = data["available_at"]
89
+ new(
90
+ outcome: data["outcome"].to_s,
91
+ available_at: available_at ? Times.parse(available_at) : nil,
92
+ attempt: Integer(data["attempt"]),
93
+ max_attempts: Integer(data["max_attempts"])
94
+ )
95
+ end
96
+ end
97
+
98
+ class FailResult
99
+ RETRYING = "retrying"
100
+ DEAD_LETTERED = "dead_lettered"
101
+ DISCARDED = "discarded"
102
+ end
103
+
104
+ # A queue's counts, for monitoring. Not part of the protocol. Counts the server adds
105
+ # later are in +other+.
106
+ Stats = Data.define(
107
+ :ready, :delayed, :processing, :completed, :failed,
108
+ :oldest_ready_seconds, :oldest_processing_seconds, :other
109
+ ) do
110
+ def self.from_api(data)
111
+ known = members - [:other]
112
+ numbers = data.select { |_name, value| value.is_a?(Numeric) }.transform_values(&:to_i)
113
+ values = known.to_h { |name| [name, numbers.fetch(name.to_s, 0)] }
114
+ new(**values, other: numbers.reject { |name, _| known.include?(name.to_sym) })
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module LessorMQ
8
+ # Sends one HTTP request. The client brings everything else (the key, retries, errors),
9
+ # so a transport of your own only has to answer #request:
10
+ #
11
+ # request(method, path, headers, body, timeout) => [status, headers, body]
12
+ #
13
+ # +headers+ in the answer have lower-case names; +body+ is a String or nil. A request
14
+ # that did not get an answer raises TransportError.
15
+ #
16
+ # This one is Net::HTTP with a small pool of kept-alive connections, so a worker's
17
+ # claims and the extends from its keepalive thread can run at the same time.
18
+ class NetHTTPTransport
19
+ NETWORK_ERRORS = [
20
+ IOError, SystemCallError, SocketError, Timeout::Error, Net::HTTPBadResponse, Net::ProtocolError,
21
+ OpenSSL::SSL::SSLError
22
+ ].freeze
23
+
24
+ METHODS = { "GET" => Net::HTTP::Get, "POST" => Net::HTTP::Post, "PATCH" => Net::HTTP::Patch }.freeze
25
+
26
+ # +open_timeout+ is the time to connect; the time to answer is per request.
27
+ def initialize(base_url, open_timeout: 5, pool_size: 8)
28
+ @uri = URI.parse(base_url)
29
+ @open_timeout = open_timeout
30
+ @pool_size = pool_size
31
+ @idle = []
32
+ @lock = Mutex.new
33
+ @pid = Process.pid
34
+ end
35
+
36
+ def request(method, path, headers, body, timeout)
37
+ http = checkout
38
+ begin
39
+ request = METHODS.fetch(method).new(@uri.path.chomp("/") + path, headers)
40
+ request.body = body if body
41
+ http.read_timeout = timeout
42
+ http.write_timeout = timeout
43
+ response = http.request(request)
44
+ rescue *NETWORK_ERRORS => e
45
+ http.finish if http.started?
46
+ raise TransportError, "#{e.class}: #{e.message}"
47
+ end
48
+ checkin(http)
49
+ [response.code.to_i, response.to_hash.transform_values { |values| values.join(", ") }, response.body]
50
+ end
51
+
52
+ private
53
+
54
+ def checkout
55
+ @lock.synchronize do
56
+ # Connections from before a fork belong to the parent.
57
+ if @pid != Process.pid
58
+ @idle.clear
59
+ @pid = Process.pid
60
+ end
61
+ @idle.pop
62
+ end || connect
63
+ end
64
+
65
+ def checkin(http)
66
+ @lock.synchronize do
67
+ if @idle.size < @pool_size && @pid == Process.pid
68
+ @idle.push(http)
69
+ http = nil
70
+ end
71
+ end
72
+ http&.finish if http&.started?
73
+ end
74
+
75
+ def connect
76
+ http = Net::HTTP.new(@uri.host, @uri.port)
77
+ http.use_ssl = @uri.scheme == "https"
78
+ http.open_timeout = @open_timeout
79
+ # Net::HTTP retries a request on its own only for idempotent methods; the client
80
+ # decides about retries.
81
+ http.max_retries = 0
82
+ http.start
83
+ http
84
+ rescue *NETWORK_ERRORS => e
85
+ raise TransportError, "#{e.class}: #{e.message}"
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ # Written from the git tag when the gem is released.
5
+ VERSION = "0.4.10"
6
+ end
@@ -0,0 +1,286 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module LessorMQ
6
+ # What a handler gets besides the message: the lease, and a way to keep it.
7
+ #
8
+ # The worker already extends the lease on a timer; call #extend_lease yourself only
9
+ # with +auto_extend: false+, or to ask for a longer lease at once.
10
+ class Job
11
+ attr_reader :lease
12
+
13
+ def initialize(client, lease)
14
+ @client = client
15
+ @lease = lease
16
+ @lease_lost = false
17
+ end
18
+
19
+ def message
20
+ @lease.message
21
+ end
22
+
23
+ # Raises LeaseLost when the lease already ended.
24
+ def extend_lease(lease_seconds: nil)
25
+ @client.extend_lease(@lease, lease_seconds: lease_seconds)
26
+ rescue LeaseLost
27
+ @lease_lost = true
28
+ raise
29
+ end
30
+
31
+ # Whether the lease was lost while the handler ran: the message is someone else's
32
+ # now, and the outcome will not be reported. A long handler can check it and stop.
33
+ def lease_lost?
34
+ @lease_lost
35
+ end
36
+ end
37
+
38
+ # Claims messages of one queue and runs a handler on each:
39
+ #
40
+ # worker = LessorMQ::Worker.new(client, "mail") do |message, job|
41
+ # Mailer.deliver(message.body)
42
+ # end
43
+ # worker.run
44
+ #
45
+ # The handler returns: the message is acked. It raises: the message is failed with the
46
+ # exception's class and message, as permanent when LessorMQ.permanent?(error). What
47
+ # happens next (another attempt, when, or the dead-letter set) is decided by the queue.
48
+ # While the handler runs, a thread extends the lease every third of it. On SIGTERM or
49
+ # SIGINT the worker stops after the current messages.
50
+ class Worker
51
+ # What a handler may raise to fail its message. Signals, exit and running out of
52
+ # memory end the worker instead; the lease then expires and the attempt counts.
53
+ HANDLER_ERRORS = [StandardError, ScriptError, SystemStackError].freeze
54
+
55
+ STOP_SIGNALS = %w[TERM INT].freeze
56
+
57
+ attr_reader :queue
58
+
59
+ # consumer:: shown to administrators; host:pid by default
60
+ # route:: the path this worker runs jobs through (a VPN exit, a proxy)
61
+ # wait_seconds:: long-poll wait per claim (at most 20)
62
+ # lease_seconds:: lease per claim and per extend; the queue's when nil
63
+ # extend_every:: seconds between automatic extends; a third of the lease when nil
64
+ # auto_extend:: extend the lease while a handler runs
65
+ # concurrency:: messages handled at the same time, each in a thread of its own
66
+ # with its own claims
67
+ # handle_signals:: stop after the current messages on SIGTERM or SIGINT
68
+ # max_messages:: stop after this many messages
69
+ # max_seconds:: stop claiming after running this long
70
+ # error_pause:: seconds to wait after the server could not be reached
71
+ # logger:: a Logger; the client's by default
72
+ def initialize(client, queue, handler = nil, consumer: nil, route: nil, wait_seconds: 20, lease_seconds: nil,
73
+ extend_every: nil, auto_extend: true, concurrency: 1, handle_signals: true, max_messages: nil,
74
+ max_seconds: nil, error_pause: 1.0, logger: nil, &block)
75
+ @handler = handler || block
76
+ raise ArgumentError, "a handler is required: a block, or anything that responds to call" unless @handler
77
+
78
+ @client = client
79
+ @queue = queue
80
+ @consumer = consumer || Worker.default_consumer
81
+ @route = route
82
+ @wait_seconds = wait_seconds
83
+ @lease_seconds = lease_seconds
84
+ @extend_every = extend_every
85
+ @auto_extend = auto_extend
86
+ @concurrency = [concurrency.to_i, 1].max
87
+ @handle_signals = handle_signals
88
+ @max_messages = max_messages
89
+ @max_seconds = max_seconds
90
+ @error_pause = error_pause
91
+ @logger = logger || client.logger
92
+ @counter = Mutex.new
93
+ @started = 0
94
+ @handled = 0
95
+ @stopping = false
96
+ @wake = Thread::Queue.new
97
+ end
98
+
99
+ # Messages handled so far.
100
+ def handled
101
+ @counter.synchronize { @handled }
102
+ end
103
+
104
+ # Claims and handles messages until #stop, a signal, or a configured limit, and
105
+ # returns once every message in hand is reported, with the number handled.
106
+ #
107
+ # A claim already waiting is not cut off when the worker is asked to stop (that
108
+ # could leave a leased message to run out): it ends within +wait_seconds+, and a
109
+ # message it brings is given back with a release. A stopped worker stays stopped,
110
+ # also when #stop came before #run.
111
+ def run
112
+ @deadline = @max_seconds && (monotonic + @max_seconds)
113
+ previous = trap_signals if @handle_signals
114
+ begin
115
+ if @concurrency == 1
116
+ loop_once until stop?
117
+ else
118
+ threads = Array.new(@concurrency) do |i|
119
+ Thread.new { loop_once until stop? }.tap { |thread| thread.name = "lessormq-#{i}" }
120
+ end
121
+ threads.each(&:join)
122
+ end
123
+ ensure
124
+ previous&.each { |signal, handler| Signal.trap(signal, handler) }
125
+ end
126
+ handled
127
+ end
128
+
129
+ # One claim, and the handler on what it got. Returns whether a message was handled.
130
+ def run_once
131
+ loop_once
132
+ end
133
+
134
+ # Stops after the current messages. Safe from any thread and from a signal handler.
135
+ def stop
136
+ @stopping = true
137
+ @wake.close
138
+ end
139
+
140
+ def stopping?
141
+ @stopping
142
+ end
143
+
144
+ # The host and the process, so the workers on one host are told apart.
145
+ def self.default_consumer
146
+ host = Socket.gethostname
147
+ host.nil? || host.empty? ? nil : "#{host}:#{Process.pid}"
148
+ rescue SystemCallError, SocketError
149
+ nil
150
+ end
151
+
152
+ private
153
+
154
+ def stop?
155
+ return true if @stopping
156
+ return true if @deadline && monotonic >= @deadline
157
+
158
+ @max_messages ? @counter.synchronize { @started >= @max_messages } : false
159
+ end
160
+
161
+ def loop_once
162
+ begin
163
+ lease = @client.claim(
164
+ @queue, consumer: @consumer, route: @route, wait_seconds: @wait_seconds, lease_seconds: @lease_seconds
165
+ )
166
+ rescue Error => e
167
+ @logger&.error("LessorMQ: claim failed (queue=#{@queue} error=#{e.message})")
168
+ @wake.pop(timeout: @error_pause)
169
+ return false
170
+ end
171
+ return false if lease.nil?
172
+
173
+ unless !@stopping && take
174
+ # Asked to stop while the claim waited, or the other threads reached
175
+ # max_messages: give the message back untouched.
176
+ report(lease, "release") { @client.release(lease) }
177
+ return false
178
+ end
179
+
180
+ handle(lease)
181
+ @counter.synchronize { @handled += 1 }
182
+ true
183
+ end
184
+
185
+ # Reserves one of max_messages for a claimed message.
186
+ def take
187
+ return true unless @max_messages
188
+
189
+ @counter.synchronize do
190
+ return false if @started >= @max_messages
191
+
192
+ @started += 1
193
+ end
194
+ true
195
+ end
196
+
197
+ def handle(lease)
198
+ job = Job.new(@client, lease)
199
+ keeper = @auto_extend ? keep(job) : nil
200
+ error = nil
201
+ begin
202
+ @handler.call(lease.message, job)
203
+ rescue *HANDLER_ERRORS => e
204
+ error = e
205
+ ensure
206
+ keeper&.stop
207
+ end
208
+
209
+ if job.lease_lost?
210
+ @logger&.warn("LessorMQ: lease lost while the handler ran; not reporting (message_id=#{lease.message.id})")
211
+ elsif error.nil?
212
+ report(lease, "ack") { @client.ack(lease) }
213
+ else
214
+ report(lease, "fail") do
215
+ result = @client.fail(lease, error)
216
+ @logger&.info("LessorMQ: message failed (message_id=#{lease.message.id} error=#{error.message} " \
217
+ "outcome=#{result.outcome} attempt=#{result.attempt} max_attempts=#{result.max_attempts})")
218
+ end
219
+ end
220
+ end
221
+
222
+ # Extends the lease every interval until stopped; a lost lease marks the job.
223
+ def keep(job)
224
+ Keeper.new(job, @lease_seconds, @extend_every, @logger)
225
+ end
226
+
227
+ # Ack, fail or release, keeping the worker alive whatever happens: a lost lease means
228
+ # the message is someone else's now; any other failure means the lease will expire
229
+ # and the server will make the message available again.
230
+ def report(lease, what)
231
+ yield
232
+ rescue LeaseLost
233
+ @logger&.warn("LessorMQ: lease lost before #{what}; the message is no longer ours " \
234
+ "(message_id=#{lease.message.id})")
235
+ rescue Error => e
236
+ @logger&.error("LessorMQ: #{what} failed; the lease will expire and the message come back " \
237
+ "(message_id=#{lease.message.id} error=#{e.message})")
238
+ end
239
+
240
+ def trap_signals
241
+ STOP_SIGNALS.to_h { |signal| [signal, Signal.trap(signal) { stop }] }
242
+ end
243
+
244
+ def monotonic
245
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
246
+ end
247
+
248
+ # The keepalive thread of one job.
249
+ class Keeper
250
+ def initialize(job, lease_seconds, extend_every, logger)
251
+ @job = job
252
+ @lease_seconds = lease_seconds
253
+ @extend_every = extend_every
254
+ @logger = logger
255
+ @done = Thread::Queue.new
256
+ @thread = Thread.new { run }
257
+ @thread.name = "lessormq-extend"
258
+ end
259
+
260
+ def stop
261
+ @done.close
262
+ @thread.join
263
+ end
264
+
265
+ private
266
+
267
+ def run
268
+ # pop returns nil on the timeout, and at once once the queue is closed.
269
+ until @done.pop(timeout: interval) || @done.closed?
270
+ begin
271
+ @job.extend_lease(lease_seconds: @lease_seconds)
272
+ rescue LeaseLost
273
+ return
274
+ rescue Error => e
275
+ @logger&.warn("LessorMQ: extend failed; trying again (error=#{e.message})")
276
+ end
277
+ end
278
+ end
279
+
280
+ def interval
281
+ @extend_every || [1.0, @job.lease.seconds_left / 3].max
282
+ end
283
+ end
284
+ private_constant :Keeper
285
+ end
286
+ end
data/lib/lessormq.rb ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ # LessorMQ for Ruby: the message queue over HTTP where the server decides and clients
4
+ # only claim, run, ack or fail.
5
+ #
6
+ # client = LessorMQ::Client.new("https://mq.example.com", ENV.fetch("LESSORMQ_KEY"))
7
+ # client.publish("mail", { "to" => "ada@example.com" })
8
+ # LessorMQ::Worker.new(client, "mail") { |message, _job| deliver(message.body) }.run
9
+ module LessorMQ
10
+ end
11
+
12
+ require_relative "lessormq/version"
13
+ require_relative "lessormq/errors"
14
+ require_relative "lessormq/models"
15
+ require_relative "lessormq/transport"
16
+ require_relative "lessormq/client"
17
+ require_relative "lessormq/worker"
metadata ADDED
@@ -0,0 +1,52 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lessormq
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.4.10
5
+ platform: ruby
6
+ authors:
7
+ - LessorMQ
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ executables: []
13
+ extensions: []
14
+ extra_rdoc_files: []
15
+ files:
16
+ - LICENSE
17
+ - README.md
18
+ - lib/lessormq.rb
19
+ - lib/lessormq/client.rb
20
+ - lib/lessormq/errors.rb
21
+ - lib/lessormq/models.rb
22
+ - lib/lessormq/transport.rb
23
+ - lib/lessormq/version.rb
24
+ - lib/lessormq/worker.rb
25
+ homepage: https://lessormq.dev
26
+ licenses:
27
+ - Apache-2.0
28
+ metadata:
29
+ homepage_uri: https://lessormq.dev
30
+ documentation_uri: https://lessormq.dev/docs/examples
31
+ source_code_uri: https://github.com/gsid-nl/lessormq/tree/main/clients/ruby
32
+ bug_tracker_uri: https://github.com/gsid-nl/lessormq/issues
33
+ rubygems_mfa_required: 'true'
34
+ rdoc_options: []
35
+ require_paths:
36
+ - lib
37
+ required_ruby_version: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: '3.3'
42
+ required_rubygems_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ requirements: []
48
+ rubygems_version: 3.6.9
49
+ specification_version: 4
50
+ summary: Ruby client and worker for LessorMQ, the message queue over HTTP where the
51
+ server decides and clients only claim, run, ack or fail
52
+ test_files: []