coil 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fe5c3a1be19ae3a27b0c9e9b9fb135d0331491b565b3bcb75bac84c34ba78094
4
+ data.tar.gz: e91931bcc919e0fac9c0970266450d648d3064dd72b43d54bc2ef9dfc28c9cf8
5
+ SHA512:
6
+ metadata.gz: e03f621569bb0316057e10e3de93cfcab2e8729d4182c5922a41a8f212e595747c41d4d353f478a1cec718bf6754fe64d05cce4675ff39a5c21551a3c54555c0
7
+ data.tar.gz: 78f428ad483173301a0394c07f7dd3c84eec353a5f8941cb3a0a9821716b48a8f42b726c4dd4efaf742de276915c68da03ab78ba87227b098734af0c822c2ba5
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,279 @@
1
+ # Coil [![concourse.odeko.com](https://concourse.odeko.com/api/v1/teams/main/pipelines/coil-main/jobs/test/badge)](https://concourse.odeko.com/teams/main/pipelines/coil-main)
2
+
3
+ <img src="./solenoid.svg" width="35%">
4
+
5
+ Transactional inbox/outbox message queuing.
6
+
7
+ This Rails engine can be mounted in any PostgreSQL-backed Rails app.
8
+
9
+ # Motivation
10
+ The motivating use-case involves event-streaming with Kafka.
11
+
12
+ Kafka guarantees that messages on the same topic and partition will be read
13
+ in the same order as written, but we need to ensure we're writing them in the
14
+ correct order, regardless of any concurrent processes we may be running.
15
+
16
+ Similarly, once we've read a message from the stream, we'd like to hand off the
17
+ message processing to an asynchronous job while ensuring we process messages of
18
+ a given type and key in the same order as read.
19
+
20
+ ## Implementation
21
+ The [inbox/outbox](https://en.wikipedia.org/wiki/Inbox_and_outbox_pattern) pattern
22
+ (see also [article](https://microservices.io/patterns/data/transactional-outbox.html))
23
+ ensures message delivery.
24
+
25
+ Message ordering is preserved using
26
+ [advisory locks](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS)
27
+ as a synchronization mechanism.
28
+
29
+ ## Installation
30
+ Add to the application's Gemfile:
31
+
32
+ ```ruby
33
+ gem "coil", source: "https://gem.odeko.com/"
34
+ gem "schema_version_cache", source: "https://gem.odeko.com/"
35
+ ```
36
+
37
+ Install engine and migrations:
38
+ ```console
39
+ $ bundle
40
+ $ bundle exec rails coil:install:migrations
41
+ $ bundle exec rails db:migrate
42
+ ```
43
+
44
+ Register periodic jobs:
45
+ ```ruby
46
+ # config/initializers/sidekiq.rb
47
+ Sidekiq.configure_server do |config|
48
+ # ...
49
+ config.periodic do |mgr|
50
+ mgr.register("*/10 * * * *", "Coil::Inbox::MessagesPeriodicJob")
51
+ mgr.register("5-59/10 * * * *", "Coil::Outbox::MessagesPeriodicJob")
52
+ end
53
+ end
54
+ ```
55
+
56
+ Filter retryable errors out of airbrake:
57
+ ```ruby
58
+ # config/initializers/airbrake.rb
59
+ Airbrake.add_filter do |notice|
60
+ exception = notice.stash[:exception]
61
+ notice.ignore! if exception.is_a?(Coil::TransactionalMessagesJob::RetryableError)
62
+ end
63
+ ```
64
+
65
+ Set up schema version cache as described
66
+ [here](https://github.com/OdekoTeam/schema_version_cache?tab=readme-ov-file#usage)
67
+
68
+ ## Usage: inbox
69
+
70
+ Define a message type and corresponding job:
71
+ ```ruby
72
+ # app/models/inbox/foo_message.rb
73
+ class Inbox::FooMessage < Coil::Inbox::Message
74
+ def job_class
75
+ Inbox::FooMessagesJob
76
+ end
77
+ end
78
+ ```
79
+ ```ruby
80
+ # app/jobs/inbox/foo_messages_job.rb
81
+ class Inbox::FooMessagesJob < Coil::TransactionalMessagesJob
82
+ private
83
+
84
+ # Put message processing logic in this method.
85
+ def process(message)
86
+ # For example...
87
+ uuid = message.key
88
+ val = message.value.deep_symbolize_keys
89
+ Foo.do_stuff(uuid:, potato: val[:potato])
90
+ end
91
+
92
+ def message_class
93
+ Inbox::FooMessage
94
+ end
95
+ end
96
+ ```
97
+ (The test-suite contains a working example with type-annotations:
98
+ [message](./spec/dummy/app/models/dummy/inbox/foo_message.rb),
99
+ [job](./spec/dummy/app/jobs/dummy/inbox/foo_messages_job.rb))
100
+
101
+ (For advanced use-cases, you can also define an `around_process` job method.
102
+ [See example](./spec/dummy/app/jobs/dummy/inbox/who_messages_job.rb))
103
+
104
+ Receive messages from Kafka:
105
+ ```ruby
106
+ # app/consumers/my_consumer.rb
107
+ class MyConsumer < Racecar::Consumer
108
+ FOO = "com.example.service.foo".freeze
109
+ subscribes_to FOO
110
+
111
+ def process(message)
112
+ key = AvroMessaging.decode(message.key)
113
+ decoded = AvroMessaging.decode_message(message.value)
114
+ value = decoded.message.deep_symbolize_keys
115
+ schema_id = decoded.schema_id
116
+
117
+ case message.topic
118
+ when FOO
119
+ Receivers::FooReceiver.receive(key:, value:, schema_id:)
120
+ end
121
+ end
122
+ end
123
+ ```
124
+ ```ruby
125
+ # app/lib/receivers/foo_receiver.rb
126
+ module Receivers::FooReceiver
127
+ VALUE_SCHEMA_SUBJECT = "com.example.service.Foo_value"
128
+
129
+ def self.receive(key:, value:, schema_id:)
130
+ schema_version = AvroVersionCache.get_version_number(
131
+ subject: VALUE_SCHEMA_SUBJECT,
132
+ schema_id:
133
+ )
134
+ Inbox::FooMessage.create!(
135
+ key:,
136
+ value:,
137
+ metadata: {
138
+ value_schema_subject: VALUE_SCHEMA_SUBJECT,
139
+ value_schema_version: schema_version,
140
+ value_schema_id: schema_id
141
+ }
142
+ )
143
+ end
144
+ end
145
+ ```
146
+
147
+ ## Usage: outbox
148
+
149
+ Define a message type and corresponding job:
150
+ ```ruby
151
+ # app/models/outbox/bar_message.rb
152
+ class Outbox::BarMessage < Coil::Outbox::Message
153
+ VALUE_SCHEMA_SUBJECT = "com.example.Bar_value"
154
+
155
+ def job_class
156
+ Outbox::BarMessagesJob
157
+ end
158
+ end
159
+ ```
160
+ ```ruby
161
+ # app/jobs/outbox/bar_messages_job.rb
162
+ class Outbox::BarMessagesJob < Coil::TransactionalMessagesJob
163
+ private
164
+
165
+ # Attach schema metadata to message
166
+ def pre_process(message)
167
+ value_schema_subject = Outbox::BarMessage::VALUE_SCHEMA_SUBJECT
168
+ value_schema_id = AvroVersionCache.get_current_id(subject: value_schema_subject)
169
+ value_schema_version = AvroVersionCache.get_version_number(
170
+ subject: value_schema_subject,
171
+ schema_id: value_schema_id
172
+ )
173
+ metadata = {
174
+ value_schema_subject:,
175
+ value_schema_id:,
176
+ value_schema_version:
177
+ }.merge(message.metadata)
178
+
179
+ message.update!(metadata:)
180
+ end
181
+
182
+ # Write message to Kafka
183
+ def process(message)
184
+ BarEvent.new(message).produce_async
185
+ end
186
+
187
+ def message_class
188
+ Outbox::BarMessage
189
+ end
190
+ end
191
+ ```
192
+ (The test-suite contains a working example with type-annotations:
193
+ [message](./spec/dummy/app/models/dummy/outbox/bar_message.rb),
194
+ [job](./spec/dummy/app/jobs/dummy/outbox/bar_messages_job.rb))
195
+
196
+ Write to the outbox:
197
+ ```ruby
198
+ bar = Bar.first
199
+ turnips = bar.count_turnips
200
+ Outbox::BarMessage.create!(key: bar.uuid, value: {turnips:})
201
+ ```
202
+
203
+ ## Usage: queue locking
204
+ The inbox and outbox operations described above automatically preserve message
205
+ ordering by sequentializing the creation and processing of messages with a given
206
+ type and key.
207
+
208
+ You can access these synchronization mechanisms directly if necessary:
209
+ ```ruby
210
+ # If we want to treat turnip-harvesting and message creation as one operation
211
+ # and ensure that concurrent attempts to run that operation on the same Bar will
212
+ # be run sequentially:
213
+ Outbox::BarMessage.locking_persistence_queue(keys: [bar.uuid]) do
214
+ bar.harvest_turnips
215
+ bar.replant
216
+ turnips = bar.count_turnips
217
+ Outbox::BarMessage.create!(key: bar.uuid, value: {turnips:})
218
+ end
219
+
220
+ # More generally, we can run an action while holding advisory locks on a list of
221
+ # keys in some arbitrary keyspace:
222
+ queue_type = "FOOD_PREP"
223
+ message_type = "SOUP"
224
+ ingredients = ["lentils", "tomato"]
225
+ Coil::QueueLocking.locking(queue_type:, message_type:, message_keys: ingredients) do
226
+ Chef.make_soup(ingredients)
227
+ end
228
+
229
+ # The `locking` call above will wait until it's able to obtain the requested
230
+ # lock. If we'd rather abort the operation than wait for the lock:
231
+ Coil::QueueLocking.locking(queue_type:, message_type:, message_keys: ingredients, wait: false) do
232
+ Chef.make_soup(ingredients)
233
+ rescue Coil::QueueLocking::LockWaitTimeout
234
+ puts("Looks like someone else is already on it")
235
+ end
236
+ ```
237
+
238
+ ## Development
239
+
240
+ Install development dependencies:
241
+ ```console
242
+ $ bundle
243
+ ```
244
+
245
+ Install pre-commit hook:
246
+ ```console
247
+ $ bin/install-pre-commit
248
+ ```
249
+
250
+ Setup database:
251
+ ```console
252
+ $ bin/rails db:setup
253
+ $ bin/rails db:migrate
254
+ ```
255
+
256
+ Run test-suite:
257
+ ```console
258
+ $ bin/ci-test
259
+ ```
260
+
261
+ Run linter:
262
+ ```console
263
+ $ bin/lint
264
+ ```
265
+
266
+ Regenerate type info for DSLs (e.g. after adding a db migration):
267
+ ```console
268
+ $ bin/tapioca dsl --app-root=spec/dummy
269
+ ```
270
+
271
+ Regenerate type info for gems (e.g. after adding a gem):
272
+ ```console
273
+ $ bin/tapioca gem
274
+ ```
275
+
276
+ Coil's type annotations are declared in `rbi/coil.rbi` to facilitate typechecking
277
+ by Rails apps that use this engine along with Sorbet. Keeping these annotations
278
+ in a separate file avoids foisting a Sorbet runtime dependency on any app that
279
+ uses our engine.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "bundler/setup"
2
+
3
+ APP_RAKEFILE = File.expand_path("spec/dummy/Rakefile", __dir__)
4
+ load "rails/tasks/engine.rake"
5
+
6
+ load "rails/tasks/statistics.rake"
7
+
8
+ require "bundler/gem_tasks"
@@ -0,0 +1,7 @@
1
+ # typed: strict
2
+
3
+ module Coil
4
+ class ApplicationJob
5
+ include Sidekiq::Worker
6
+ end
7
+ end
@@ -0,0 +1,16 @@
1
+ # typed: strict
2
+
3
+ # This periodic job acts as a fallback mechanism, polling for inbox messages
4
+ # that were not enqueued and processed automatically upon create, e.g. due to a
5
+ # failure to push a job onto the Redis queue.
6
+ module Coil
7
+ module Inbox
8
+ class MessagesPeriodicJob < TransactionalMessagesPeriodicJob
9
+ private
10
+
11
+ def message_parent_class
12
+ ::Coil::Inbox::Message
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,16 @@
1
+ # typed: strict
2
+
3
+ # This periodic job acts as a fallback mechanism, polling for outbox messages
4
+ # that were not enqueued and processed automatically upon create, e.g. due to a
5
+ # failure to push a job onto the Redis queue.
6
+ module Coil
7
+ module Outbox
8
+ class MessagesPeriodicJob < TransactionalMessagesPeriodicJob
9
+ private
10
+
11
+ def message_parent_class
12
+ ::Coil::Outbox::Message
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,80 @@
1
+ # typed: true
2
+
3
+ module Coil
4
+ class TransactionalMessagesJob < ApplicationJob
5
+ RetryableError = Class.new(StandardError)
6
+ DuplicateJobError = Class.new(StandardError)
7
+
8
+ # Sidekiq is not designed for long-running jobs, so we place an upper bound
9
+ # on job duration. When a job exceeds this bound, we'll enqueue a subsequent
10
+ # job to pick up where we left off.
11
+ MAX_DURATION = 5.minutes
12
+
13
+ sidekiq_options retry: 4, dead: false
14
+
15
+ def perform(key, processor_name = self.class.to_s)
16
+ deadline = Time.current + MAX_DURATION
17
+ next_in_line = process_messages(key:, processor_name:, deadline:)
18
+ return if next_in_line.nil?
19
+
20
+ # If we reach this point, it means we exceeded the deadline and there
21
+ # are messages we still haven't processed.
22
+ Rails.logger.info(<<~INFO.squish)
23
+ #{self.class} exceeded deadline.
24
+ Enqueuing subsequent job with key=#{key} processor_name=#{processor_name}
25
+ INFO
26
+ next_in_line.enqueue_job(processor_name)
27
+ rescue DuplicateJobError
28
+ # A duplicate job is in the midst of its message-processing loop. We'll
29
+ # call this job done and allow the other one to continue.
30
+ end
31
+
32
+ private
33
+
34
+ # Process unprocessed messages until none remain or deadline is exceeded,
35
+ # then return the next unprocessed message, if any remain.
36
+ def process_messages(key:, processor_name:, deadline:)
37
+ loop do
38
+ next_in_line = next_message(key:, processor_name:)
39
+ return next_in_line if next_in_line.nil? || Time.current > deadline
40
+
41
+ locking(key) do
42
+ message = next_message(key:, processor_name:)
43
+
44
+ if message.present?
45
+ around_process(message, processor_name:) do
46
+ pre_process(message)
47
+ message.processed(processor_name:)
48
+ process(message)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+
55
+ def around_process(message, processor_name:, &blk)
56
+ blk.call
57
+ end
58
+
59
+ def pre_process(message)
60
+ end
61
+
62
+ def process(message)
63
+ end
64
+
65
+ def message_class
66
+ end
67
+
68
+ def next_message(key:, processor_name:)
69
+ message_class.uncached do
70
+ message_class.next_in_line(key:, processor_name:)
71
+ end
72
+ end
73
+
74
+ def locking(key, &blk)
75
+ message_class.locking_process_queue(keys: [key], wait: false, &blk)
76
+ rescue QueueLocking::LockWaitTimeout
77
+ raise DuplicateJobError
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,33 @@
1
+ # typed: strict
2
+
3
+ # The periodic job acts as a fallback mechanism, polling for messages that were
4
+ # not enqueued and processed automatically upon create, e.g. due to a failure to
5
+ # push a job onto the Redis queue.
6
+ module Coil
7
+ class TransactionalMessagesPeriodicJob < ApplicationJob
8
+ def perform
9
+ t = Time.current - TransactionalMessagesJob::MAX_DURATION
10
+
11
+ # Identify distinct message types, their associated job types, and
12
+ # the distinct keys for which we have unprocessed messages (excluding
13
+ # very recent messages, since a TransactionalMessagesJob may still be
14
+ # processing those). Then, enqueue the necessary jobs for those keys.
15
+ message_parent_class.select(:type).distinct.each do |x|
16
+ message_class = x.class
17
+ job_class = x.job_class
18
+
19
+ message_class
20
+ .unprocessed(processor_name: job_class.name)
21
+ .where(created_at: nil...t)
22
+ .distinct
23
+ .pluck(:key)
24
+ .each { |k| job_class.perform_async(k) }
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ def message_parent_class
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,7 @@
1
+ # typed: strict
2
+
3
+ module Coil
4
+ class ApplicationRecord < ActiveRecord::Base
5
+ self.abstract_class = true
6
+ end
7
+ end
@@ -0,0 +1,11 @@
1
+ # typed: strict
2
+
3
+ module Coil
4
+ module Inbox
5
+ class Completion < ApplicationRecord
6
+ include PreventDestruction
7
+
8
+ attr_readonly :processor_name, :message_type, :message_key
9
+ end
10
+ end
11
+ end