lessormq-rails 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: 3052f113b9d44332c03bb2a2b72039765179dc945ee5ba4cd930003c38f6ef1c
4
+ data.tar.gz: 7c619ea211cbdd9e080809adf8d40f90a773de99c349b36af08e8f28344f2f76
5
+ SHA512:
6
+ metadata.gz: d07857835e20011eeab00b0393952c941503fb3ec6c972d6f881861b9a084e1da389a3ce1fbd76ce20160366474819ed77a5c73f5b1904b1eb96940bdd659ae0
7
+ data.tar.gz: ab3ac8f9d1aeee259745536d0c0c300616b492be85bb4b00092025ebf4be006c6853caee69f3b70507f7a0102ee17e945ddb12252ea2470a4fb6e780bab6d105
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,190 @@
1
+ # LessorMQ for Rails
2
+
3
+ An ActiveJob queue adapter and worker for [LessorMQ](https://lessormq.dev), the message
4
+ queue over HTTP where the server decides and clients only claim, run, ack or fail. The
5
+ queue decides what happens to a failed job (another attempt, when, or the dead-letter
6
+ set); Rails only enqueues jobs and runs them.
7
+
8
+ The gem is `lessormq-rails`, for Rails 7.2, 8.0 and 8.1 on Ruby 3.3 or later. It builds on
9
+ the Ruby client, [lessormq](https://github.com/gsid-nl/lessormq/tree/main/clients/ruby), of
10
+ the same version (or a later patch).
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ bundle add lessormq-rails
16
+ ```
17
+
18
+ It brings the `lessormq` gem with it.
19
+
20
+ ## Configure
21
+
22
+ ```ruby
23
+ # config/application.rb (or config/environments/production.rb)
24
+ config.active_job.queue_adapter = :lessormq
25
+
26
+ config.lessormq.url = ENV["LESSORMQ_URL"] # the default
27
+ config.lessormq.api_key = ENV["LESSORMQ_KEY"] # the default
28
+ config.lessormq.queues = %w[mail default] # what the worker takes; ["default"] by default
29
+ ```
30
+
31
+ The key needs the `publish` scope for the app and `consume` for the worker (see
32
+ [tenants and keys](https://lessormq.dev/docs/protocol#tenants-and-keys)). Other settings
33
+ under `config.lessormq`:
34
+
35
+ | Setting | Default | |
36
+ |---|---|---|
37
+ | `threads` | 1 | jobs run at the same time, per queue |
38
+ | `wait_seconds` | 20 | how long a claim waits for a job (at most 20) |
39
+ | `lease_seconds` | the queue's | lease per claim, and per keepalive |
40
+ | `extend_every` | a third of the lease | seconds between keepalives |
41
+ | `consumer` | host:pid | shown to administrators, in the server's list of workers |
42
+ | `route` | none | the path this worker runs jobs through (VPN, proxy, account) |
43
+ | `http_retries` | 3 | retries after network errors, 5xx and 429 |
44
+ | `timeout` | 10 | seconds per request; a claim gets its wait on top |
45
+ | `client` | made from `url` and `api_key` | a `LessorMQ::Client` of your own |
46
+
47
+ There is no setting for retries, delays or dead-lettering: set those on the queue
48
+ (`PATCH /v1/queues/{queue}`, see [concepts](https://lessormq.dev/docs/concepts#queues-and-their-settings)).
49
+ Each thread needs a database connection, so keep the pool at least `threads` times the
50
+ number of queues.
51
+
52
+ ## Dispatch
53
+
54
+ Jobs are ordinary ActiveJob jobs:
55
+
56
+ ```ruby
57
+ class WelcomeMailJob < ApplicationJob
58
+ queue_as :mail
59
+
60
+ def perform(user)
61
+ UserMailer.welcome(user).deliver_now
62
+ end
63
+ end
64
+
65
+ WelcomeMailJob.perform_later(user)
66
+ WelcomeMailJob.set(wait: 10.minutes).perform_later(user)
67
+ ```
68
+
69
+ A job is published to the LessorMQ queue named by its `queue_name`, with its serialized
70
+ form as the body (readable in the queue) and its class as the `type` header.
71
+ `job.provider_job_id` is the message id. A publish the server refuses raises
72
+ `ActiveJob::EnqueueError`, so `perform_later` returns false.
73
+
74
+ Per job class, `lessormq_options` asks for fewer or more attempts than the queue's
75
+ default, and keeps at most one open message per key:
76
+
77
+ ```ruby
78
+ class InvoiceJob < ApplicationJob
79
+ lessormq_options max_attempts: 3, dedup_key: ->(job) { "invoice-#{job.arguments.first.id}" }
80
+ end
81
+ ```
82
+
83
+ ## Run workers
84
+
85
+ ```sh
86
+ bin/rails lessormq:work
87
+ bin/rails lessormq:work QUEUES=mail,default THREADS=4
88
+ ```
89
+
90
+ The task boots the app (eager loaded when `config.eager_load` is on) and runs a worker
91
+ per queue, `THREADS` jobs at a time each, until SIGTERM or SIGINT. Then every worker
92
+ stops after its current jobs. A claim that is still waiting is not cut off: it ends
93
+ within `wait_seconds`, and a job it brings is given back unrun. So give the process at
94
+ least `wait_seconds` plus your longest job to stop (in Kubernetes,
95
+ `terminationGracePeriodSeconds`), or lower `wait_seconds`.
96
+
97
+ Without the task (another process manager, a test), in the booted app:
98
+
99
+ ```ruby
100
+ LessorMQ::Rails::Runner.new(queues: %w[mail], threads: 2).run
101
+ ```
102
+
103
+ ## How it behaves
104
+
105
+ - **A job that returns**: the message is acked.
106
+ - **A job that raises**: the message is failed with the exception's class and message.
107
+ The queue decides whether and when it comes back (its `max_attempts` and `backoff`),
108
+ and whether it goes to the dead-letter set after the last attempt.
109
+ - **`retry_on`**: a matching exception fails the message like any other. ActiveJob would
110
+ enqueue a copy instead, which would reset the server's attempt count; under the worker,
111
+ `retry_job` raises the error instead. Its `attempts`, `wait`, `jitter`, `queue` and
112
+ `priority` do not apply: the queue's settings do. (Its counter only sees the current
113
+ delivery, so only `attempts: 1` makes it give up: then its block runs and the message
114
+ fails as permanent.) A `retry_job` of your own (from a `rescue_from`) fails the message
115
+ the same way.
116
+ - **`discard_on`**: the job gives up, so the message is failed as permanent with the
117
+ original error. The queue's `on_permanent` decides: the dead-letter set at once by
118
+ default, or another attempt with `retry`. Its block runs as usual.
119
+ - **Permanent failures**: an error that includes `LessorMQ::Permanent` (or raise
120
+ `LessorMQ::PermanentFailure`), and `ActiveJob::DeserializationError` (a record that is
121
+ gone, an argument that cannot be read), are reported as permanent. A `retry_on
122
+ ActiveJob::DeserializationError` makes the latter an ordinary failure again. A message
123
+ that is not an ActiveJob job is permanent too; a job class this worker does not know
124
+ is not (during a deploy, the next attempt may reach a worker that has it).
125
+ - **`executions`** is the server's attempt number. It is for logging; nothing in this
126
+ gem decides on it.
127
+ - **`after_discard`** runs when the job gives up (`discard_on`). Not after an exception
128
+ that nothing handled: the queue may try that message again. A message the server gives
129
+ up on is in the dead-letter set.
130
+ - **Failed jobs**: there is no failed-jobs table. Messages that ran out of attempts, or
131
+ failed permanently, stay in the queue's dead-letter set for its retention, where an
132
+ administrator can inspect, replay or delete them.
133
+ - **Release**: a worker that is stopped while a claim waits gives the job back with a
134
+ release: the attempt does not count.
135
+ - **Timeouts**: ActiveJob has none, and neither does the worker. While `perform` runs,
136
+ a thread extends the lease every third of it. If the lease is lost anyway, the outcome
137
+ is not reported (the message is someone else's by then); a long job can check
138
+ `lessormq_job&.lease_lost?` and stop. A worker that dies mid-job leaves the lease to
139
+ expire, which counts as a failed attempt, so a job that crashes its worker still runs
140
+ out of attempts.
141
+ - **Scheduling**: `wait` and `wait_until` become the message's delay, in whole seconds
142
+ from the server's clock, rounded up.
143
+ - **Priority** does not exist in LessorMQ and is not sent; use separate queues.
144
+ - **Errors** reach Rails' error reporter (and so Sentry, Honeybadger, ...) as in any
145
+ ActiveJob backend: every failed attempt; a discarded job only with `report: true`
146
+ (Rails 8.1).
147
+ - **Job continuations** (Rails 8.1) run their steps, but the progress is not kept between
148
+ attempts: LessorMQ redelivers the message as it was published, so a failed attempt
149
+ starts again from the first step. The worker does not interrupt jobs when it stops;
150
+ it waits for them.
151
+ - **Enqueue after commit**: a job enqueued inside a database transaction is published
152
+ after the commit when `enqueue_after_transaction_commit` is on: by default on Rails
153
+ 7.2, with `config.active_job.enqueue_after_transaction_commit = true` on 8.x.
154
+
155
+ ## Moving from another queue
156
+
157
+ - Let the queue decide about retries: set the queue's `max_attempts` and `backoff` to what
158
+ your `retry_on` (or Sidekiq's `retry`) did. `retry_on` can stay, it is harmless, but it
159
+ no longer chooses the wait or the number of attempts.
160
+ - A failed-jobs UI is not needed: messages that ran out of attempts stay in the queue's
161
+ dead-letter set, where an administrator can look at and replay them.
162
+ - Uniqueness is `lessormq_options dedup_key:`: at most one open message per key.
163
+ - Workers on different network paths (VPN exits, proxies) set `config.lessormq.route`;
164
+ see [routes](https://lessormq.dev/docs/concepts#routes).
165
+ - Move one queue at a time: give the job classes of that queue
166
+ `self.queue_adapter = :lessormq`, run `bin/rails lessormq:work QUEUES=that-queue` beside
167
+ your old workers, and switch `config.active_job.queue_adapter` when the last one has
168
+ moved.
169
+
170
+ ## Development
171
+
172
+ ```sh
173
+ cd clients/rails
174
+ bundle install
175
+ bundle exec rake test
176
+ ```
177
+
178
+ The unit tests use ActiveJob's test helpers and a scripted LessorMQ server, no server
179
+ needed. `RAILS_VERSION=7.2` (or `8.0`, `8.1`, the default) picks the Rails to test
180
+ against. The end-to-end tests boot a small Rails app (`test/dummy`), dispatch jobs
181
+ through ActiveJob and run them with the worker and with `rake lessormq:work`, against a
182
+ running server (with `LEASE_SWEEP_SECONDS=1`) and its operator key:
183
+
184
+ ```sh
185
+ LESSORMQ_URL=http://127.0.0.1:8080 LESSORMQ_OPERATOR_KEY=lmq_... bundle exec rake e2e
186
+ ```
187
+
188
+ They create a tenant of their own and delete it afterwards. The Ruby client's own tests
189
+ and conformance adapter are in
190
+ [clients/ruby](https://github.com/gsid-nl/lessormq/tree/main/clients/ruby).
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loaded by lessormq/rails, which brings the client and the configuration.
4
+
5
+ module ActiveJob
6
+ module QueueAdapters
7
+ # The LessorMQ queue adapter:
8
+ #
9
+ # config.active_job.queue_adapter = :lessormq
10
+ #
11
+ # A job is published to the LessorMQ queue of its queue_name, its serialized form as
12
+ # the body and its class as the +type+ header. A scheduled job gets a delay; the
13
+ # server makes it available then. Priorities do not exist in LessorMQ and are not sent.
14
+ #
15
+ # The jobs are run by the worker: bin/rails lessormq:work.
16
+ class LessormqAdapter < AbstractAdapter
17
+ # +client+: a LessorMQ::Client; by default the one of config.lessormq.
18
+ def initialize(client = nil)
19
+ super()
20
+ @client = client
21
+ end
22
+
23
+ def enqueue(job)
24
+ publish(job, nil)
25
+ end
26
+
27
+ def enqueue_at(job, timestamp)
28
+ publish(job, timestamp)
29
+ end
30
+
31
+ private
32
+
33
+ def publish(job, timestamp)
34
+ options = job.class.respond_to?(:lessormq_publish_options) ? job.class.lessormq_publish_options : {}
35
+ dedup_key = options[:dedup_key]
36
+ dedup_key = dedup_key.call(job) if dedup_key.respond_to?(:call)
37
+ # Whole seconds from the server's clock, rounded up so a job never runs early.
38
+ delay = timestamp ? (timestamp.to_f - Time.now.to_f).ceil : 0
39
+ published = client.publish(
40
+ job.queue_name, job.serialize,
41
+ headers: { "type" => job.class.name.to_s },
42
+ dedup_key: dedup_key&.to_s,
43
+ delay_seconds: delay.positive? ? delay : nil,
44
+ max_attempts: options[:max_attempts]
45
+ )
46
+ job.provider_job_id = published.id
47
+ published
48
+ rescue LessorMQ::Error => e
49
+ raise ActiveJob::EnqueueError, "LessorMQ: #{e.message}"
50
+ end
51
+
52
+ def client
53
+ @client || LessorMQ::Rails.config.client
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ module Rails
5
+ # Runs the ActiveJob job in a message: the handler of the worker's LessorMQ::Worker.
6
+ #
7
+ # It returns: the message is acked. It raises: the message is failed with the job's
8
+ # error, and the queue decides what follows. The error is marked permanent when the
9
+ # job gave up on it (discard_on, or a retry_on whose block ran), when the job's
10
+ # arguments cannot be deserialized, or when it is a LessorMQ::Permanent error.
11
+ class Executor
12
+ GIVE_UP_EVENTS = /\A(discard|retry_stopped)\.active_job\z/
13
+
14
+ # The error itself, marked permanent, so the server gets its own class and message.
15
+ def self.permanent(error)
16
+ error.extend(LessorMQ::Permanent) unless error.frozen? || LessorMQ.permanent?(error)
17
+ error
18
+ end
19
+
20
+ def initialize
21
+ # ActiveJob::Base brings ActiveJob::Callbacks, and runs the app's on_load hooks.
22
+ # Not before: an executor is made when the worker starts, after the app has booted.
23
+ require "active_job/base"
24
+ end
25
+
26
+ def call(message, lease_job)
27
+ data = message.body
28
+ unless data.is_a?(Hash) && data["job_class"].is_a?(String)
29
+ raise InvalidJob, "message #{message.id} is not an ActiveJob job (no job_class)"
30
+ end
31
+
32
+ given_up = nil
33
+ ActiveJob::Callbacks.run_callbacks(:execute) { given_up = perform(data, message, lease_job) }
34
+ # Raised outside the app's executor: a job that gave up is not an unhandled error
35
+ # for Rails' error reporter, as in ActiveJob (discard_on report: true, Rails 8.1,
36
+ # reports it itself).
37
+ raise Executor.permanent(given_up) if given_up
38
+ end
39
+
40
+ private
41
+
42
+ # Returns the error the job gave up on, if it did.
43
+ def perform(data, message, lease_job)
44
+ # An unknown class is a NameError, not permanent: during a rolling deploy the
45
+ # next attempt may well reach a worker that has it.
46
+ job = ActiveJob::Base.deserialize(data)
47
+ # The server counts the attempts: perform_now adds this one.
48
+ job.executions = message.attempt - 1
49
+ job.provider_job_id = message.id
50
+ job.lessormq_job = lease_job
51
+
52
+ given_up = nil
53
+ watch = lambda do |_name, _started, _finished, _id, payload|
54
+ given_up ||= payload[:error] if payload[:job].equal?(job)
55
+ end
56
+ begin
57
+ ActiveSupport::Notifications.subscribed(watch, GIVE_UP_EVENTS) { job.perform_now }
58
+ rescue ActiveJob::DeserializationError => e
59
+ # A record that no longer exists, an argument that cannot be read: another
60
+ # attempt would fail the same way, unless the job asked for one (retry_on).
61
+ raise if job.lessormq_retry_requested?
62
+
63
+ raise Executor.permanent(e)
64
+ end
65
+ given_up
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ module Rails
5
+ # Included in ActiveJob::Base. A job that the LessorMQ worker runs leaves retries to
6
+ # the queue: retry_job (and so retry_on) fails the message instead of enqueueing a
7
+ # copy, which would reset the server's attempt count and backoff.
8
+ module JobExtension
9
+ def self.included(base)
10
+ base.class_attribute :lessormq_publish_options, instance_accessor: false, default: {}.freeze
11
+ base.extend ClassMethods
12
+ end
13
+
14
+ module ClassMethods
15
+ # Options for every publish of this job class:
16
+ #
17
+ # max_attempts:: attempts for its messages, within the queue's max_attempts_limit
18
+ # dedup_key:: a String, or a callable that gets the job, for at most one open
19
+ # message per key
20
+ #
21
+ # class InvoiceJob < ApplicationJob
22
+ # lessormq_options max_attempts: 3, dedup_key: ->(job) { "invoice-#{job.arguments.first}" }
23
+ # end
24
+ def lessormq_options(max_attempts: nil, dedup_key: nil)
25
+ self.lessormq_publish_options = { max_attempts: max_attempts, dedup_key: dedup_key }.compact.freeze
26
+ end
27
+ end
28
+
29
+ # The LessorMQ::Job (lease, message, extend_lease, lease_lost?) while the LessorMQ
30
+ # worker runs this job; nil otherwise.
31
+ attr_accessor :lessormq_job
32
+
33
+ # In the worker: the error that made the job ask for a retry is raised, so the
34
+ # message is failed and the queue decides about the next attempt. Elsewhere (a job
35
+ # performed inline) ActiveJob enqueues a copy, as always.
36
+ def retry_job(options = {})
37
+ return super if lessormq_job.nil?
38
+
39
+ @lessormq_retry_requested = true
40
+ # retry_on passes the error; a job continuation (Rails 8.1) retries from its rescue.
41
+ error = options[:error] || $!
42
+ raise error if error
43
+
44
+ raise RetryRequested, "#{self.class.name} asked to be retried"
45
+ end
46
+
47
+ # Whether the job asked to be retried while the worker ran it.
48
+ def lessormq_retry_requested?
49
+ @lessormq_retry_requested == true
50
+ end
51
+
52
+ def rescue_with_handler(...)
53
+ handled = super
54
+ @lessormq_unhandled = !handled if lessormq_job
55
+ handled
56
+ end
57
+
58
+ private
59
+
60
+ # ActiveJob runs after_discard for an error that no handler took, since its adapters
61
+ # then drop the job or retry it on their own. Here the queue may try the message
62
+ # again, so after_discard only runs when the job itself gives up: discard_on, or a
63
+ # retry_on whose block ran.
64
+ def run_after_discard_procs(exception)
65
+ return if lessormq_job && @lessormq_unhandled
66
+
67
+ super
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ module Rails
5
+ # config.lessormq in the app, the Rails logger, and the lessormq:work task.
6
+ class Railtie < ::Rails::Railtie
7
+ config.lessormq = LessorMQ::Rails.config
8
+
9
+ initializer "lessormq.logger" do
10
+ LessorMQ::Rails.config.logger ||= ::Rails.logger
11
+ end
12
+
13
+ rake_tasks do
14
+ load File.expand_path("tasks/lessormq.rake", __dir__)
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ module Rails
5
+ # The worker command: a LessorMQ::Worker per queue, each with +threads+ jobs at a
6
+ # time, until SIGTERM or SIGINT. Then every worker stops after its current jobs; a
7
+ # claim that is still waiting ends within wait_seconds, and a job it brings is given
8
+ # back unrun.
9
+ #
10
+ # bin/rails lessormq:work QUEUES=mail,default THREADS=4
11
+ class Runner
12
+ STOP_SIGNALS = %w[TERM INT].freeze
13
+
14
+ attr_reader :workers
15
+
16
+ # queues:: the queues to take jobs from
17
+ # threads:: jobs run at the same time, per queue
18
+ # max_messages:: stop each queue's worker after this many jobs (for tests)
19
+ # The rest are LessorMQ::Worker's options; the configuration fills in what is not given.
20
+ def initialize(queues: nil, threads: nil, client: nil, config: LessorMQ::Rails.config, max_messages: nil,
21
+ **worker_options)
22
+ @config = config
23
+ @queues = Array(queues || config.queues).map(&:to_s).reject(&:empty?)
24
+ raise ArgumentError, "LessorMQ: no queues to work" if @queues.empty?
25
+
26
+ @threads = Integer(threads || config.threads)
27
+ @client = client || config.client
28
+ @logger = worker_options[:logger] || config.logger
29
+ options = {
30
+ consumer: config.consumer, route: config.route, wait_seconds: config.wait_seconds,
31
+ lease_seconds: config.lease_seconds, extend_every: config.extend_every, logger: @logger
32
+ }.compact.merge(worker_options.compact)
33
+ executor = Executor.new
34
+ @workers = @queues.map do |queue|
35
+ LessorMQ::Worker.new(@client, queue, executor, concurrency: @threads, handle_signals: false,
36
+ max_messages: max_messages, **options)
37
+ end
38
+ end
39
+
40
+ # The runner as the rake task starts it: QUEUES (comma-separated) and THREADS from
41
+ # the environment, over the configuration.
42
+ def self.from_env(env = ENV, config: LessorMQ::Rails.config)
43
+ queues = env["QUEUES"]&.split(",")&.map(&:strip)
44
+ new(queues: queues, threads: env["THREADS"], config: config)
45
+ end
46
+
47
+ # Runs until stopped, and returns the number of jobs handled.
48
+ def run(handle_signals: true)
49
+ previous = handle_signals ? STOP_SIGNALS.to_h { |signal| [signal, Signal.trap(signal) { stop }] } : nil
50
+ @logger&.info("LessorMQ: working queues #{@queues.join(', ')} with #{@threads} thread(s) each")
51
+ threads = @workers.map { |worker| Thread.new { worker.run }.tap { |t| t.name = "lessormq-#{worker.queue}" } }
52
+ handled = threads.sum(&:value)
53
+ @logger&.info("LessorMQ: stopped after #{handled} job(s)")
54
+ handled
55
+ ensure
56
+ previous&.each { |signal, handler| Signal.trap(signal, handler) }
57
+ end
58
+
59
+ # Stops after the current jobs. Safe from any thread and from a signal handler.
60
+ def stop
61
+ @workers.each(&:stop)
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ namespace :lessormq do
4
+ desc "Run ActiveJob jobs from LessorMQ until SIGTERM or SIGINT (QUEUES=mail,default THREADS=1)"
5
+ task work: :environment do
6
+ # Rake does not eager load; a worker should, as the app server does.
7
+ Rails.application.eager_load! if Rails.application.config.eager_load
8
+ LessorMQ::Rails::Runner.from_env.run
9
+ end
10
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LessorMQ
4
+ module Rails
5
+ # Written from the git tag when the gem is released, as the lessormq gem's; this gem
6
+ # requires lessormq of the same version or a later patch.
7
+ VERSION = "0.4.10"
8
+ end
9
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "lessormq"
4
+ require "active_job"
5
+ require_relative "rails/version"
6
+
7
+ module LessorMQ
8
+ # ActiveJob on LessorMQ. The queue decides what happens to a failed job (another
9
+ # attempt, when, or the dead-letter set); Rails only enqueues and runs jobs.
10
+ #
11
+ # Inside this module +Rails+ is LessorMQ::Rails: the framework is always ::Rails.
12
+ module Rails
13
+ # How to reach the server and how the worker claims. There is nothing about retries:
14
+ # those are the queue's settings.
15
+ class Configuration
16
+ # The server, and a key with the publish and/or consume scope.
17
+ attr_accessor :url, :api_key
18
+ # Queues the worker takes jobs from, and the jobs it runs at the same time per queue.
19
+ attr_accessor :queues, :threads
20
+ # How the worker claims; see LessorMQ::Worker.
21
+ attr_accessor :wait_seconds, :lease_seconds, :extend_every, :consumer, :route
22
+ # The client's HTTP retries and timeout per request.
23
+ attr_accessor :http_retries, :timeout
24
+ # A Logger; Rails.logger once the app is booted.
25
+ attr_accessor :logger
26
+ # A LessorMQ::Client of your own, instead of one made from url and api_key.
27
+ attr_writer :client
28
+
29
+ def initialize
30
+ @url = ENV.fetch("LESSORMQ_URL", nil)
31
+ @api_key = ENV.fetch("LESSORMQ_KEY", nil)
32
+ @queues = ["default"]
33
+ @threads = 1
34
+ @wait_seconds = 20
35
+ @http_retries = 3
36
+ @timeout = 10
37
+ @lock = Mutex.new
38
+ end
39
+
40
+ # The client every enqueue and the worker use, made on first use.
41
+ def client
42
+ @lock.synchronize do
43
+ @client ||= begin
44
+ raise ArgumentError, "LessorMQ: set config.lessormq.url and api_key (or LESSORMQ_URL and LESSORMQ_KEY)" \
45
+ if url.to_s.empty? || api_key.to_s.empty?
46
+
47
+ LessorMQ::Client.new(url, api_key, http_retries: http_retries, timeout: timeout, logger: logger)
48
+ end
49
+ end
50
+ end
51
+
52
+ # Never the key.
53
+ def inspect
54
+ "#<LessorMQ::Rails::Configuration url=#{url.inspect} queues=#{queues.inspect}>"
55
+ end
56
+ end
57
+
58
+ # The message is not an ActiveJob job: another attempt would not change that.
59
+ class InvalidJob < StandardError
60
+ include LessorMQ::Permanent
61
+ end
62
+
63
+ # A job called retry_job without an error of its own.
64
+ class RetryRequested < StandardError; end
65
+
66
+ def self.config
67
+ @config ||= Configuration.new
68
+ end
69
+
70
+ def self.configure
71
+ yield config
72
+ end
73
+ end
74
+ end
75
+
76
+ require_relative "rails/job_extension"
77
+ ActiveSupport.on_load(:active_job) { include LessorMQ::Rails::JobExtension }
78
+ require_relative "rails/executor"
79
+ require_relative "rails/runner"
80
+ require_relative "../active_job/queue_adapters/lessormq_adapter"
81
+ require_relative "rails/railtie" if defined?(::Rails::Railtie)
metadata ADDED
@@ -0,0 +1,107 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lessormq-rails
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
+ - !ruby/object:Gem::Dependency
13
+ name: activejob
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.2'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '7.2'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9'
32
+ - !ruby/object:Gem::Dependency
33
+ name: lessormq
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - "~>"
37
+ - !ruby/object:Gem::Version
38
+ version: 0.4.10
39
+ type: :runtime
40
+ prerelease: false
41
+ version_requirements: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - "~>"
44
+ - !ruby/object:Gem::Version
45
+ version: 0.4.10
46
+ - !ruby/object:Gem::Dependency
47
+ name: railties
48
+ requirement: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '7.2'
53
+ - - "<"
54
+ - !ruby/object:Gem::Version
55
+ version: '9'
56
+ type: :runtime
57
+ prerelease: false
58
+ version_requirements: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '7.2'
63
+ - - "<"
64
+ - !ruby/object:Gem::Version
65
+ version: '9'
66
+ executables: []
67
+ extensions: []
68
+ extra_rdoc_files: []
69
+ files:
70
+ - LICENSE
71
+ - README.md
72
+ - lib/active_job/queue_adapters/lessormq_adapter.rb
73
+ - lib/lessormq/rails.rb
74
+ - lib/lessormq/rails/executor.rb
75
+ - lib/lessormq/rails/job_extension.rb
76
+ - lib/lessormq/rails/railtie.rb
77
+ - lib/lessormq/rails/runner.rb
78
+ - lib/lessormq/rails/tasks/lessormq.rake
79
+ - lib/lessormq/rails/version.rb
80
+ homepage: https://lessormq.dev
81
+ licenses:
82
+ - Apache-2.0
83
+ metadata:
84
+ homepage_uri: https://lessormq.dev
85
+ documentation_uri: https://lessormq.dev/docs/examples
86
+ source_code_uri: https://github.com/gsid-nl/lessormq/tree/main/clients/rails
87
+ bug_tracker_uri: https://github.com/gsid-nl/lessormq/issues
88
+ rubygems_mfa_required: 'true'
89
+ rdoc_options: []
90
+ require_paths:
91
+ - lib
92
+ required_ruby_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '3.3'
97
+ required_rubygems_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ requirements: []
103
+ rubygems_version: 3.6.9
104
+ specification_version: 4
105
+ summary: 'ActiveJob adapter and worker for LessorMQ: the queue decides retries, delays
106
+ and dead-lettering; Rails only enqueues and runs jobs'
107
+ test_files: []