acidic_job 1.0.0.pre21 → 1.0.0.pre24

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f47391c0a8bdb8c62c967d716d0190eeddc5ebdd28af81309ffea17ae58f52b2
4
- data.tar.gz: 575abae7eb9f70a81537b3260fa8a5ac76d64c231936f0f8e4d96b9e4be116d7
3
+ metadata.gz: 223aa8cad5d48e2a4fc04a9e33f82bdf7ef54cb933c2e14f3dc0aa6d46986932
4
+ data.tar.gz: a8a646da8f9e5987267f1448e44056bdd37c2d4f8cbfbc84650659555567b635
5
5
  SHA512:
6
- metadata.gz: 6d325fad1fb3240a6cf56d5b8d683b4bf4a0ab8b44c68173141d96fc7ca23a4c8d9f9fcf36d3410ed74f6dec9c16ef4739a642bb09e106050f1a21bc473e3a82
7
- data.tar.gz: 355057c6f50d2b37a1b5837247d0d54b9e40e9fedc5793115a607bf9c03353e9ae5f847624608778ee54bdc1bfb950888c33b5ff6db96cb42f83001582571377
6
+ metadata.gz: 857647ff5cce856d41a8e30014005ef035cefcca383a719e6e679a4fc7bdc254c76f65e2d312c508ad56fd45b1e33ed533aecf2541e13b0480c579e0127ec338
7
+ data.tar.gz: 4208fa26057e5a1fb0908c554b8e2ef74c6a5018a4d782815caa1fbd7716f18b33598ff6877e3c0c583f449099438d316c506dee6fa84afea34d54aa42f085b8
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- acidic_job (1.0.0.pre21)
4
+ acidic_job (1.0.0.pre24)
5
5
  activerecord
6
6
  activesupport
7
7
  database_cleaner
data/README.md CHANGED
@@ -280,7 +280,7 @@ class RideCreateJob < ActiveJob::Base
280
280
  @params = ride_params
281
281
 
282
282
  with_acidity providing: { ride: nil } do
283
- step :create_ride_and_audit_record, awaits: [SomeJob]
283
+ step :create_ride_and_audit_record, awaits: awaits: [SomeJob.with('argument_1', keyword: 'value')]
284
284
  step :create_stripe_charge, args: [1, 2, 3], kwargs: { some: 'thing' }
285
285
  step :send_receipt
286
286
  end
@@ -288,6 +288,37 @@ class RideCreateJob < ActiveJob::Base
288
288
  end
289
289
  ```
290
290
 
291
+ You can also await a batch of jobs by simply passing multiple jobs to the `awaits` array (e.g. `awaits: [SomeJob, AnotherJob.with('argument_1', keyword: 'value')]`). Your top level workflow job will only continue to the next step once all of the jobs in your `awaits` array have successfully finished.
292
+
293
+ In some cases, you may need to _dynamically_ determine the collection of jobs that the step should wait for; in these cases, you can pass the name of a method to the `awaits` option:
294
+
295
+ ```ruby
296
+ class RideCreateJob < ActiveJob::Base
297
+ include AcidicJob
298
+ set_callback :finish, :after, :delete_run_record
299
+
300
+ def perform(user_id, ride_params)
301
+ @user = User.find(user_id)
302
+ @params = ride_params
303
+
304
+ with_acidity providing: { ride: nil } do
305
+ step :create_ride_and_audit_record, awaits: :dynamic_awaits
306
+ step :create_stripe_charge, args: [1, 2, 3], kwargs: { some: 'thing' }
307
+ step :send_receipt
308
+ end
309
+ end
310
+
311
+ def dynamic_awaits
312
+ if @params["key"].present?
313
+ [SomeJob.with('argument_1', keyword: 'value')]
314
+ else
315
+ [AnotherJob]
316
+ end
317
+ end
318
+ end
319
+ ```
320
+
321
+
291
322
  ### Run Finished Callbacks
292
323
 
293
324
  When working with workflow jobs that make use of the `awaits` feature for a step, it is important to remember that the `after_perform` callback will be called _as soon as the first `awaits` step has enqueued job_, and **not** when the entire job run has finished. `acidic_job` allows the `perform` method to finish so that the queue for the workflow job is cleared to pick up new work while the `awaits` jobs are running. `acidic_job` will automatically re-enqueue the workflow job and progress to the next step when all of the `awaits` jobs have successfully finished. However, this means that `after_perform` **is not necessarily** the same as `after_finish`. In order to provide the opportunity for you to execute callback logic _if and only if_ a job run has finished, we provide callback hooks for the `finish` event.
@@ -318,8 +349,6 @@ class RideCreateJob < ActiveJob::Base
318
349
  end
319
350
  ```
320
351
 
321
- You can also await a batch of jobs by simply passing multiple jobs to the `awaits` array (e.g. `awaits: [SomeJob, AnotherJob.with('argument_1', keyword: 'value')]`). Your top level workflow job will only continue to the next step once all of the jobs in your `awaits` array have successfully finished.
322
-
323
352
  ## Testing
324
353
 
325
354
  When testing acidic jobs, you are likely to run into `ActiveRecord::TransactionIsolationError`s:
@@ -8,32 +8,58 @@ module AcidicJob
8
8
 
9
9
  private
10
10
 
11
- def enqueue_step_parallel_jobs(jobs, run, step_result)
12
- # `batch` is available from Sidekiq::Pro
13
- raise SidekiqBatchRequired unless defined?(Sidekiq::Batch)
14
-
15
- step_batch = Sidekiq::Batch.new
16
- # step_batch.description = "AcidicJob::Workflow Step: #{step}"
17
- step_batch.on(
18
- :success,
19
- "#{self.class.name}#step_done",
20
- # NOTE: options are marshalled through JSON so use only basic types.
21
- {
22
- "run_id" => run.id,
23
- "step_result_yaml" => step_result.to_yaml.strip,
24
- "parent_worker" => self.class.name,
25
- "job_names" => jobs.map { |job| job_name(job) }
26
- }
27
- )
28
-
29
- # NOTE: The jobs method is atomic.
30
- # All jobs created in the block are actually pushed atomically at the end of the block.
31
- # If an error is raised, none of the jobs will go to Redis.
32
- step_batch.jobs do
33
- jobs.each do |job|
34
- worker, args, kwargs = job_args_and_kwargs(job)
35
-
36
- worker.perform_async(*args, **kwargs)
11
+ def was_awaited_job?
12
+ (acidic_job_run.present? && acidic_job_run.awaited_by.present?) ||
13
+ (staged_job_run.present? && staged_job_run.awaited_by.present?)
14
+ end
15
+
16
+ def reenqueue_awaited_by_job
17
+ run = staged_job_run&.awaited_by || acidic_job_run&.awaited_by
18
+
19
+ return unless run
20
+
21
+ current_step = run.workflow[run.recovery_point.to_s]
22
+ step_result = run.returning_to
23
+
24
+ job = run.job_class.constantize.deserialize(run.serialized_job)
25
+ # this needs to be explicitly set so that `was_workflow_job?` appropriately returns `true`
26
+ # which is what the `after_finish :reenqueue_awaited_by_job` check needs
27
+ job.instance_variable_set(:@acidic_job_run, run)
28
+
29
+ step = Step.new(current_step, run, job, step_result)
30
+ # TODO: WRITE REGRESSION TESTS FOR PARALLEL JOB FAILING AND RETRYING THE ORIGINAL STEP
31
+ step.progress
32
+
33
+ return if run.finished?
34
+
35
+ # when a batch of jobs for a step succeeds, we begin processing the `AcidicJob::Run` record again
36
+ # process_run(run)
37
+ run.update_column(:locked_at, nil)
38
+ job.enqueue
39
+ end
40
+
41
+ def enqueue_step_parallel_jobs(jobs_or_jobs_getter, run, step_result)
42
+ awaited_jobs = case jobs_or_jobs_getter
43
+ when Array
44
+ jobs_or_jobs_getter
45
+ when Symbol, String
46
+ method(jobs_or_jobs_getter).call
47
+ end
48
+
49
+ AcidicJob::Run.transaction do
50
+ awaited_jobs.each do |awaited_job|
51
+ worker_class, args, kwargs = job_args_and_kwargs(awaited_job)
52
+
53
+ job = worker_class.new(*args, **kwargs)
54
+
55
+ AcidicJob::Run.create!(
56
+ staged: true,
57
+ awaited_by: run,
58
+ job_class: worker_class,
59
+ serialized_job: job.serialize_job(*args, **kwargs),
60
+ idempotency_key: job.idempotency_key
61
+ )
62
+ run.update(returning_to: step_result)
37
63
  end
38
64
  end
39
65
  end
@@ -51,17 +77,6 @@ module AcidicJob
51
77
  process_run(run)
52
78
  end
53
79
 
54
- def job_name(job)
55
- case job
56
- when Class, Symbol
57
- job.to_s
58
- when String
59
- job
60
- else
61
- job.class.name
62
- end
63
- end
64
-
65
80
  def job_args_and_kwargs(job)
66
81
  case job
67
82
  when Class
@@ -13,7 +13,11 @@ module AcidicJob
13
13
  class_methods do
14
14
  # called only from `AcidicJob::Run#enqueue_staged_job`
15
15
  def deserialize(serialized_job_hash)
16
- klass = serialized_job_hash["class"].constantize
16
+ klass = if serialized_job_hash["class"].is_a?(Class)
17
+ serialized_job_hash["class"]
18
+ else
19
+ serialized_job_hash["class"].constantize
20
+ end
17
21
  worker = klass.new
18
22
  worker.jid = serialized_job_hash["jid"]
19
23
  worker.instance_variable_set(:@args, serialized_job_hash["args"])
@@ -54,7 +58,7 @@ module AcidicJob
54
58
  ::Sidekiq::Client.push(
55
59
  "class" => self.class,
56
60
  "args" => @args,
57
- "jid" => @jid
61
+ "jid" => @acidic_job_run&.staged_job_id || @jid
58
62
  )
59
63
  end
60
64
  end
@@ -20,7 +20,15 @@ module AcidicJob
20
20
  end
21
21
  end
22
22
 
23
- value || value_from_job_args(hash_or_job, *args, **kwargs)
23
+ result = value || value_from_job_args(hash_or_job, *args, **kwargs)
24
+
25
+ if result.start_with?("STG__")
26
+ # "STG__#{idempotency_key}__#{encoded_global_id}"
27
+ _prefix, idempotency_key, _encoded_global_id = result.split("__")
28
+ idempotency_key
29
+ else
30
+ result
31
+ end
24
32
  end
25
33
 
26
34
  private
@@ -12,11 +12,15 @@ module AcidicJob
12
12
 
13
13
  self.table_name = "acidic_job_runs"
14
14
 
15
+ belongs_to :awaited_by, class_name: "AcidicJob::Run", optional: true
16
+ has_many :batched_runs, class_name: "AcidicJob::Run", foreign_key: "awaited_by_id"
17
+
15
18
  after_create_commit :enqueue_staged_job, if: :staged?
16
19
 
17
20
  serialize :error_object
18
21
  serialize :serialized_job
19
22
  serialize :workflow
23
+ serialize :returning_to
20
24
  store :attr_accessors
21
25
 
22
26
  validates :staged, inclusion: { in: [true, false] } # uses database default
@@ -60,16 +64,19 @@ module AcidicJob
60
64
  error_object.present?
61
65
  end
62
66
 
63
- private
64
-
65
- def enqueue_staged_job
66
- return unless staged?
67
-
67
+ def staged_job_id
68
68
  # encode the identifier for this record in the job ID
69
69
  # base64 encoding for minimal security
70
70
  global_id = to_global_id.to_s.remove("gid://")
71
71
  encoded_global_id = Base64.encode64(global_id).strip
72
- staged_job_id = "STG_#{idempotency_key}__#{encoded_global_id}"
72
+
73
+ "STG__#{idempotency_key}__#{encoded_global_id}"
74
+ end
75
+
76
+ private
77
+
78
+ def enqueue_staged_job
79
+ return unless staged?
73
80
 
74
81
  serialized_staged_job = if serialized_job.key?("jid")
75
82
  serialized_job.merge("jid" => staged_job_id)
@@ -7,17 +7,10 @@ module AcidicJob
7
7
  module Staging
8
8
  extend ActiveSupport::Concern
9
9
 
10
- def delete_staged_job_record
11
- return unless was_staged_job?
12
-
13
- staged_job_run.delete
14
- true
15
- rescue ActiveRecord::RecordNotFound
16
- true
17
- end
10
+ private
18
11
 
19
12
  def was_staged_job?
20
- identifier.start_with? "STG_"
13
+ identifier.start_with? "STG__"
21
14
  end
22
15
 
23
16
  def staged_job_run
@@ -26,6 +19,8 @@ module AcidicJob
26
19
  staged_job_gid = "gid://#{Base64.decode64(encoded_global_id)}"
27
20
 
28
21
  GlobalID::Locator.locate(staged_job_gid)
22
+ rescue ActiveRecord::RecordNotFound
23
+ nil
29
24
  end
30
25
 
31
26
  def identifier
@@ -33,7 +28,9 @@ module AcidicJob
33
28
  return job_id if defined?(job_id) && !job_id.nil?
34
29
 
35
30
  # might be defined already in `with_acidity` method
36
- @__acidic_job_idempotency_key ||= IdempotencyKey.value_for(self, @__acidic_job_args, @__acidic_job_kwargs)
31
+ acidic_identifier = self.class.acidic_identifier
32
+ @__acidic_job_idempotency_key ||= IdempotencyKey.new(acidic_identifier)
33
+ .value_for(self, *@__acidic_job_args, **@__acidic_job_kwargs)
37
34
 
38
35
  @__acidic_job_idempotency_key
39
36
  end
@@ -42,7 +42,13 @@ module AcidicJob
42
42
  # The progression phase advances the job run state machine onto the next step
43
43
  def progress
44
44
  @run.with_lock do
45
- @step_result.call(run: @run)
45
+ if @step_result.is_a?(FinishedPoint)
46
+ @job.run_callbacks :finish do
47
+ @step_result.call(run: @run)
48
+ end
49
+ else
50
+ @step_result.call(run: @run)
51
+ end
46
52
  end
47
53
  end
48
54
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AcidicJob
4
- VERSION = "1.0.0.pre21"
4
+ VERSION = "1.0.0.pre24"
5
5
  end
data/lib/acidic_job.rb CHANGED
@@ -48,8 +48,11 @@ module AcidicJob
48
48
  end
49
49
 
50
50
  # TODO: write test for a staged job that uses awaits
51
- klass.set_callback :perform, :after, :delete_staged_job_record, if: :was_staged_job?
51
+ klass.set_callback :perform, :after, :reenqueue_awaited_by_job,
52
+ if: -> { was_awaited_job? && !was_workflow_job? }
52
53
  klass.define_callbacks :finish
54
+ klass.set_callback :finish, :after, :reenqueue_awaited_by_job,
55
+ if: -> { was_workflow_job? && was_awaited_job? }
53
56
 
54
57
  klass.instance_variable_set(:@acidic_identifier, :job_id)
55
58
  klass.define_singleton_method(:acidic_by_job_id) { @acidic_identifier = :job_id }
@@ -133,9 +136,13 @@ module AcidicJob
133
136
 
134
137
  private
135
138
 
139
+ def was_workflow_job?
140
+ defined?(@acidic_job_run) && @acidic_job_run.present?
141
+ end
142
+
136
143
  def process_run(run)
137
144
  # if the run record is already marked as finished, immediately return its result
138
- return finish_run(run) if run.finished?
145
+ return run.succeeded? if run.finished?
139
146
 
140
147
  # otherwise, we will enter a loop to process each step of the workflow
141
148
  loop do
@@ -148,7 +155,7 @@ module AcidicJob
148
155
  break
149
156
  elsif current_step.nil?
150
157
  raise UnknownRecoveryPoint, "Defined workflow does not reference this step: #{recovery_point}"
151
- elsif (jobs = current_step.fetch("awaits", [])).any?
158
+ elsif !(jobs = current_step.fetch("awaits", []) || []).empty?
152
159
  step = Step.new(current_step, run, self)
153
160
  # Only execute the current step, without yet progressing the recovery_point to the next step.
154
161
  # This ensures that any failures in parallel jobs will have this step retried in the main workflow
@@ -174,13 +181,7 @@ module AcidicJob
174
181
  end
175
182
 
176
183
  # the loop will break once the job is finished, so simply report the status
177
- finish_run(run)
178
- end
179
-
180
- def finish_run(run)
181
- run_callbacks :finish do
182
- run.succeeded?
183
- end
184
+ run.succeeded?
184
185
  end
185
186
 
186
187
  def step(method_name, awaits: [], for_each: nil)
@@ -223,9 +224,7 @@ module AcidicJob
223
224
  if run.present?
224
225
  # Programs enqueuing multiple jobs with different parameters but the
225
226
  # same idempotency key is a bug.
226
- # NOTE: WOULD THE ENQUEUED_AT OR CREATED_AT FIELD BE NECESSARILY DIFFERENT?
227
- if run.serialized_job.except("jid", "job_id",
228
- "enqueued_at") != serialized_job.except("jid", "job_id", "enqueued_at")
227
+ if run.serialized_job.slice("args", "arguments") != serialized_job.slice("args", "arguments")
229
228
  raise MismatchedIdempotencyKeyAndJobArguments
230
229
  end
231
230
 
@@ -234,7 +233,14 @@ module AcidicJob
234
233
  raise LockedIdempotencyKey if run.locked_at && run.locked_at > Time.current - IDEMPOTENCY_KEY_LOCK_TIMEOUT
235
234
 
236
235
  # Lock the run and update latest run unless the job is already finished.
237
- run.update!(last_run_at: Time.current, locked_at: Time.current, workflow: workflow) unless run.finished?
236
+ unless run.finished?
237
+ run.update!(
238
+ last_run_at: Time.current,
239
+ locked_at: Time.current,
240
+ workflow: workflow,
241
+ recovery_point: run.recovery_point || workflow.first.first
242
+ )
243
+ end
238
244
  else
239
245
  run = Run.create!(
240
246
  staged: false,
@@ -1,19 +1,19 @@
1
1
  class <%= migration_class_name %> < ActiveRecord::Migration<%= migration_version %>
2
2
  def change
3
3
  create_table :acidic_job_runs do |t|
4
- t.boolean :staged, null: false, default: -> { false }
5
- t.string :idempotency_key, null: false
6
- t.text :serialized_job, null: false
7
- t.string :job_class, null: false
8
- t.datetime :last_run_at, null: true, default: -> { "CURRENT_TIMESTAMP" }
9
- t.datetime :locked_at, null: true
10
- t.string :recovery_point, null: true
11
- t.text :error_object, null: true
12
- t.text :attr_accessors, null: true
13
- t.text :workflow, null: true
4
+ t.boolean :staged, null: false, default: -> { false }
5
+ t.string :idempotency_key, null: false, index: { unique: true }
6
+ t.text :serialized_job, null: false
7
+ t.string :job_class, null: false
8
+ t.datetime :last_run_at, null: true, default: -> { "CURRENT_TIMESTAMP" }
9
+ t.datetime :locked_at, null: true
10
+ t.string :recovery_point, null: true
11
+ t.text :error_object, null: true
12
+ t.text :attr_accessors, null: true
13
+ t.text :workflow, null: true
14
+ t.references :awaited_by, null: true, index: true
15
+ t.text :returning_to, null: true
14
16
  t.timestamps
15
-
16
- t.index :idempotency_key, unique: true
17
17
  end
18
18
  end
19
19
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: acidic_job
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0.pre21
4
+ version: 1.0.0.pre24
5
5
  platform: ruby
6
6
  authors:
7
7
  - fractaledmind
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2022-05-17 00:00:00.000000000 Z
11
+ date: 2022-05-26 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activerecord