Class: ActiveSaga::Stores::ActiveRecord

Inherits:
Base
  • Object
show all
Defined in:
lib/active_saga/stores/active_record.rb

Overview

ActiveRecord-backed persistence implementation.

Defined Under Namespace

Modules: Models Classes: Processor

Constant Summary collapse

TERMINAL_STATES =
%w[completed failed cancelled timed_out].freeze

Instance Attribute Summary

Attributes inherited from Base

#clock, #logger, #serializer

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from ActiveSaga::Stores::Base

Instance Method Details

#advance_cursor(execution, step) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/active_saga/stores/active_record.rb', line 352

def advance_cursor(execution, step)
  next_step = execution.steps.ordered.where("position > ?", step.position).first
  if next_step
    execution.update!(
      cursor_step: next_step.name,
      state: next_step.waiting? ? "waiting" : "running"
    )
  else
    execution.update!(
      cursor_step: nil,
      state: "completed",
      completed_at: clock.call
    )
    ActiveSupport::Notifications.instrument("active_saga.execution.completed",
      execution_id: execution.id,
      workflow: execution.workflow_class)
  end
end

#apply_signal_handler(execution, name, payload) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
# File 'lib/active_saga/stores/active_record.rb', line 340

def apply_signal_handler(execution, name, payload)
  workflow_class = execution.workflow_class.constantize
  handler = workflow_class.signal_handler_for(name)
  return unless handler

  ctx = context_from(execution)
  workflow = workflow_class.new(context: ctx, execution_id: execution.id)

  workflow.send(handler, payload)
  persist_context(execution, workflow.ctx)
end

#build_execution(record) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/active_saga/stores/active_record.rb', line 322

def build_execution(record)
  ActiveSaga::Execution.new(
    id: record.id,
    workflow_class: record.workflow_class,
    state: record.state,
    ctx: serializer.load(record.ctx),
    cursor_step: record.cursor_step&.to_sym,
    created_at: record.created_at,
    updated_at: record.updated_at,
    cancelled_at: record.cancelled_at,
    store: self
  )
end

#cancel_execution!(execution_id, reason: nil) ⇒ Object



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/active_saga/stores/active_record.rb', line 289

def cancel_execution!(execution_id, reason: nil)
  with_execution_lock(execution_id) do |execution|
    return build_execution(execution) if TERMINAL_STATES.include?(execution.state)

    completed_upto = execution.steps.where(state: %w[completed compensated failed timed_out]).maximum(:position)
    run_compensations!(execution, upto: completed_upto)
    cancel_remaining_steps(execution, upto: completed_upto)

    execution.update!(
      state: "cancelled",
      cursor_step: nil,
      last_error_class: nil,
      last_error_message: nil,
      cancelled_at: clock.call
    )

    ActiveSupport::Notifications.instrument("active_saga.execution.cancelled",
      execution_id: execution.id,
      workflow: execution.workflow_class,
      reason: reason)

    build_execution(execution)
  end
end

#complete_step!(execution_id, step_name, payload:, idempotency_key: nil) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/active_saga/stores/active_record.rb', line 182

def complete_step!(execution_id, step_name, payload:, idempotency_key: nil)
  with_execution_lock(execution_id) do |execution|
    step = execution.steps.lock.find_by(name: step_name.to_s)
    if step&.completed? && idempotency_key && step.completion_idempotency_key == idempotency_key
      return build_execution(execution)
    end

    raise ActiveSaga::Errors::StepNotWaiting, "Step #{step_name} is not waiting" unless step&.waiting?

    if idempotency_key && step.completion_idempotency_key.present? && step.completion_idempotency_key != idempotency_key
      raise ActiveSaga::Errors::AsyncCompletionConflict, "Completion idempotency mismatch"
    end

    return build_execution(execution) if step.completion_idempotency_key.present? && step.completion_idempotency_key == idempotency_key

    definition = step_definition(execution, step)
    ctx = context_from(execution)

    unless definition.options[:fire_and_forget]
      store_keys = [definition.name.to_sym]
      store_result = definition.options[:store_result_as]&.to_sym
      store_keys << store_result if store_result && store_result != definition.name.to_sym

      store_keys.each do |key|
        ctx[key] = payload unless payload.nil?
      end
    end

    step.update!(
      state: "completed",
      completion_payload: payload,
      completion_idempotency_key: idempotency_key,
      waiting_since: nil,
      timeout_at: nil,
      completed_at: clock.call
    )

    ActiveSupport::Notifications.instrument("active_saga.step.completed_async",
      execution_id: execution.id,
      step: step.name,
      workflow: execution.workflow_class)

    persist_context(execution, ctx)
    advance_cursor(execution, step)
    enqueue_runner(execution, step_name: execution.cursor_step)
  end
end

#context_from(execution) ⇒ Object



314
315
316
# File 'lib/active_saga/stores/active_record.rb', line 314

def context_from(execution)
  ActiveSaga::Context.new(serializer.load(execution.ctx))
end

#enqueue_runner(execution, step_name: nil, run_at: nil) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/active_saga/stores/active_record.rb', line 154

def enqueue_runner(execution, step_name: nil, run_at: nil)
  return if execution.nil?

  options = {}
  options[:wait_until] = run_at if run_at
  queue = queue_for_execution(execution, step_name)
  options[:queue] = queue if queue

  job = ActiveSaga::Jobs::RunnerJob
  job = job.set(options) if options.any?
  job.perform_later(execution.id)
end

#events_for(execution_id) ⇒ Object



148
149
150
151
152
# File 'lib/active_saga/stores/active_record.rb', line 148

def events_for(execution_id)
  Models::Event.where(execution_id: execution_id).order(:created_at).map do |event|
    event.attributes.deep_symbolize_keys
  end
end

#executions(limit: 100, offset: 0, workflow_class: nil, state: nil, order: :desc) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/active_saga/stores/active_record.rb', line 130

def executions(limit: 100, offset: 0, workflow_class: nil, state: nil, order: :desc)
  scope = Models::Execution.order(created_at: order == :asc ? :asc : :desc)
  if workflow_class
    name = workflow_class.is_a?(Class) ? workflow_class.name : workflow_class.to_s
    scope = scope.where(workflow_class: name)
  end
  scope = scope.where(state:) if state
  scope = scope.offset(offset) if offset&.positive?
  scope = scope.limit(limit) if limit
  scope.map { |record| build_execution(record) }
end

#extend_timeout!(execution_id, step_name, by:) ⇒ Object



255
256
257
258
259
260
261
262
# File 'lib/active_saga/stores/active_record.rb', line 255

def extend_timeout!(execution_id, step_name, by:)
  with_execution_lock(execution_id) do |execution|
    step = execution.steps.lock.find_by(name: step_name.to_s)
    return unless step&.waiting?

    step.update!(timeout_at: step.timeout_at && step.timeout_at + by)
  end
end

#fail_step!(execution_id, step_name, error_class:, message:, details:, idempotency_key: nil) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/active_saga/stores/active_record.rb', line 230

def fail_step!(execution_id, step_name, error_class:, message:, details:, idempotency_key: nil)
  with_execution_lock(execution_id) do |execution|
    step = execution.steps.lock.find_by(name: step_name.to_s)
    raise ActiveSaga::Errors::StepNotWaiting, "Step #{step_name} is not waiting" unless step&.waiting?

    definition = step_definition(execution, step)
    current_attempts = step.attempts.to_i
    record_failure!(execution, step,
      error_class:,
      message:,
      details: details || {},
      attempts: current_attempts,
      async: true)

    ActiveSupport::Notifications.instrument("active_saga.step.failed_async",
      execution_id: execution.id,
      step: step.name,
      workflow: execution.workflow_class,
      error_class: error_class,
      message: message)

    schedule_retry_or_fail!(execution, step, definition)
  end
end

#heartbeat!(execution_id, step_name, at: clock.call) ⇒ Object



264
265
266
267
268
269
270
271
# File 'lib/active_saga/stores/active_record.rb', line 264

def heartbeat!(execution_id, step_name, at: clock.call)
  with_execution_lock(execution_id) do |execution|
    step = execution.steps.lock.find_by(name: step_name.to_s)
    return unless step&.waiting?

    step.update!(last_heartbeat_at: at)
  end
end

#load_execution(id) ⇒ Object



125
126
127
128
# File 'lib/active_saga/stores/active_record.rb', line 125

def load_execution(id)
  record = Models::Execution.find_by(id:)
  build_execution(record) if record
end

#persist_context(execution, ctx) ⇒ Object



318
319
320
# File 'lib/active_saga/stores/active_record.rb', line 318

def persist_context(execution, ctx)
  execution.update!(ctx: serializer.dump(ctx.to_h))
end

#process_execution(execution_id) ⇒ Object



176
177
178
179
180
# File 'lib/active_saga/stores/active_record.rb', line 176

def process_execution(execution_id)
  with_execution_lock(execution_id) do |execution|
    Processor.new(self, execution).process!
  end
end

#record_failure!(execution, step, error_class:, message:, details:, attempts:, async: false) ⇒ Object



371
372
373
374
375
376
377
378
379
380
381
# File 'lib/active_saga/stores/active_record.rb', line 371

def record_failure!(execution, step, error_class:, message:, details:, attempts:, async: false)
  step.update!(
    state: async ? "failed" : "failed",
    last_error_class: error_class,
    last_error_message: message,
    last_error_details: details,
    attempts: attempts,
    last_error_at: clock.call
  )
  execution.update!(state: "failed", last_error_class: error_class, last_error_message: message)
end

#schedule_retry_or_fail!(execution, step, definition) ⇒ Object



383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/active_saga/stores/active_record.rb', line 383

def schedule_retry_or_fail!(execution, step, definition)
  retry_config = (definition.options[:retry] || {}).deep_symbolize_keys

  return transition_to_failed!(execution, step) if retry_config.empty?

  current_attempts = step.attempts.to_i
  max_attempts = retry_config[:max] || Float::INFINITY

  if current_attempts < max_attempts
    retry_index = [current_attempts, 1].max
    delay = ActiveSaga::Backoff.calculate(retry_config, attempts: retry_index)
    scheduled_at = clock.call + delay

    step.update!(state: "pending", attempts: current_attempts, scheduled_at: scheduled_at)
    execution.update!(state: "running", cursor_step: definition.name)

    ActiveSupport::Notifications.instrument("active_saga.retry.scheduled",
      execution_id: execution.id,
      workflow: execution.workflow_class,
      step: step.name,
      attempts: current_attempts + 1,
      wait: delay)

    enqueue_runner(execution, step_name: step.name, run_at: scheduled_at)
  else
    transition_to_failed!(execution, step)
  end
end

#serializable_step_options(options) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/active_saga/stores/active_record.rb', line 106

def serializable_step_options(options)
  return {} unless options.is_a?(Hash)

  options.each_with_object({}) do |(key, value), hash|
    hash[key.to_s] = case value
    when Proc, Method
      nil
    when Hash
      serializable_step_options(value)
    when Array
      value.map { |item| item.is_a?(Hash) ? serializable_step_options(item) : item }
    when Symbol, String, Numeric, TrueClass, FalseClass, NilClass
      value
    else
      value.respond_to?(:name) ? value.name : value.to_s
    end
  end.compact
end

#signal!(execution_id, name, payload: nil) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/active_saga/stores/active_record.rb', line 273

def signal!(execution_id, name, payload: nil)
  with_execution_lock(execution_id) do |execution|
    Models::Event.create!(execution:, name: name.to_s, payload: payload)

    ActiveSupport::Notifications.instrument("active_saga.signal.received",
      execution_id: execution.id,
      signal: name)

    apply_signal_handler(execution, name, payload)

    if execution.steps.where(name: name.to_s, state: "waiting").exists?
      enqueue_runner(execution, step_name: name)
    end
  end
end

#start_execution(workflow_class:, context:, steps:, idempotency_key:, timeout:, metadata: {}) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/active_saga/stores/active_record.rb', line 61

def start_execution(workflow_class:, context:, steps:, idempotency_key:, timeout:, metadata: {})
  now = clock.call
  record = nil

  ::ActiveRecord::Base.transaction do
    if idempotency_key
      existing = Models::Execution.lock.find_by(idempotency_key:)
      return build_execution(existing) if existing
    end

    record = Models::Execution.create!(
      workflow_class:,
      state: "running",
      ctx: serializer.dump(context),
      cursor_step: steps.first && steps.first[:name],
      idempotency_key:,
      metadata: ( || {}).stringify_keys,
      timeout_at: timeout ? now + timeout : nil,
      last_enqueued_at: now
    )

    steps.each_with_index do |step, index|
      Models::Step.create!(
        execution: record,
        name: step[:name].to_s,
        style: step[:style].to_s,
        options: serializable_step_options(step[:options]),
        position: step[:position] || index,
        state: index.zero? ? "pending" : "pending",
        attempts: 0
      )
    end

    if steps.empty?
      record.update!(state: "completed", cursor_step: nil, completed_at: now)
      ActiveSupport::Notifications.instrument("active_saga.execution.completed",
        execution_id: record.id,
        workflow: workflow_class)
    end
  end

  enqueue_runner(record, step_name: steps.first && steps.first[:name]) unless steps.empty?
  build_execution(record)
end

#step_definition(execution, step) ⇒ Object



336
337
338
# File 'lib/active_saga/stores/active_record.rb', line 336

def step_definition(execution, step)
  execution.workflow_class.constantize.step_definition(step.name)
end

#steps_for(execution_id) ⇒ Object



142
143
144
145
146
# File 'lib/active_saga/stores/active_record.rb', line 142

def steps_for(execution_id)
  Models::Step.where(execution_id: execution_id).order(:position).map do |step|
    step.attributes.deep_symbolize_keys
  end
end

#transition_to_failed!(execution, step) ⇒ Object



412
413
414
415
416
417
418
419
420
# File 'lib/active_saga/stores/active_record.rb', line 412

def transition_to_failed!(execution, step)
  step.update!(state: "failed")
  run_compensations!(execution, upto: step.position)
  execution.update!(state: "failed", cursor_step: nil)
  ActiveSupport::Notifications.instrument("active_saga.execution.failed",
    execution_id: execution.id,
    workflow: execution.workflow_class,
    step: step.name)
end

#with_execution_lock(execution_id) ⇒ Object



167
168
169
170
171
172
173
174
# File 'lib/active_saga/stores/active_record.rb', line 167

def with_execution_lock(execution_id)
  ::ActiveRecord::Base.transaction do
    record = Models::Execution.lock.find_by(id: execution_id)
    return unless record

    yield(record)
  end
end