适用于 Active Job 的可持续执行工作流程
[!WARNING] This is the README for the new release candidate of v1, which is a major refactor from the previous release candidate of v1. If you are looking for the stable release, please refer to the v0.9.0 README.
Rails applications today frequently need to coordinate complex multi-step operations across external services, databases, and systems. While Active Job provides eventual consistency guarantees, it doesn't address the challenges of managing stateful, long-running operations that must be resilient to failures, timeouts, and partial completions. AcidicJob enhances Active Job with durable execution workflows that automatically track state and resiliently handle retries, while providing you the tools to ensure your operations are truly idempotent through careful state management and IO awareness.
With AcidicJob, you can write reliable and repeatable multi-step distributed operations that are Atomic ⚛️, Consistent , Isolated , and Durable ⛰️.
Install the gem and add to the application's Gemfile by executing:
bundle add acidic_job --version "1.0.0.rc3"If bundler is not being used to manage dependencies, install the gem by executing:
gem install acidic_job --preAfter installing the gem, run the installer:
rails generate acidic_job:installThe installer will create a migration file at db/migrate to setup the tables that the gem requires.
AcidicJob provides a simple DSL to define linear workflows within your job. In order to define and execute a workflow within a particular job, simply include AcidicJob::Workflow. This will provide the execute_workflow method to the job, which takes a unique_by keyword argument and a block where you define the steps of the workflow:
…ruby execute_workflow(unique_by: [@user, @params]) do |workflow| workflow.step :create_ride_and_audit_record, transactional: true workflow.step :create_stripe_charge workflow.step :send_receipt end
### Persisted Attributes
In addition to the workflow steps, `AcidicJob` also provides you with an isolated context where you can persist data that is needed across steps and across retries. This means that you can set an attribute in step 1, access it in step 2, have step 2 fail, have the job retry, jump directly back to step 2 on retry, and have that object still accessible. This is available via the `ctx` object, which is an instance of `AcidicJob::Context`, in all of your step methods:
```ruby
class RideCreateJob [!NOTE]
> This does mean that you are restricted to objects that can be serialized by **_`ActiveJob`_** (for more info, see [the Rails Guide on `ActiveJob`](https://edgeguides.rubyonrails.org/active_job_basics.html#supported-types-for-arguments)). This means you can persist Active Record models, and any simple Ruby data types, but you can't persist things like Procs or custom class instances, for example. `AcidicJob` does, though, extend the standard set of supported types to include Active Job instances themselves, unpersisted Active Record instances, and Ruby exceptions.
As the code sample also suggests, you should always use standard instance variables defined in your `perform` method when you have any values that your `step` methods need access to, but are present at the start of the `perform` method. You only need to persist attributes that will be set _during a step_ via `ctx`.
### Custom Workflow Uniqueness
Resilient workflows must, necessarily, be idempotent.[^2] Idempotency is a fancy word that simply means your jobs need to be able to be run multiple times while any side effects only happen once. In order for your workflow executions to be idempotent, `AcidicJob` needs to know what constitutes a unique execution of your job. You can define what makes your job unique by passing the `unique_by` argument when executing the workflow:
[^2]: This is echoed both by [Mike Perham](https://www.mikeperham.com), the creator of Sidekiq, in the Sidekiq [docs on best practices](https://github.com/mperham/sidekiq/wiki/Best-Practices#2-make-your-job-idempotent-and-transactional) by the GitLab team in their [Sidekiq Style Guide](https://docs.gitlab.com/ee/development/sidekiq/idempotent_jobs.html).
…
ruby
class Job < ActiveJob::Base
include AcidicJob::Workflow
def perform(users)
@users = users
execute_workflow(unique_by: @users) do |w|
w.step :notify_users
end
end
def notify_users
cursor = ctx[:cursor] || 0
user = @users[cursor]
return if user.nil?
UserMailer.with(user: user).welcome_email.deliver_later
ctx[:cursor] = cursor + 1
repeat_step!
end
end
…
ruby
class Job < ActiveJob::Base
include AcidicJob::Workflow
def perform(user)
@user = user
execute_workflow(unique_by: @user) do |w|
w.step :delay
w.step :send_welcome_email
end
end
def delay
enqueue(wait: 14.days)
ctx[:halt] = true
end
def send_welcome_email
if ctx[:halt]
ctx[:halt] = false
halt_workflow!
end
UserMailer.with(user: @user).welcome_email.deliver_later
end
end
…
ActiveRecord::TransactionIsolationError: cannot set transaction isolation in a nested transaction
…
ruby
require "database_cleaner/active_record"
# see https://github.com/DatabaseCleaner/database_cleaner#how-to-use
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with :truncation
# Here we are defaulting to :transaction but swapping to deletion for some specs;
# if your spec or its code-under-test uses
# nested transactions then specify :transactional e.g.:
# describe "SomeWorker", :transactional do
#
DatabaseCleaner.strategy = :transaction
config.before(:context, transactional: true) { DatabaseCleaner.strategy = :deletion }
config.after(:context, transactional: true) { DatabaseCleaner.strategy = :transaction }
config.before(:context, type: :system) { DatabaseCleaner.strategy = :deletion }
config.after(:context, type: :system) { DatabaseCleaner.strategy = :transaction }
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
end
…
sh
bundle exec rake test # Run all tests against all databases
bundle exec rake test:sqlite # Run tests against SQLite only
bundle exec rake test:mysql # Run tests against MySQL only
bundle exec rake test:postgres # Run tests against PostgreSQL only
bundle exec rake help # Show all available commands with examplesRun a specific test file or line:
bundle exec rake test:sqlite TEST=test/jobs/doing_job_test.rb
bundle exec rake test:sqlite TEST=test/jobs/doing_job_test.rb:10Run with a specific Rails version:
BUNDLE_GEMFILE=gemfiles/rails_7_1.gemfile bundle exec rake test:sqliteRun with a specific Ruby version (using ASDF or rbenv):
ASDF_RUBY_VERSION=3.2.0 bundle exec rake test
RBENV_VERSION=3.2.0 bundle exec rake testTo generate a coverage report, set the COVERAGE environment variable. This runs tests serially to ensure accurate coverage tracking:
COVERAGE=1 bundle exec rake test:sqliteThe HTML report is generated in the coverage/ directory.
To enforce minimum coverage thresholds (used in CI), also set COVERAGE_CHECK:
COVERAGE=1 COVERAGE_CHECK=1 bundle exec rake test:sqliteThis will fail if line coverage drops below 80% or branch coverage drops below 70%.
These options can be combined to help narrow down your debugging when you find a failing test in CI.
Bug reports and pull requests are welcome on GitHub at https://github.com/fractaledmind/acidic_job.
暂无开放 Issues,或尚未同步最近议题。