async_active_job 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: 781ab804ad113969151deac3374e5eade276e6ecc27beb6891dd32e3bf30e970
4
+ data.tar.gz: 2546f62c46dffd62fc18ead62a846f7cfbc417312b9fe95c648fbdeed2868a1c
5
+ SHA512:
6
+ metadata.gz: a27ce2db6a039665b9b5a28cf68c310c05126e3a25e9571c0a1a841c54065744d6a79aeb7c77b83d14e86fcdf515fb806ccf4d00d69c282845d87f334c6b7d30
7
+ data.tar.gz: 61bee175e0d4a86371b9994c2edbe3b50dcefc0f78cac68c29971aecff9df14545061806dbb09b8fcdba8c59924e1997c7cd226e919b16df5ededbd092c6808d
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,130 @@
1
+ # https://docs.rubocop.org/rubocop/1.9/index.html
2
+
3
+ require:
4
+ - rubocop-rails
5
+ - rubocop-performance
6
+ - rubocop-rake
7
+ - rubocop-rspec
8
+
9
+ AllCops:
10
+ TargetRubyVersion: 2.6
11
+ DisplayCopNames: true
12
+ NewCops: enable
13
+ Exclude:
14
+ - 'bin/*'
15
+ - 'tmp/**/*'
16
+ - 'vendor/**/*'
17
+
18
+ Layout/DotPosition:
19
+ EnforcedStyle: leading
20
+
21
+ Layout/SpaceInsideArrayLiteralBrackets:
22
+ EnforcedStyle: no_space
23
+
24
+ Layout/LineLength:
25
+ Max: 120
26
+
27
+ Layout/MultilineArrayBraceLayout:
28
+ EnforcedStyle: new_line
29
+
30
+ Layout/MultilineHashBraceLayout:
31
+ EnforcedStyle: new_line
32
+
33
+ Layout/MultilineMethodCallBraceLayout:
34
+ EnforcedStyle: new_line
35
+
36
+ Layout/FirstArgumentIndentation:
37
+ EnforcedStyle: consistent_relative_to_receiver
38
+
39
+ Lint/ScriptPermission:
40
+ Exclude:
41
+ - 'lib/generators/async_active_job/templates/*'
42
+
43
+ Metrics/BlockLength:
44
+ Max: 80
45
+ Exclude:
46
+ - "spec/**/*.rb"
47
+
48
+ Metrics/MethodLength:
49
+ Max: 40
50
+ Exclude:
51
+ - "spec/**/*.rb"
52
+
53
+ Metrics/ParameterLists:
54
+ Max: 3
55
+ CountKeywordArgs: false
56
+
57
+ Metrics/AbcSize:
58
+ Enabled: false
59
+
60
+ Metrics/BlockNesting:
61
+ Max: 5
62
+ Exclude:
63
+ - "spec/**/*.rb"
64
+
65
+ Metrics/ClassLength:
66
+ Enabled: false
67
+
68
+ Metrics/CyclomaticComplexity:
69
+ Enabled: false
70
+
71
+ Metrics/ModuleLength:
72
+ Enabled: false
73
+
74
+ Metrics/PerceivedComplexity:
75
+ Enabled: false
76
+
77
+ Style/Documentation:
78
+ Enabled: false
79
+
80
+ Style/SymbolArray:
81
+ EnforcedStyle: brackets
82
+
83
+ Style/WordArray:
84
+ EnforcedStyle: brackets
85
+
86
+ # All lambda will be like `->() {}`, `->() do end`.
87
+ Style/Lambda:
88
+ EnforcedStyle: literal
89
+
90
+ Style/ConditionalAssignment:
91
+ Enabled: false
92
+
93
+ Style/EmptyMethod:
94
+ EnforcedStyle: expanded
95
+
96
+ Style/SingleLineMethods:
97
+ AllowIfMethodIsEmpty: false
98
+
99
+ Style/FormatStringToken:
100
+ Enabled: false
101
+
102
+ Rails/NotNullColumn:
103
+ Enabled: false
104
+
105
+ RSpec/SharedExamples:
106
+ Enabled: false
107
+
108
+ RSpec/DescribeClass:
109
+ Enabled: false
110
+
111
+ RSpec/ExampleLength:
112
+ Enabled: false
113
+
114
+ RSpec/MultipleMemoizedHelpers:
115
+ Enabled: false
116
+
117
+ RSpec/NamedSubject:
118
+ Enabled: false
119
+
120
+ RSpec/MultipleExpectations:
121
+ Enabled: false
122
+
123
+ RSpec/MessageSpies:
124
+ EnforcedStyle: receive
125
+
126
+ RSpec/ExpectChange:
127
+ EnforcedStyle: block
128
+
129
+ RSpec/Rails/HttpStatus:
130
+ EnforcedStyle: numeric
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2021-11-27
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at senid231@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in async_active_job.gemspec
6
+ gemspec
7
+
8
+ gem 'rails', ENV.fetch('RAILS_VERSION', '~> 6.0')
9
+
10
+ gem 'rake', '~> 13.0'
11
+
12
+ gem 'rspec', '~> 3.0'
13
+
14
+ gem 'rubocop', '~> 1.21'
15
+ gem 'rubocop-performance'
16
+ gem 'rubocop-rails'
17
+ gem 'rubocop-rake'
18
+ gem 'rubocop-rspec'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Denis Talakevich
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # AsyncActiveJob
2
+
3
+ [![Tests](https://github.com/senid231/async_active_job/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/senid231/async_active_job/actions/workflows/tests.yml)
4
+
5
+ Multi-fiber, Postgres-based, ActiveJob backend for Ruby on Rails.
6
+ Based on [async](https://github.com/socketry/async)
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'async_active_job'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle install
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install async_active_job
23
+
24
+ ## Usage
25
+
26
+ Add to `config/application.rb`:
27
+ ```ruby
28
+ config.active_job.queue_adapter = :async_active_job
29
+ ```
30
+
31
+ Generate `bin/async_active_job` file:
32
+ ```shell
33
+ $ rails g async_active_job
34
+ ```
35
+
36
+ Generate migration:
37
+ ```shell
38
+ $ rails g async_active_job:active_record
39
+ ```
40
+
41
+ Apply migration:
42
+ ```shell
43
+ $ rails db:migrate
44
+ ```
45
+
46
+ Create `config/initilizers/async_active_job.rb` to override configuration defaults:
47
+ ```ruby
48
+ AsyncJob.configure do |config|
49
+ # config.default_max_attempts = 25
50
+ # config.default_next_run_at = ->(now, opts) { opts[:attempts].minutes.from_now(now) }
51
+ # config.max_run_timeout = 1.hour
52
+ # config.default_priority = 0
53
+ # config.default_queue_name = nil
54
+ # config.no_job_sleep_duration = 3
55
+ # config.task_limit = nil
56
+ # config.task_limit_sleep_duration = 3
57
+ # config.active_record_base_class_name = 'ApplicationRecord'
58
+ end
59
+ ```
60
+
61
+ Start `async_active_job` process:
62
+ ```shell
63
+ $ bundle exec bin/async_active_job
64
+ ```
65
+
66
+ ## Development
67
+
68
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
69
+
70
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
71
+
72
+ ## Contributing
73
+
74
+ Bug reports and pull requests are welcome on GitHub at https://github.com/senid231/async_active_job. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/senid231/async_active_job/blob/master/CODE_OF_CONDUCT.md).
75
+
76
+ ## License
77
+
78
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
79
+
80
+ ## Code of Conduct
81
+
82
+ Everyone interacting in the AsyncActiveJob project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/senid231/async_active_job/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: [:spec, :rubocop]
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsyncActiveJob
4
+ class Job < AsyncActiveJob.configuration.active_record_base_class
5
+ self.table_name = 'async_active_jobs'
6
+
7
+ PRIORITY_MIN = -32_768
8
+ PRIORITY_MAX = 32_767
9
+ ATTEMPTS_MIN = 0
10
+ ATTEMPTS_MAX = 32_767
11
+
12
+ before_validation on: :create do
13
+ self.queue_name = AsyncActiveJob.configuration.default_queue_name if queue_name.blank?
14
+ self.priority ||= AsyncActiveJob.configuration.default_priority
15
+ end
16
+
17
+ validates :job_data, presence: true
18
+ validates :priority, numericality: {
19
+ only_integer: true,
20
+ greater_than_or_equal_to: PRIORITY_MIN,
21
+ less_than_or_equal_to: PRIORITY_MAX
22
+ }
23
+ validates :attempts, numericality: {
24
+ only_integer: true,
25
+ greater_than_or_equal_to: ATTEMPTS_MIN,
26
+ less_than_or_equal_to: ATTEMPTS_MAX
27
+ }
28
+
29
+ before_save do
30
+ self.queue_name = queue_name&.presence
31
+ end
32
+
33
+ scope :not_locked, -> do
34
+ timeout = AsyncActiveJob.configuration.max_run_timeout
35
+ where('locked_at IS NULL OR locked_at < ?', current_time_from_proper_timezone - timeout)
36
+ end
37
+
38
+ scope :ready, -> do
39
+ where('run_at IS NOT NULL AND run_at <= ?', current_time_from_proper_timezone)
40
+ end
41
+
42
+ scope :order_by_priority, -> do
43
+ order('priority ASC, run_at ASC')
44
+ end
45
+
46
+ scope :with_queues, ->(queue_names) do
47
+ if queue_names.nil?
48
+ all
49
+ else
50
+ where(queue_name: queue_names)
51
+ end
52
+ end
53
+
54
+ class << self
55
+ # @param job_wrapper [AsyncActiveJob::Adapter::JobWrapper]
56
+ # @param options [Hash] with keys:
57
+ # queue_name [String,nil]
58
+ # priority [Integer,nil]
59
+ # run_at [Time]
60
+ def enqueue(job_wrapper, options = {})
61
+ options.assert_valid_keys(:queue_name, :priority, :run_at)
62
+ record = new(job_wrapper: job_wrapper, **options)
63
+ record.save!
64
+ record
65
+ end
66
+
67
+ # UPDATE async_active_jobs
68
+ # SET locked_at = ?, locked_by = ?
69
+ # WHERE id IN (
70
+ # SELECT id FROM async_active_jobs WHERE ... ORDER BY ... LIMIT 1 FOR UPDATE
71
+ # )
72
+ # @param queue_names [Array,nil]
73
+ # @return [AsyncActiveJob::Job,nil]
74
+ def next_with_lock(queue_names)
75
+ quoted_name = connection.quote_table_name(table_name)
76
+ ready_scope = AsyncActiveJob::Job.not_locked.ready.with_queues(queue_names).order_by_priority
77
+ subquery = ready_scope.limit(1).lock(true).select(:id).to_sql
78
+ sql = "UPDATE #{quoted_name} SET locked_at = ?, locked_by = ? WHERE id IN (#{subquery}) RETURNING *"
79
+ result = find_by_sql([sql, current_time_from_proper_timezone, Process.pid])
80
+ result[0]
81
+ end
82
+
83
+ # @param async_active_job [AsyncActiveJob::Job]
84
+ def perform_job(async_active_job)
85
+ async_active_job.perform
86
+ async_active_job.destroy!
87
+ rescue StandardError => e
88
+ handle_failed_job(async_active_job, e)
89
+ end
90
+
91
+ def calculate_max_attempts(active_job_class)
92
+ if active_job_class.respond_to?(:max_attempts)
93
+ active_job_class.max_attempts
94
+ else
95
+ AsyncActiveJob.configuration.default_max_attempts
96
+ end
97
+ end
98
+
99
+ def calculate_next_run_at(active_job_class, options)
100
+ now = current_time_from_proper_timezone
101
+ if active_job_class.respond_to?(:next_run_at)
102
+ active_job_class.next_run_at(now, options)
103
+ else
104
+ AsyncActiveJob.configuration.default_next_run_at.call(now, options)
105
+ end
106
+ end
107
+
108
+ # @param async_active_job [AsyncActiveJob::Job]
109
+ # @param error [Exception]
110
+ def handle_failed_job(async_active_job, error)
111
+ attempts = async_active_job.attempts + 1
112
+ max_attempts = calculate_max_attempts(async_active_job.active_job_class)
113
+
114
+ if attempts >= max_attempts
115
+ next_run_at = nil
116
+ failed_at = current_time_from_proper_timezone
117
+ else
118
+ next_run_at = calculate_next_run_at(
119
+ async_active_job.active_job_class,
120
+ attempts: attempts,
121
+ max_attempts: max_attempts,
122
+ run_at: async_active_job.run_at
123
+ )
124
+ failed_at = nil
125
+ end
126
+
127
+ async_active_job.update!(
128
+ job_wrapper: async_active_job.job_wrapper,
129
+ attempts: attempts,
130
+ last_error: format_error(error),
131
+ run_at: next_run_at,
132
+ locked_at: nil,
133
+ locked_by: nil,
134
+ failed_at: failed_at
135
+ )
136
+ end
137
+
138
+ def format_error(error, causes: [])
139
+ lines = ["#{error.class} #{error.message}", error.backtrace&.join("\n")]
140
+ if error.cause && error.cause != error && causes.exclude?(error.cause)
141
+ new_causes = causes + [error]
142
+ lines.push "Caused by:\n#{format_error(error.cause, causes: new_causes)}"
143
+ end
144
+ lines.compact.join("\n")
145
+ end
146
+ end
147
+
148
+ delegate :perform, :active_job_class, to: :job_wrapper
149
+
150
+ def active_job_id
151
+ job_data['job_id']
152
+ end
153
+
154
+ # @return [AsyncActiveJob::Adapter::JobWrapper] with job_data:
155
+ # "job_class" => self.class.name,
156
+ # "job_id" => job_id,
157
+ # "provider_job_id" => provider_job_id,
158
+ # "queue_name" => queue_name,
159
+ # "priority" => priority,
160
+ # "arguments" => serialize_arguments_if_needed(arguments),
161
+ # "executions" => executions,
162
+ # "exception_executions" => exception_executions,
163
+ # "locale" => I18n.locale.to_s,
164
+ # "timezone" => timezone,
165
+ # "enqueued_at" => Time.now.utc.iso8601
166
+ def job_wrapper
167
+ return if job_data.nil?
168
+
169
+ data = job_data.merge('provider_job_id' => id)
170
+ @job_wrapper ||= AsyncActiveJob::Adapter::JobWrapper.new(data)
171
+ end
172
+
173
+ # @param job_wrapper [AsyncActiveJob::Adapter::JobWrapper]
174
+ def job_wrapper=(job_wrapper)
175
+ self.job_data = job_wrapper.job_data.except('provider_job_id')
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/async_active_job/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'async_active_job'
7
+ spec.version = AsyncActiveJob::VERSION
8
+ spec.authors = ['Denis Talakevich']
9
+ spec.email = ['senid231@gmail.com']
10
+
11
+ spec.summary = 'Multi-fiber, Postgres-based, ActiveJob backend for Ruby on Rails'
12
+ spec.homepage = 'https://github.com/senid231/async_active_job'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = '>= 2.6.0'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = "#{spec.homepage}/tree/master"
18
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
23
+ `git ls-files -z`.split("\x0").reject do |f|
24
+ (f == __FILE__) || f.match(%r{\A(?:(?:spec)/|\.(?:git|github))})
25
+ end
26
+ end
27
+ spec.require_paths = ['lib']
28
+
29
+ spec.add_dependency 'activejob'
30
+ spec.add_dependency 'async', '~> 1.0'
31
+ spec.add_dependency 'dry-cli', '~> 0.6'
32
+ spec.metadata = {
33
+ 'rubygems_mfa_required' => 'true'
34
+ }
35
+ end
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'async_active_job'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActiveJob
4
+ module QueueAdapters
5
+ class AsyncActiveJobAdapter < AsyncActiveJob::Adapter
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsyncActiveJob
4
+ class Adapter
5
+ # @param active_job [ActiveJob::Base] the job to be enqueued from +#perform_later+
6
+ # @return [AsyncActiveJob::Job]
7
+ def enqueue(active_job)
8
+ enqueue_at(active_job, nil)
9
+ end
10
+
11
+ # @param active_job [ActiveJob::Base] the job to be enqueued from +#perform_later+
12
+ # @param timestamp [Integer, nil] the epoch time to perform the job
13
+ # @return [AsyncActiveJob::Job]
14
+ def enqueue_at(active_job, timestamp)
15
+ scheduled_at = timestamp ? Time.zone.at(timestamp) : nil
16
+ opts = { active_job: active_job, scheduled_at: scheduled_at }
17
+ ActiveSupport::Notifications.instrument('enqueue_job.async_active_job', opts) do |instrument_payload|
18
+ async_active_job = AsyncActiveJob::Job.enqueue(
19
+ JobWrapper.new(active_job.serialize),
20
+ queue_name: active_job.queue_name || AsyncActiveJob.configuration.default_queue_name,
21
+ priority: active_job.priority || AsyncActiveJob.configuration.default_priority,
22
+ run_at: scheduled_at || Time.zone.now
23
+ )
24
+ instrument_payload[:async_active_job] = async_active_job
25
+ active_job.provider_job_id = async_active_job.id
26
+ async_active_job
27
+ end
28
+ end
29
+
30
+ class JobWrapper # :nodoc:
31
+ attr_accessor :job_data
32
+
33
+ def initialize(job_data)
34
+ @job_data = job_data
35
+ end
36
+
37
+ def active_job_class
38
+ job_data['job_class'].constantize
39
+ end
40
+
41
+ def perform
42
+ ActiveJob::Base.execute(job_data)
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'async_active_job'
4
+ require 'async_active_job/runner'
5
+ require 'dry/cli'
6
+
7
+ module AsyncActiveJob
8
+ module CLI
9
+ module Commands
10
+ extend Dry::CLI::Registry
11
+
12
+ class Version < Dry::CLI::Command
13
+ desc 'Print version'
14
+
15
+ def call(*)
16
+ Rails.logger.debug AsyncActiveJob::VERSION
17
+ end
18
+ end
19
+
20
+ class Start < Dry::CLI::Command
21
+ desc 'Start worker'
22
+
23
+ option :queues, desc: 'comma separated list of queue names'
24
+
25
+ def call(queues: nil, **)
26
+ queues = queues&.split(',')
27
+ AsyncActiveJob::Runner.start(queues: queues)
28
+ end
29
+ end
30
+
31
+ register 'version', Version, aliases: ['v', '-v', '--version']
32
+ register 'start', Start
33
+ end
34
+
35
+ module_function
36
+
37
+ def call(arguments)
38
+ Dry::CLI.new(Commands).call(arguments: arguments)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'singleton'
4
+
5
+ module AsyncActiveJob
6
+ class Configuration
7
+ include Singleton
8
+
9
+ class << self
10
+ def attr_config(name, default:)
11
+ ivar = :"@#{name}"
12
+ attr_writer name
13
+
14
+ define_method(name) { instance_variable_defined?(ivar) ? instance_variable_get(ivar) : default }
15
+ end
16
+ end
17
+
18
+ # @!method default_max_attempts [Integer]
19
+ # @return [Integer]
20
+ # @!method default_max_attempts=(value)
21
+ # @param value [Integer]
22
+ attr_config :default_max_attempts, default: 25
23
+
24
+ # @!method default_next_run_at
25
+ # @return [Proc]
26
+ # @!method default_next_run_at=(value)
27
+ # @param value [Proc]
28
+ attr_config :default_next_run_at, default: ->(now, opts) { opts[:attempts].minutes.from_now(now) }
29
+
30
+ # @!method max_run_timeout [Integer]
31
+ # @return [Integer]
32
+ # @!method max_run_timeout=(value)
33
+ # @param value [Integer]
34
+ attr_config :max_run_timeout, default: 60 * 60 # 1 hour
35
+
36
+ # @!method default_priority
37
+ # @return [Integer]
38
+ # @!method default_priority=(value)
39
+ # @param value [Integer]
40
+ attr_config :default_priority, default: 0
41
+
42
+ # @!method default_queue_name
43
+ # @return [String,nil]
44
+ # @!method default_queue_name=(value)
45
+ # @param value [String,nil]
46
+ attr_config :default_queue_name, default: nil
47
+
48
+ # @!method no_job_sleep_duration
49
+ # @return [Integer]
50
+ # @!method no_job_sleep_duration=(value)
51
+ # @param value [Integer]
52
+ attr_config :no_job_sleep_duration, default: 3
53
+
54
+ # @!method task_limit
55
+ # @return [Integer,nil]
56
+ # @!method task_limit=(value)
57
+ # @param value [Integer,nil]
58
+ attr_config :task_limit, default: nil
59
+
60
+ # @!method task_limit_sleep_duration
61
+ # @return [Integer]
62
+ # @!method task_limit_sleep_duration=(value)
63
+ # @param value [Integer]
64
+ attr_config :task_limit_sleep_duration, default: 3
65
+
66
+ # @!method active_record_base_class_name
67
+ # @return [String]
68
+ # @!method active_record_base_class_name=(value)
69
+ # @param value [String]
70
+ attr_config :active_record_base_class_name, default: 'ApplicationRecord'
71
+
72
+ # @return [Class<ActiveRecord::Base>]
73
+ def active_record_base_class
74
+ active_record_base_class_name.constantize
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsyncActiveJob
4
+ class Engine < ::Rails::Engine
5
+ isolate_namespace AsyncActiveJob
6
+ end
7
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'async'
4
+
5
+ module AsyncActiveJob
6
+ class Runner
7
+ class << self
8
+ def start(queues: nil)
9
+ new(queues: queues).start
10
+ end
11
+ end
12
+
13
+ # @param queues [Array,nil]
14
+ def initialize(queues: nil)
15
+ @reactor = nil
16
+ @logger = Rails.logger
17
+ @interrupted = false
18
+ @task_count = 0
19
+ @queues = queues&.presence
20
+ end
21
+
22
+ def start
23
+ trap('TERM') { interrupt! }
24
+ trap('INT') { interrupt! }
25
+
26
+ ::Async::Reactor.run do
27
+ @reactor = Async::Task.current.reactor
28
+ loop do
29
+ if interrupted?
30
+ logger.info { 'Exiting...' }
31
+ break
32
+ end
33
+ run_once
34
+ end
35
+ end
36
+ end
37
+
38
+ def run_once
39
+ task_limit = AsyncActiveJob.configuration.task_limit
40
+ task_limit_sleep_duration = AsyncActiveJob.configuration.task_limit_sleep_duration
41
+ if task_limit && task_count >= task_limit
42
+
43
+ logger.debug { "Task limit #{task_limit} reached, sleeping for #{task_limit_sleep_duration} seconds" }
44
+ reactor.sleep(task_limit_sleep_duration)
45
+ return
46
+ end
47
+
48
+ async_active_job = AsyncActiveJob::Job.next_with_lock(queues)
49
+ if async_active_job
50
+ run_task do
51
+ with_optional_timeout(AsyncActiveJob.configuration.max_run_timeout) do
52
+ run_job(async_active_job)
53
+ end
54
+ end
55
+ reactor.sleep(0)
56
+ else
57
+ no_job_sleep_duration = AsyncActiveJob.configuration.no_job_sleep_duration
58
+ logger.debug { "No jobs, sleeping for #{no_job_sleep_duration} seconds" }
59
+ reactor.sleep(no_job_sleep_duration)
60
+ end
61
+ end
62
+
63
+ private
64
+
65
+ attr_reader :reactor, :logger, :queues
66
+ attr_accessor :task_count
67
+
68
+ def with_optional_timeout(duration, &block)
69
+ return yield if duration.nil?
70
+
71
+ reactor.with_timeout(duration, &block)
72
+ end
73
+
74
+ def run_job(async_active_job)
75
+ self.task_count += 1
76
+ job_name = "AsyncActiveJob::Job##{async_active_job.id} (Job ID: #{async_active_job.active_job_id})"
77
+ logger.debug { "Performing #{job_name}" }
78
+ ms = Benchmark.ms { AsyncActiveJob::Job.perform_job(async_active_job) }
79
+ logger.debug { format("#{job_name} performed in %.2fms", ms) }
80
+ self.task_count -= 1
81
+ end
82
+
83
+ def run_task(&block)
84
+ Async::Task.new(reactor, &block).run
85
+ end
86
+
87
+ def schedule_task(&block)
88
+ reactor << Async::Task.new(reactor, &block).fiber
89
+ end
90
+
91
+ def interrupt!
92
+ @interrupted = true
93
+ end
94
+
95
+ def interrupted?
96
+ @interrupted
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AsyncActiveJob
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'async_active_job/adapter'
4
+ require 'async_active_job/configuration'
5
+ require 'active_job/queue_adapters/async_active_job_adapter'
6
+ require 'async_active_job/engine'
7
+
8
+ module AsyncActiveJob
9
+ module_function
10
+
11
+ # @return [AsyncActiveJob::Configuration]
12
+ def configuration
13
+ AsyncActiveJob::Configuration.instance
14
+ end
15
+
16
+ # @yield [config]
17
+ # @yieldparam config [AsyncActiveJob::Configuration]
18
+ def configure
19
+ yield configuration
20
+ end
21
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators/migration'
4
+ require 'rails/generators/active_record'
5
+
6
+ module AsyncActiveJob
7
+ class ActiveRecordGenerator < Rails::Generators::Base
8
+ include Rails::Generators::Migration
9
+
10
+ source_paths << File.join(__dir__, 'templates')
11
+
12
+ def create_migration_file
13
+ migration_template 'migration.rb.erb',
14
+ 'db/migrate/create_async_active_jobs.rb',
15
+ migration_version: migration_version
16
+ end
17
+
18
+ def self.next_migration_number(dirname)
19
+ ActiveRecord::Generators::Base.next_migration_number dirname
20
+ end
21
+
22
+ private
23
+
24
+ def migration_version
25
+ "[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]" if ActiveRecord::VERSION::MAJOR >= 5
26
+ end
27
+
28
+ def next_migration_number(dirname)
29
+ next_migration_number = current_migration_number(dirname) + 1
30
+ if ActiveRecord::Base.timestamped_migrations
31
+ [Time.now.utc.strftime('%Y%m%d%H%M%S'), format('%.14d', next_migration_number)].max
32
+ else
33
+ format('%.3d', next_migration_number)
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators/base'
4
+
5
+ class AsyncActiveJobGenerator < Rails::Generators::Base
6
+ source_paths << File.join(__dir__, 'templates')
7
+
8
+ def create_executable_file
9
+ template 'script', 'bin/async_active_job'
10
+ chmod 'bin/async_active_job', 0o755
11
+ end
12
+ end
@@ -0,0 +1,25 @@
1
+ class CreateAsyncActiveJobs < ActiveRecord::Migration<%= migration_version %>
2
+ def up
3
+ create_table :async_active_jobs do |t|
4
+ t.string :queue_name
5
+ t.integer :priority, limit: 2, default: 0, null: false
6
+ t.integer :attempts, limit: 2, default: 0, null: false
7
+ t.json :job_data, null: false
8
+ t.text :last_error
9
+ t.timestamp :run_at
10
+ t.timestamp :locked_at
11
+ t.string :locked_by
12
+ t.timestamp :failed_at
13
+ t.timestamps null: false
14
+ end
15
+
16
+ add_index :async_active_jobs, :priority, name: 'async_active_jobs_priority_idx'
17
+ add_index :async_active_jobs, :run_at, name: 'async_active_jobs_run_at_idx'
18
+ add_index :async_active_jobs, :locked_at, name: 'async_active_jobs_locked_at_idx'
19
+ add_index :async_active_jobs, :queue_name, name: 'async_active_jobs_queue_name_idx'
20
+ end
21
+
22
+ def down
23
+ drop_table :async_active_jobs
24
+ end
25
+ end
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require File.expand_path(File.join(__dir__, '../config/environment'))
5
+ require 'async_active_job/cli'
6
+
7
+ AsyncActiveJob::CLI.call(ARGV)
metadata ADDED
@@ -0,0 +1,110 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: async_active_job
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Denis Talakevich
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2021-12-17 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activejob
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: async
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: dry-cli
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.6'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.6'
55
+ description:
56
+ email:
57
+ - senid231@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - CHANGELOG.md
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - app/models/async_active_job/job.rb
71
+ - async_active_job.gemspec
72
+ - bin/console
73
+ - bin/setup
74
+ - lib/active_job/queue_adapters/async_active_job_adapter.rb
75
+ - lib/async_active_job.rb
76
+ - lib/async_active_job/adapter.rb
77
+ - lib/async_active_job/cli.rb
78
+ - lib/async_active_job/configuration.rb
79
+ - lib/async_active_job/engine.rb
80
+ - lib/async_active_job/runner.rb
81
+ - lib/async_active_job/version.rb
82
+ - lib/generators/async_active_job/active_record_generator.rb
83
+ - lib/generators/async_active_job/async_active_job_generator.rb
84
+ - lib/generators/async_active_job/templates/migration.rb.erb
85
+ - lib/generators/async_active_job/templates/script
86
+ homepage: https://github.com/senid231/async_active_job
87
+ licenses:
88
+ - MIT
89
+ metadata:
90
+ rubygems_mfa_required: 'true'
91
+ post_install_message:
92
+ rdoc_options: []
93
+ require_paths:
94
+ - lib
95
+ required_ruby_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: 2.6.0
100
+ required_rubygems_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ requirements: []
106
+ rubygems_version: 3.1.6
107
+ signing_key:
108
+ specification_version: 4
109
+ summary: Multi-fiber, Postgres-based, ActiveJob backend for Ruby on Rails
110
+ test_files: []