Class: ActiveWorkflow::Stores::ActiveRecord

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

Overview

ActiveRecord-backed persistence implementation.

Defined Under Namespace

Modules: Models Classes: Backoff, 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 ActiveWorkflow::Stores::Base

Instance Method Details

#advance_cursor(execution, step) ⇒ Object



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/active_workflow/stores/active_record.rb', line 294

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_workflow.execution.completed",
      execution_id: execution.id,
      workflow: execution.workflow_class)
  end
end

#apply_signal_handler(execution, name, payload) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
# File 'lib/active_workflow/stores/active_record.rb', line 282

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



265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/active_workflow/stores/active_record.rb', line 265

def build_execution(record)
  ActiveWorkflow::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,
    store: self
  )
end

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



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/active_workflow/stores/active_record.rb', line 150

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 ActiveWorkflow::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 ActiveWorkflow::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_workflow.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.id)
  end
end

#context_from(execution) ⇒ Object



257
258
259
# File 'lib/active_workflow/stores/active_record.rb', line 257

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

#enqueue_runner(execution_id, run_at: nil) ⇒ Object



127
128
129
130
131
132
133
# File 'lib/active_workflow/stores/active_record.rb', line 127

def enqueue_runner(execution_id, run_at: nil)
  if run_at
    ActiveWorkflow::Jobs::RunnerJob.set(wait_until: run_at).perform_later(execution_id)
  else
    ActiveWorkflow::Jobs::RunnerJob.perform_later(execution_id)
  end
end

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



223
224
225
226
227
228
229
230
# File 'lib/active_workflow/stores/active_record.rb', line 223

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



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/active_workflow/stores/active_record.rb', line 198

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 ActiveWorkflow::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_workflow.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



232
233
234
235
236
237
238
239
# File 'lib/active_workflow/stores/active_record.rb', line 232

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



122
123
124
125
# File 'lib/active_workflow/stores/active_record.rb', line 122

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

#persist_context(execution, ctx) ⇒ Object



261
262
263
# File 'lib/active_workflow/stores/active_record.rb', line 261

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

#process_execution(execution_id) ⇒ Object



144
145
146
147
148
# File 'lib/active_workflow/stores/active_record.rb', line 144

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



313
314
315
316
317
318
319
320
321
322
323
# File 'lib/active_workflow/stores/active_record.rb', line 313

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



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/active_workflow/stores/active_record.rb', line 325

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 = 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_workflow.retry.scheduled",
      execution_id: execution.id,
      workflow: execution.workflow_class,
      step: step.name,
      attempts: current_attempts + 1,
      wait: delay)

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

#serializable_step_options(options) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/active_workflow/stores/active_record.rb', line 103

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



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/active_workflow/stores/active_record.rb', line 241

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_workflow.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.id)
    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
# File 'lib/active_workflow/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)
    end
  end

  enqueue_runner(record.id) unless steps.empty?
  build_execution(record)
end

#step_definition(execution, step) ⇒ Object



278
279
280
# File 'lib/active_workflow/stores/active_record.rb', line 278

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

#transition_to_failed!(execution, step) ⇒ Object



354
355
356
357
358
359
360
361
362
# File 'lib/active_workflow/stores/active_record.rb', line 354

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_workflow.execution.failed",
    execution_id: execution.id,
    workflow: execution.workflow_class,
    step: step.name)
end

#with_execution_lock(execution_id) ⇒ Object



135
136
137
138
139
140
141
142
# File 'lib/active_workflow/stores/active_record.rb', line 135

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