aws-activejob-sqs 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0d637830be5b747a64bf196605511e325d998d43bdd378ce9377a04c4cd0d217
4
+ data.tar.gz: 3dd1d9a0385451965ef4e4efc9f51c73a9bdc5e896d4a2a9cd65c862319aac8b
5
+ SHA512:
6
+ metadata.gz: edeeb1caccc5479f6a70bffada55cce0d7a15e70088a3a9f381782be366cf8200e0a16b03291be78c551a54b18192268b32b85f8626b6f0a23cf1b2392cd7da7
7
+ data.tar.gz: 945cce4e13a9ccf35d5f2521da551dc53dc349bdb1667a20ad7ad7c8d509b97d7892761a418152afafad3656ebdecdfc2d8bee0f1922be54a72d40ea4703218f
data/CHANGELOG.md ADDED
@@ -0,0 +1,4 @@
1
+ 0.1.0 (2024-11-16)
2
+ ------------------
3
+
4
+ * Feature - Initial version of this gem.
data/LICENSE ADDED
@@ -0,0 +1,175 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.0
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative '../lib/aws/active_job/sqs/poller'
5
+
6
+ require 'rails'
7
+ require File.expand_path("config/environment.rb")
8
+
9
+ Aws::ActiveJob::SQS::Poller.new(ARGV).run
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveJob
4
+ module QueueAdapters
5
+ class SqsAdapter
6
+ # Build request parameter of Aws::SQS::Client
7
+ # @api private
8
+ class Params
9
+ class << self
10
+ def assured_delay_seconds(timestamp)
11
+ delay = (timestamp - Time.now.to_f).floor
12
+ delay = 0 if delay.negative?
13
+ raise ArgumentError, 'Unable to queue a job with a delay great than 15 minutes' if delay > 15.minutes
14
+
15
+ delay
16
+ end
17
+ end
18
+
19
+ def initialize(job, body)
20
+ @job = job
21
+ @body = body || job.serialize
22
+ end
23
+
24
+ def queue_url
25
+ @queue_url ||= Aws::ActiveJob::SQS.config.queue_url_for(@job.queue_name)
26
+ end
27
+
28
+ def entry
29
+ if Aws::ActiveJob::SQS.fifo?(queue_url)
30
+ default_entry.merge(options_for_fifo)
31
+ else
32
+ default_entry
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ def default_entry
39
+ {
40
+ message_body: Aws::Json.dump(@body),
41
+ message_attributes: message_attributes
42
+ }
43
+ end
44
+
45
+ def message_attributes
46
+ {
47
+ 'aws_sqs_active_job_class' => {
48
+ string_value: @job.class.to_s,
49
+ data_type: 'String'
50
+ },
51
+ 'aws_sqs_active_job_version' => {
52
+ string_value: Aws::ActiveJob::SQS::VERSION,
53
+ data_type: 'String'
54
+ }
55
+ }
56
+ end
57
+
58
+ def options_for_fifo
59
+ options = {}
60
+ options[:message_deduplication_id] =
61
+ Digest::SHA256.hexdigest(Aws::Json.dump(deduplication_body))
62
+
63
+ message_group_id = @job.message_group_id if @job.respond_to?(:message_group_id)
64
+ message_group_id ||= Aws::ActiveJob::SQS.config.message_group_id
65
+
66
+ options[:message_group_id] = message_group_id
67
+ options
68
+ end
69
+
70
+ def deduplication_body
71
+ ex_dedup_keys = @job.excluded_deduplication_keys if @job.respond_to?(:excluded_deduplication_keys)
72
+ ex_dedup_keys ||= Aws::ActiveJob::SQS.config.excluded_deduplication_keys
73
+
74
+ @body.except(*ex_dedup_keys)
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'aws-sdk-sqs'
4
+
5
+ module ActiveJob
6
+ module QueueAdapters
7
+ # Synchronous adapter for Amazon SQS ActiveJob. This adapter queues jobs synchronously (ie blocking).
8
+ #
9
+ # To use this adapter, set up as:
10
+ #
11
+ # config.active_job.queue_adapter = :sqs_async
12
+ class SqsAdapter
13
+ def enqueue_after_transaction_commit?
14
+ # can be removed after Rails 8
15
+ true
16
+ end
17
+
18
+ def enqueue(job)
19
+ _enqueue(job)
20
+ end
21
+
22
+ def enqueue_at(job, timestamp)
23
+ delay = Params.assured_delay_seconds(timestamp)
24
+ _enqueue(job, nil, delay_seconds: delay)
25
+ end
26
+
27
+ def enqueue_all(jobs)
28
+ enqueued_count = 0
29
+ jobs.group_by(&:queue_name).each do |queue_name, same_queue_jobs|
30
+ queue_url = Aws::ActiveJob::SQS.config.queue_url_for(queue_name)
31
+ base_send_message_opts = { queue_url: queue_url }
32
+
33
+ same_queue_jobs.each_slice(10) do |chunk|
34
+ entries = chunk.map do |job|
35
+ entry = Params.new(job, nil).entry
36
+ entry[:id] = job.job_id
37
+ entry[:delay_seconds] = Params.assured_delay_seconds(job.scheduled_at) if job.scheduled_at
38
+ entry
39
+ end
40
+
41
+ send_message_opts = base_send_message_opts.deep_dup
42
+ send_message_opts[:entries] = entries
43
+
44
+ send_message_batch_result = Aws::ActiveJob::SQS.config.client.send_message_batch(send_message_opts)
45
+ enqueued_count += send_message_batch_result.successful.count
46
+ end
47
+ end
48
+ enqueued_count
49
+ end
50
+
51
+ private
52
+
53
+ def _enqueue(job, body = nil, send_message_opts = {})
54
+ body ||= job.serialize
55
+ params = Params.new(job, body)
56
+ send_message_opts = send_message_opts.merge(params.entry)
57
+ send_message_opts[:queue_url] = params.queue_url
58
+ Aws::ActiveJob::SQS.config.client.send_message(send_message_opts)
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'aws-sdk-sqs'
4
+ require 'concurrent'
5
+
6
+ module ActiveJob
7
+ module QueueAdapters
8
+ # Asynchronous adapter for Amazon SQS ActiveJob This adapter queues jobs asynchronously (ie non-blocking).
9
+ #
10
+ # An error handler can be configured with:
11
+ #
12
+ # Aws::ActiveJob::SQS.config.async_queue_error_handler = ->(error, job, send_message_opts) { ... }
13
+ #
14
+ # To use this adapter, set up as:
15
+ #
16
+ # config.active_job.queue_adapter = :sqs_async
17
+ class SqsAsyncAdapter < SqsAdapter
18
+ private
19
+
20
+ def _enqueue(job, body = nil, send_message_opts = {})
21
+ # FIFO jobs must be queued in order, so do not queue async
22
+ queue_url = Aws::ActiveJob::SQS.config.queue_url_for(job.queue_name)
23
+ if Aws::ActiveJob::SQS.fifo?(queue_url)
24
+ super
25
+ else
26
+ # Serialize is called here because the job’s locale needs to be
27
+ # determined in this thread and not in some other thread.
28
+ body = job.serialize
29
+ Concurrent::Promises
30
+ .future { super(job, body, send_message_opts) }
31
+ .rescue do |e|
32
+ # TODO: should be config logger? fails
33
+ Rails.logger.error "Failed to queue job #{job}. Reason: #{e}"
34
+ error_handler = Aws::ActiveJob::SQS.config.async_queue_error_handler
35
+ error_handler&.call(e, job, send_message_opts)
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,183 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aws
4
+ module ActiveJob
5
+ module SQS
6
+ # Use +Aws::ActiveJob::SQS.config+ to access the singleton config instance.
7
+ class Configuration
8
+ # Default configuration options
9
+ # @api private
10
+ DEFAULTS = {
11
+ max_messages: 10,
12
+ shutdown_timeout: 15,
13
+ retry_standard_errors: true, # TODO: Remove in next MV
14
+ queues: {},
15
+ logger: ::Rails.logger,
16
+ message_group_id: 'SqsActiveJobGroup',
17
+ excluded_deduplication_keys: ['job_id']
18
+ }.freeze
19
+
20
+ # @api private
21
+ attr_accessor :queues, :max_messages, :visibility_timeout,
22
+ :shutdown_timeout, :client, :logger,
23
+ :async_queue_error_handler, :message_group_id
24
+
25
+ attr_reader :excluded_deduplication_keys
26
+
27
+ # Don't use this method directly: Configuration is a singleton class, use
28
+ # +Aws::ActiveJob::SQS.config+ to access the singleton config.
29
+ #
30
+ # @param [Hash] options
31
+ # @option options [Hash[Symbol, String]] :queues A mapping between the
32
+ # active job queue name and the SQS Queue URL. Note: multiple active
33
+ # job queues can map to the same SQS Queue URL.
34
+ #
35
+ # @option options [Integer] :max_messages
36
+ # The max number of messages to poll for in a batch.
37
+ #
38
+ # @option options [Integer] :visibility_timeout
39
+ # If unset, the visibility timeout configured on the
40
+ # SQS queue will be used.
41
+ # The visibility timeout is the number of seconds
42
+ # that a message will not be processable by any other consumers.
43
+ # You should set this value to be longer than your expected job runtime
44
+ # to prevent other processes from picking up an running job.
45
+ # See the (SQS Visibility Timeout Documentation)[https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html]
46
+ #
47
+ # @option options [Integer] :shutdown_timeout
48
+ # the amount of time to wait
49
+ # for a clean shutdown. Jobs that are unable to complete in this time
50
+ # will not be deleted from the SQS queue and will be retryable after
51
+ # the visibility timeout.
52
+ #
53
+ # @ option options [Boolean] :retry_standard_errors
54
+ # If `true`, StandardErrors raised by ActiveJobs are left on the queue
55
+ # and will be retried (pending the SQS Queue's redrive/DLQ/maximum receive settings).
56
+ # This behavior overrides the standard Rails ActiveJob
57
+ # [Retry/Discard for failed jobs](https://guides.rubyonrails.org/active_job_basics.html#retrying-or-discarding-failed-jobs)
58
+ # behavior. When set to `true` the retries provided by this will be
59
+ # on top of any retries configured on the job with `retry_on`.
60
+ # When `false`, retry behavior is fully configured
61
+ # through `retry_on`/`discard_on` on the ActiveJobs.
62
+ #
63
+ # @option options [ActiveSupport::Logger] :logger Logger to use
64
+ # for the poller.
65
+ #
66
+ # @option options [String] :config_file
67
+ # Override file to load configuration from. If not specified will
68
+ # attempt to load from config/aws_sqs_active_job.yml.
69
+ #
70
+ # @option options [String] :message_group_id (SqsActiveJobGroup)
71
+ # The message_group_id to use for queueing messages on a fifo queues.
72
+ # Applies only to jobs queued on FIFO queues.
73
+ # See the (SQS FIFO Documentation)[https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/FIFO-queues.html]
74
+ #
75
+ # @option options [Callable] :async_queue_error_handler An error handler
76
+ # to be called when the async active job adapter experiances an error
77
+ # queueing a job. Only applies when
78
+ # +active_job.queue_adapter = :sqs_async+. Called with:
79
+ # [error, job, job_options]
80
+ #
81
+ # @option options [SQS::Client] :client SQS Client to use. A default
82
+ # client will be created if none is provided.
83
+ #
84
+ # @option options [Array] :excluded_deduplication_keys (['job_id'])
85
+ # The type of keys stored in the array should be String or Symbol.
86
+ # Using this option, job_id is implicitly added to the keys.
87
+
88
+ def initialize(options = {})
89
+ options[:config_file] ||= config_file if File.exist?(config_file)
90
+ options = DEFAULTS
91
+ .merge(file_options(options))
92
+ .merge(options)
93
+ set_attributes(options)
94
+ end
95
+
96
+ def excluded_deduplication_keys=(keys)
97
+ @excluded_deduplication_keys = keys.map(&:to_s) | ['job_id']
98
+ end
99
+
100
+ def client
101
+ @client ||= begin
102
+ client = Aws::SQS::Client.new
103
+ client.config.user_agent_frameworks << 'aws-activejob-sqs'
104
+ client
105
+ end
106
+ end
107
+
108
+ # Return the queue_url for a given job_queue name
109
+ def queue_url_for(job_queue)
110
+ job_queue = job_queue.to_sym
111
+ raise ArgumentError, "No queue defined for #{job_queue}" unless queues.key? job_queue
112
+
113
+ queues[job_queue]
114
+ end
115
+
116
+ # @api private
117
+ def to_s
118
+ to_h.to_s
119
+ end
120
+
121
+ # @api private
122
+ def to_h
123
+ h = {}
124
+ instance_variables.each do |v|
125
+ v_sym = v.to_s.delete('@').to_sym
126
+ val = instance_variable_get(v)
127
+ h[v_sym] = val
128
+ end
129
+ h
130
+ end
131
+
132
+ private
133
+
134
+ # Set accessible attributes after merged options.
135
+ def set_attributes(options)
136
+ options.each_key do |opt_name|
137
+ instance_variable_set("@#{opt_name}", options[opt_name])
138
+ client.config.user_agent_frameworks << 'aws-activejob-sqs' if opt_name == :client
139
+ end
140
+ end
141
+
142
+ def file_options(options = {})
143
+ file_path = config_file_path(options)
144
+ if file_path
145
+ load_from_file(file_path)
146
+ else
147
+ {}
148
+ end
149
+ end
150
+
151
+ def config_file
152
+ file = ::Rails.root.join("config/aws_sqs_active_job/#{::Rails.env}.yml")
153
+ file = ::Rails.root.join('config/aws_sqs_active_job.yml') unless File.exist?(file)
154
+ file
155
+ end
156
+
157
+ # Load options from YAML file
158
+ def load_from_file(file_path)
159
+ opts = load_yaml(file_path) || {}
160
+ opts.deep_symbolize_keys
161
+ end
162
+
163
+ # @return [String] Configuration path found in environment or YAML file.
164
+ def config_file_path(options)
165
+ options[:config_file] || ENV.fetch('AWS_SQS_ACTIVE_JOB_CONFIG_FILE', nil)
166
+ end
167
+
168
+ def load_yaml(file_path)
169
+ require 'erb'
170
+ source = ERB.new(File.read(file_path)).result
171
+
172
+ # Avoid incompatible changes with Psych 4.0.0
173
+ # https://bugs.ruby-lang.org/issues/17866
174
+ begin
175
+ YAML.safe_load(source, aliases: true) || {}
176
+ rescue ArgumentError
177
+ YAML.safe_load(source) || {}
178
+ end
179
+ end
180
+ end
181
+ end
182
+ end
183
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aws
4
+ module ActiveJob
5
+ module SQS
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ class_attribute :excluded_deduplication_keys
10
+ end
11
+
12
+ # class methods for SQS ActiveJob.
13
+ module ClassMethods
14
+ def deduplicate_without(*keys)
15
+ self.excluded_deduplication_keys = keys.map(&:to_s) | ['job_id']
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'concurrent'
4
+
5
+ module Aws
6
+ module ActiveJob
7
+ module SQS
8
+ # CLI runner for polling for SQS ActiveJobs
9
+ class Executor
10
+ DEFAULTS = {
11
+ min_threads: 0,
12
+ max_threads: Integer(Concurrent.available_processor_count || Concurrent.processor_count),
13
+ auto_terminate: true,
14
+ idletime: 60, # 1 minute
15
+ fallback_policy: :abort # Concurrent::RejectedExecutionError must be handled
16
+ }.freeze
17
+
18
+ def initialize(options = {})
19
+ @executor = Concurrent::ThreadPoolExecutor.new(DEFAULTS.merge(options))
20
+ @retry_standard_errors = options[:retry_standard_errors]
21
+ @logger = options[:logger] || ActiveSupport::Logger.new($stdout)
22
+ @task_complete = Concurrent::Event.new
23
+ end
24
+
25
+ def execute(message)
26
+ post_task(message)
27
+ rescue Concurrent::RejectedExecutionError
28
+ # no capacity, wait for a task to complete
29
+ @task_complete.reset
30
+ @task_complete.wait
31
+ retry
32
+ end
33
+
34
+ def shutdown(timeout = nil)
35
+ @executor.shutdown
36
+ clean_shutdown = @executor.wait_for_termination(timeout)
37
+ if clean_shutdown
38
+ @logger.info 'Clean shutdown complete. All executing jobs finished.'
39
+ else
40
+ @logger.info "Timeout (#{timeout}) exceeded. Some jobs may not have " \
41
+ 'finished cleanly. Unfinished jobs will not be removed from ' \
42
+ 'the queue and can be ru-run once their visibility timeout ' \
43
+ 'passes.'
44
+ end
45
+ end
46
+
47
+ private
48
+
49
+ def post_task(message)
50
+ @executor.post(message) do |message|
51
+ job = JobRunner.new(message)
52
+ @logger.info("Running job: #{job.id}[#{job.class_name}]")
53
+ job.run
54
+ message.delete
55
+ rescue Aws::Json::ParseError => e
56
+ @logger.error "Unable to parse message body: #{message.data.body}. Error: #{e}."
57
+ rescue StandardError => e
58
+ job_msg = job ? "#{job.id}[#{job.class_name}]" : 'unknown job'
59
+ @logger.info "Error processing job #{job_msg}: #{e}"
60
+ @logger.debug e.backtrace.join("\n")
61
+
62
+ if @retry_standard_errors && !job.exception_executions?
63
+ @logger.info(
64
+ 'retry_standard_errors is enabled and job has not ' \
65
+ "been retried by Rails. Leaving #{job_msg} in the queue."
66
+ )
67
+ else
68
+ message.delete
69
+ end
70
+ ensure
71
+ @task_complete.set
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Aws
4
+ module ActiveJob
5
+ module SQS
6
+ # @api private
7
+ class JobRunner
8
+ attr_reader :id, :class_name
9
+
10
+ def initialize(message)
11
+ @job_data = Aws::Json.load(message.data.body)
12
+ @class_name = @job_data['job_class'].constantize
13
+ @id = @job_data['job_id']
14
+ end
15
+
16
+ def run
17
+ ::ActiveJob::Base.execute @job_data
18
+ end
19
+
20
+ def exception_executions?
21
+ @job_data['exception_executions'] &&
22
+ !@job_data['exception_executions'].empty?
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'aws-sdk-sqs'
4
+
5
+ module Aws
6
+ module ActiveJob
7
+ module SQS
8
+ class << self
9
+ # A lambda event handler to run jobs from an SQS queue trigger.
10
+ # Configure the entrypoint to: +config/environment.Aws::ActiveJob::SQS.lambda_job_handler+
11
+ # This will load your Rails environment, and then use this method as the handler.
12
+ def lambda_job_handler(event:, context:)
13
+ return 'no records to process' unless event['Records']
14
+
15
+ event['Records'].each do |record|
16
+ sqs_msg = to_sqs_msg(record)
17
+ job = Aws::ActiveJob::SQS::JobRunner.new(sqs_msg)
18
+ puts("Running job: #{job.id}[#{job.class_name}]")
19
+ job.run
20
+ sqs_msg.delete
21
+ end
22
+ "Processed #{event['Records'].length} jobs."
23
+ end
24
+
25
+ private
26
+
27
+ def to_sqs_msg(record)
28
+ msg = Aws::SQS::Types::Message.new(
29
+ body: record['body'],
30
+ md5_of_body: record['md5OfBody'],
31
+ message_attributes: to_message_attributes(record),
32
+ message_id: record['messageId'],
33
+ receipt_handle: record['receiptHandle']
34
+ )
35
+ Aws::SQS::Message.new(
36
+ queue_url: to_queue_url(record),
37
+ receipt_handle: msg.receipt_handle,
38
+ data: msg,
39
+ client: Aws::ActiveJob::SQS.config.client
40
+ )
41
+ end
42
+
43
+ def to_message_attributes(record)
44
+ record['messageAttributes'].transform_values do |value|
45
+ {
46
+ string_value: value['stringValue'],
47
+ binary_value: value['binaryValue'],
48
+ string_list_values: ['stringListValues'],
49
+ binary_list_values: value['binaryListValues'],
50
+ data_type: value['dataType']
51
+ }
52
+ end
53
+ end
54
+
55
+ def to_queue_url(record)
56
+ source_arn = record['eventSourceARN']
57
+ raise ArgumentError, "Invalid queue arn: #{source_arn}" unless Aws::ARNParser.arn?(source_arn)
58
+
59
+ arn = Aws::ARNParser.parse(source_arn)
60
+ sfx = Aws::Partitions::EndpointProvider.dns_suffix_for(arn.region)
61
+ "https://sqs.#{arn.region}.#{sfx}/#{arn.account_id}/#{arn.resource}"
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'aws-sdk-sqs'
4
+ require 'optparse'
5
+ require 'concurrent'
6
+
7
+ module Aws
8
+ module ActiveJob
9
+ module SQS
10
+ # CLI runner for polling for SQS ActiveJobs
11
+ # Use `aws_sqs_active_job --help` for detailed usage
12
+ class Poller
13
+ class Interrupt < StandardError; end
14
+
15
+ DEFAULT_OPTS = {
16
+ threads: 2 * Concurrent.processor_count,
17
+ max_messages: 10,
18
+ shutdown_timeout: 15,
19
+ backpressure: 10,
20
+ retry_standard_errors: true
21
+ }.freeze
22
+
23
+ def initialize(args = ARGV)
24
+ @options = parse_args(args)
25
+ # Set_environment must be run before we boot_rails
26
+ set_environment
27
+ end
28
+
29
+ def set_environment
30
+ @environment = @options[:environment] || ENV['APP_ENV'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
31
+ end
32
+
33
+ def run
34
+ # exit 0
35
+ boot_rails
36
+
37
+ # cannot load config (from file or initializers) until after
38
+ # rails has been booted.
39
+ @options = DEFAULT_OPTS
40
+ .merge(Aws::ActiveJob::SQS.config.to_h)
41
+ .merge(@options.to_h)
42
+ validate_config
43
+ # ensure we have a logger configured
44
+ @logger = @options[:logger] || ActiveSupport::Logger.new($stdout)
45
+ @logger.info("Starting Poller with options=#{@options}")
46
+
47
+ Signal.trap('INT') { raise Interrupt }
48
+ Signal.trap('TERM') { raise Interrupt }
49
+ @executor = Executor.new(
50
+ max_threads: @options[:threads],
51
+ logger: @logger,
52
+ max_queue: @options[:backpressure],
53
+ retry_standard_errors: @options[:retry_standard_errors]
54
+ )
55
+
56
+ poll
57
+ rescue Interrupt
58
+ @logger.info 'Process Interrupted or killed - attempting to shutdown cleanly.'
59
+ shutdown
60
+ exit
61
+ end
62
+
63
+ private
64
+
65
+ def shutdown
66
+ @executor.shutdown(@options[:shutdown_timeout])
67
+ end
68
+
69
+ def poll
70
+ queue_url = Aws::ActiveJob::SQS.config.queue_url_for(@options[:queue])
71
+ @logger.info "Polling on: #{@options[:queue]} => #{queue_url}"
72
+ client = Aws::ActiveJob::SQS.config.client
73
+ @poller = Aws::SQS::QueuePoller.new(queue_url, client: client)
74
+ poller_options = {
75
+ skip_delete: true,
76
+ max_number_of_messages: @options[:max_messages],
77
+ visibility_timeout: @options[:visibility_timeout]
78
+ }
79
+ # Limit max_number_of_messages for FIFO queues to 1
80
+ # this ensures jobs with the same message_group_id are processed
81
+ # in order
82
+ # Jobs with different message_group_id will be processed in
83
+ # parallel and may be out of order.
84
+ poller_options[:max_number_of_messages] = 1 if Aws::ActiveJob::SQS.fifo?(queue_url)
85
+
86
+ single_message = poller_options[:max_number_of_messages] == 1
87
+
88
+ @poller.poll(poller_options) do |msgs|
89
+ msgs = [msgs] if single_message
90
+ @logger.info "Processing batch of #{msgs.length} messages"
91
+ msgs.each do |msg|
92
+ @executor.execute(Aws::SQS::Message.new(
93
+ queue_url: queue_url,
94
+ receipt_handle: msg.receipt_handle,
95
+ data: msg,
96
+ client: client
97
+ ))
98
+ end
99
+ end
100
+ end
101
+
102
+ def boot_rails
103
+ ENV['RACK_ENV'] = ENV['RAILS_ENV'] = @environment
104
+ require 'rails'
105
+ require File.expand_path('config/environment.rb')
106
+ end
107
+
108
+ # rubocop:disable Metrics
109
+ def parse_args(argv)
110
+ out = {}
111
+ parser = ::OptionParser.new do |opts|
112
+ opts.on('-q', '--queue STRING', '[Required] Queue to poll') { |a| out[:queue] = a }
113
+ opts.on('-e', '--environment STRING',
114
+ 'Rails environment (defaults to development). You can also use the APP_ENV or RAILS_ENV environment variables to specify the environment.') do |a|
115
+ out[:environment] = a
116
+ end
117
+ opts.on('-t', '--threads INTEGER', Integer,
118
+ 'The maximum number of worker threads to create. Defaults to 2x the number of processors available on this system.') do |a|
119
+ out[:threads] = a
120
+ end
121
+ opts.on('-b', '--backpressure INTEGER', Integer,
122
+ 'The maximum number of messages to have waiting in the Executor queue. This should be a low, but non zero number. Messages in the Executor queue cannot be picked up by other processes and will slow down shutdown.') do |a|
123
+ out[:backpressure] = a
124
+ end
125
+ opts.on('-m', '--max_messages INTEGER', Integer,
126
+ 'Max number of messages to receive in a batch from SQS.') do |a|
127
+ out[:max_messages] = a
128
+ end
129
+ opts.on('-v', '--visibility_timeout INTEGER', Integer,
130
+ 'The visibility timeout is the number of seconds that a message will not be processable by any other consumers. You should set this value to be longer than your expected job runtime to prevent other processes from picking up an running job. See the SQS Visibility Timeout Documentation at https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html.') do |a|
131
+ out[:visibility_timeout] = a
132
+ end
133
+ opts.on('-s', '--shutdown_timeout INTEGER', Integer,
134
+ 'The amount of time to wait for a clean shutdown. Jobs that are unable to complete in this time will not be deleted from the SQS queue and will be retryable after the visibility timeout.') do |a|
135
+ out[:shutdown_timeout] = a
136
+ end
137
+ opts.on('--[no-]retry_standard_errors [FLAG]', TrueClass,
138
+ 'When set, retry all StandardErrors (leaving failed messages on the SQS Queue). These retries are ON TOP of standard Rails ActiveJob retries set by retry_on in the ActiveJob.') do |a|
139
+ out[:retry_standard_errors] = a.nil? ? true : a
140
+ end
141
+ end
142
+
143
+ parser.banner = 'aws_sqs_active_job [options]'
144
+ parser.on_tail '-h', '--help', 'Show help' do
145
+ puts parser
146
+ exit 1
147
+ end
148
+
149
+ parser.parse(argv)
150
+ out
151
+ end
152
+ # rubocop:enable Metrics
153
+
154
+ def validate_config
155
+ raise ArgumentError, 'You must specify the name of the queue to process jobs from' unless @options[:queue]
156
+ end
157
+ end
158
+ end
159
+ end
160
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'active_job/queue_adapters/sqs_adapter'
4
+ require_relative 'active_job/queue_adapters/sqs_adapter/params'
5
+ require_relative 'active_job/queue_adapters/sqs_async_adapter'
6
+ require_relative 'aws/active_job/sqs/configuration'
7
+ require_relative 'aws/active_job/sqs/deduplication'
8
+ require_relative 'aws/active_job/sqs/executor'
9
+ require_relative 'aws/active_job/sqs/job_runner'
10
+ require_relative 'aws/active_job/sqs/lambda_handler'
11
+
12
+ module Aws
13
+ module ActiveJob
14
+ module SQS
15
+ VERSION = File.read(File.expand_path('../VERSION', __dir__)).strip
16
+
17
+ # @return [Configuration] the (singleton) Configuration
18
+ def self.config
19
+ @config ||= Configuration.new
20
+ end
21
+
22
+ # @yield Configuration
23
+ def self.configure
24
+ yield(config)
25
+ end
26
+
27
+ # @param queue_url [String]
28
+ # @return [Boolean] true if the queue_url is a FIFO queue
29
+ def self.fifo?(queue_url)
30
+ queue_url.end_with?('.fifo')
31
+ end
32
+ end
33
+ end
34
+ end
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: aws-activejob-sqs
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Amazon Web Services
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-11-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: aws-sdk-sqs
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 1.56.0
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '1'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 1.56.0
33
+ - !ruby/object:Gem::Dependency
34
+ name: activejob
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: 7.1.0
40
+ type: :runtime
41
+ prerelease: false
42
+ version_requirements: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 7.1.0
47
+ - !ruby/object:Gem::Dependency
48
+ name: concurrent-ruby
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '1'
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '1'
61
+ description: Amazon Simple Queue Service as an ActiveJob adapter
62
+ email:
63
+ - aws-dr-rubygems@amazon.com
64
+ executables:
65
+ - aws_sqs_active_job
66
+ extensions: []
67
+ extra_rdoc_files: []
68
+ files:
69
+ - CHANGELOG.md
70
+ - LICENSE
71
+ - VERSION
72
+ - bin/aws_sqs_active_job
73
+ - lib/active_job/queue_adapters/sqs_adapter.rb
74
+ - lib/active_job/queue_adapters/sqs_adapter/params.rb
75
+ - lib/active_job/queue_adapters/sqs_async_adapter.rb
76
+ - lib/aws-activejob-sqs.rb
77
+ - lib/aws/active_job/sqs/configuration.rb
78
+ - lib/aws/active_job/sqs/deduplication.rb
79
+ - lib/aws/active_job/sqs/executor.rb
80
+ - lib/aws/active_job/sqs/job_runner.rb
81
+ - lib/aws/active_job/sqs/lambda_handler.rb
82
+ - lib/aws/active_job/sqs/poller.rb
83
+ homepage: https://github.com/aws/aws-activejob-sqs-ruby
84
+ licenses:
85
+ - Apache-2.0
86
+ metadata: {}
87
+ post_install_message:
88
+ rdoc_options: []
89
+ require_paths:
90
+ - lib
91
+ required_ruby_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '2.7'
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ requirements: []
102
+ rubygems_version: 3.5.11
103
+ signing_key:
104
+ specification_version: 4
105
+ summary: ActiveJob integration with SQS
106
+ test_files: []