acidic_job 1.0.0.pre20 → 1.0.0.pre23

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: e608eefef4baffbfb2c95dcbef942a53c9ca242c4c593ddbbe0d677ef7d318da
4
- data.tar.gz: 65bed32739c1a1a860102e59dac69598c4357512034d8d3e87ed772469b9bac0
3
+ metadata.gz: 5fb0d14a9e26e9a79f4976dc74318e97c096c695dacfed5a6546dff058ca4b1b
4
+ data.tar.gz: abe13e27abaf05a1200a1bc245e649e00da1948847576df3ca1774101ca03d28
5
5
  SHA512:
6
- metadata.gz: 5a5f6155e20f929c631392f00480f57928455778e13117609457be9b8624e7f16c41661df96ae34a4045582f957b044cbdf811bfa7e187dd627b8b72b80edb90
7
- data.tar.gz: 6a663d288bd1ef3ba5cfac8e137fd496ebbca76e08573e50d706ed2570c98b6fe3148b8c9335b55313a091ccd0cc226e3b9023878dd418d400af33fd0280c1b4
6
+ metadata.gz: 1f7abb59cb78202482f82e4c9057afabf3dc687b1c723d10c2b60e8bcea3a7bb6bd4c9c6b8d835f8498076f2a75fa124baba1571e4f16093d80c6fc0228c8658
7
+ data.tar.gz: cea09574f0843c71b52c542eaeef20cd1ee330fd11a1f7c37977126d2c321ea3e055e8073b4c4ae525af17b133c3d98b50f1fa9d2ead2b93026b45897dc5945e
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- acidic_job (1.0.0.pre20)
4
+ acidic_job (1.0.0.pre23)
5
5
  activerecord
6
6
  activesupport
7
7
  database_cleaner
data/README.md CHANGED
@@ -269,6 +269,56 @@ class RideCreateJob < ActiveJob::Base
269
269
  end
270
270
  ```
271
271
 
272
+ If you need to await a job that takes arguments, you can prepare that job along with its arguments using the `with` class method that `acidic_job` will add to your jobs:
273
+
274
+ ```ruby
275
+ class RideCreateJob < ActiveJob::Base
276
+ include AcidicJob
277
+
278
+ def perform(user_id, ride_params)
279
+ @user = User.find(user_id)
280
+ @params = ride_params
281
+
282
+ with_acidity providing: { ride: nil } do
283
+ step :create_ride_and_audit_record, awaits: awaits: [SomeJob.with('argument_1', keyword: 'value')]
284
+ step :create_stripe_charge, args: [1, 2, 3], kwargs: { some: 'thing' }
285
+ step :send_receipt
286
+ end
287
+ end
288
+ end
289
+ ```
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
+
272
322
  ### Run Finished Callbacks
273
323
 
274
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.
@@ -285,7 +335,7 @@ class RideCreateJob < ActiveJob::Base
285
335
  @params = ride_params
286
336
 
287
337
  with_acidity providing: { ride: nil } do
288
- step :create_ride_and_audit_record, awaits: [SomeJob]
338
+ step :create_ride_and_audit_record, awaits: [SomeJob.with('argument_1', keyword: 'value')]
289
339
  step :create_stripe_charge, args: [1, 2, 3], kwargs: { some: 'thing' }
290
340
  step :send_receipt
291
341
  end
@@ -6,37 +6,61 @@ module AcidicJob
6
6
  module Awaiting
7
7
  extend ActiveSupport::Concern
8
8
 
9
- def enqueue_step_parallel_jobs(jobs, run, step_result)
10
- # `batch` is available from Sidekiq::Pro
11
- raise SidekiqBatchRequired unless defined?(Sidekiq::Batch)
12
-
13
- step_batch = Sidekiq::Batch.new
14
- # step_batch.description = "AcidicJob::Workflow Step: #{step}"
15
- step_batch.on(
16
- :success,
17
- "#{self.class.name}#step_done",
18
- # NOTE: options are marshalled through JSON so use only basic types.
19
- { "run_id" => run.id,
20
- "step_result_yaml" => step_result.to_yaml.strip,
21
- "parent_worker" => self.class.name,
22
- "job_names" => jobs.map(&:to_s) }
23
- )
24
-
25
- # NOTE: The jobs method is atomic.
26
- # All jobs created in the block are actually pushed atomically at the end of the block.
27
- # If an error is raised, none of the jobs will go to Redis.
28
- step_batch.jobs do
29
- jobs.each do |worker_name|
30
- # TODO: handle Symbols as well
31
- worker = worker_name.is_a?(String) ? worker_name.constantize : worker_name
32
-
33
- if worker.instance_method(:perform).arity.presence_in [0, -1]
34
- worker.perform_async
35
- elsif worker.instance_method(:perform).arity == 1
36
- worker.perform_async(run.id)
37
- else
38
- raise TooManyParametersForParallelJob
39
- end
9
+ private
10
+
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
+ # job = job_class.constantize.deserialize(serialized_staged_job)
36
+ # job.enqueue
37
+
38
+ # when a batch of jobs for a step succeeds, we begin processing the `AcidicJob::Run` record again
39
+ process_run(run)
40
+ end
41
+
42
+ def enqueue_step_parallel_jobs(jobs_or_jobs_getter, run, step_result)
43
+ awaited_jobs = case jobs_or_jobs_getter
44
+ when Array
45
+ jobs_or_jobs_getter
46
+ when Symbol, String
47
+ method(jobs_or_jobs_getter).call
48
+ end
49
+
50
+ AcidicJob::Run.transaction do
51
+ awaited_jobs.each do |awaited_job|
52
+ worker_class, args, kwargs = job_args_and_kwargs(awaited_job)
53
+
54
+ job = worker_class.new(*args, **kwargs)
55
+
56
+ AcidicJob::Run.create!(
57
+ staged: true,
58
+ awaited_by: run,
59
+ job_class: worker_class,
60
+ serialized_job: job.serialize_job(*args, **kwargs),
61
+ idempotency_key: job.idempotency_key
62
+ )
63
+ run.update(returning_to: step_result)
40
64
  end
41
65
  end
42
66
  end
@@ -53,5 +77,22 @@ module AcidicJob
53
77
  # when a batch of jobs for a step succeeds, we begin processing the `AcidicJob::Run` record again
54
78
  process_run(run)
55
79
  end
80
+
81
+ def job_args_and_kwargs(job)
82
+ case job
83
+ when Class
84
+ [job, [], {}]
85
+ when String
86
+ [job.constantize, [], {}]
87
+ when Symbol
88
+ [job.to_s.constantize, [], {}]
89
+ else
90
+ [
91
+ job.class,
92
+ job.instance_variable_get(:@__acidic_job_args),
93
+ job.instance_variable_get(:@__acidic_job_kwargs)
94
+ ]
95
+ end
96
+ end
56
97
  end
57
98
  end
@@ -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"])
@@ -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
@@ -69,7 +73,7 @@ module AcidicJob
69
73
  # base64 encoding for minimal security
70
74
  global_id = to_global_id.to_s.remove("gid://")
71
75
  encoded_global_id = Base64.encode64(global_id).strip
72
- staged_job_id = "STG_#{idempotency_key}__#{encoded_global_id}"
76
+ staged_job_id = "STG__#{idempotency_key}__#{encoded_global_id}"
73
77
 
74
78
  serialized_staged_job = if serialized_job.key?("jid")
75
79
  serialized_job.merge("jid" => staged_job_id)
@@ -7,6 +7,8 @@ module AcidicJob
7
7
  module Staging
8
8
  extend ActiveSupport::Concern
9
9
 
10
+ private
11
+
10
12
  def delete_staged_job_record
11
13
  return unless was_staged_job?
12
14
 
@@ -17,7 +19,7 @@ module AcidicJob
17
19
  end
18
20
 
19
21
  def was_staged_job?
20
- identifier.start_with? "STG_"
22
+ identifier.start_with? "STG__"
21
23
  end
22
24
 
23
25
  def staged_job_run
@@ -26,6 +28,8 @@ module AcidicJob
26
28
  staged_job_gid = "gid://#{Base64.decode64(encoded_global_id)}"
27
29
 
28
30
  GlobalID::Locator.locate(staged_job_gid)
31
+ rescue ActiveRecord::RecordNotFound
32
+ nil
29
33
  end
30
34
 
31
35
  def identifier
@@ -33,7 +37,9 @@ module AcidicJob
33
37
  return job_id if defined?(job_id) && !job_id.nil?
34
38
 
35
39
  # might be defined already in `with_acidity` method
36
- @__acidic_job_idempotency_key ||= IdempotencyKey.value_for(self, @__acidic_job_args, @__acidic_job_kwargs)
40
+ acidic_identifier = self.class.acidic_identifier
41
+ @__acidic_job_idempotency_key ||= IdempotencyKey.new(acidic_identifier)
42
+ .value_for(self, *@__acidic_job_args, **@__acidic_job_kwargs)
37
43
 
38
44
  @__acidic_job_idempotency_key
39
45
  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.pre20"
4
+ VERSION = "1.0.0.pre23"
5
5
  end
data/lib/acidic_job.rb CHANGED
@@ -48,8 +48,15 @@ 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? }
53
+ klass.set_callback :perform, :after, :delete_staged_job_record,
54
+ if: -> { was_staged_job? && !was_awaited_job? }
52
55
  klass.define_callbacks :finish
56
+ klass.set_callback :finish, :after, :reenqueue_awaited_by_job,
57
+ if: -> { was_workflow_job? && was_awaited_job? }
58
+ klass.set_callback :finish, :after, :delete_staged_job_record,
59
+ if: -> { was_workflow_job? && was_staged_job? && !was_awaited_job? }
53
60
 
54
61
  klass.instance_variable_set(:@acidic_identifier, :job_id)
55
62
  klass.define_singleton_method(:acidic_by_job_id) { @acidic_identifier = :job_id }
@@ -68,6 +75,10 @@ module AcidicJob
68
75
  super
69
76
  end
70
77
 
78
+ def with(*args, **kwargs)
79
+ new(*args, **kwargs)
80
+ end
81
+
71
82
  def acidic_identifier
72
83
  @acidic_identifier
73
84
  end
@@ -79,11 +90,11 @@ module AcidicJob
79
90
  @__acidic_job_args = args
80
91
  @__acidic_job_kwargs = kwargs
81
92
 
82
- if method(__method__).super_method.arity.zero?
83
- super()
84
- else
85
- super(*args, **kwargs)
86
- end
93
+ super(*args, **kwargs)
94
+ rescue ArgumentError => e
95
+ raise e unless e.message.include?("wrong number of arguments")
96
+
97
+ super()
87
98
  end
88
99
 
89
100
  def with_acidity(providing: {})
@@ -129,9 +140,13 @@ module AcidicJob
129
140
 
130
141
  private
131
142
 
143
+ def was_workflow_job?
144
+ defined?(@acidic_job_run) && @acidic_job_run.present?
145
+ end
146
+
132
147
  def process_run(run)
133
148
  # if the run record is already marked as finished, immediately return its result
134
- return finish_run(run) if run.finished?
149
+ return run.succeeded? if run.finished?
135
150
 
136
151
  # otherwise, we will enter a loop to process each step of the workflow
137
152
  loop do
@@ -144,7 +159,7 @@ module AcidicJob
144
159
  break
145
160
  elsif current_step.nil?
146
161
  raise UnknownRecoveryPoint, "Defined workflow does not reference this step: #{recovery_point}"
147
- elsif (jobs = current_step.fetch("awaits", [])).any?
162
+ elsif !(jobs = current_step.fetch("awaits", []) || []).empty?
148
163
  step = Step.new(current_step, run, self)
149
164
  # Only execute the current step, without yet progressing the recovery_point to the next step.
150
165
  # This ensures that any failures in parallel jobs will have this step retried in the main workflow
@@ -170,13 +185,7 @@ module AcidicJob
170
185
  end
171
186
 
172
187
  # the loop will break once the job is finished, so simply report the status
173
- finish_run(run)
174
- end
175
-
176
- def finish_run(run)
177
- run_callbacks :finish do
178
- run.succeeded?
179
- end
188
+ run.succeeded?
180
189
  end
181
190
 
182
191
  def step(method_name, awaits: [], for_each: nil)
@@ -219,9 +228,7 @@ module AcidicJob
219
228
  if run.present?
220
229
  # Programs enqueuing multiple jobs with different parameters but the
221
230
  # same idempotency key is a bug.
222
- # NOTE: WOULD THE ENQUEUED_AT OR CREATED_AT FIELD BE NECESSARILY DIFFERENT?
223
- if run.serialized_job.except("jid", "job_id",
224
- "enqueued_at") != serialized_job.except("jid", "job_id", "enqueued_at")
231
+ if run.serialized_job.slice("args", "arguments") != serialized_job.slice("args", "arguments")
225
232
  raise MismatchedIdempotencyKeyAndJobArguments
226
233
  end
227
234
 
@@ -230,7 +237,14 @@ module AcidicJob
230
237
  raise LockedIdempotencyKey if run.locked_at && run.locked_at > Time.current - IDEMPOTENCY_KEY_LOCK_TIMEOUT
231
238
 
232
239
  # Lock the run and update latest run unless the job is already finished.
233
- run.update!(last_run_at: Time.current, locked_at: Time.current, workflow: workflow) unless run.finished?
240
+ unless run.finished?
241
+ run.update!(
242
+ last_run_at: Time.current,
243
+ locked_at: Time.current,
244
+ workflow: workflow,
245
+ recovery_point: run.recovery_point || workflow.first.first
246
+ )
247
+ end
234
248
  else
235
249
  run = Run.create!(
236
250
  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.pre20
4
+ version: 1.0.0.pre23
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-16 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