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



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/active_saga/stores/active_record.rb', line 323

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



311
312
313
314
315
316
317
318
319
320
321
# File 'lib/active_saga/stores/active_record.rb', line 311

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



293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/active_saga/stores/active_record.rb', line 293

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



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/active_saga/stores/active_record.rb', line 260

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



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
197
198
199
# File 'lib/active_saga/stores/active_record.rb', line 153

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

#context_from(execution) ⇒ Object



285
286
287
# File 'lib/active_saga/stores/active_record.rb', line 285

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

#enqueue_runner(execution_id, run_at: nil) ⇒ Object



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

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

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



226
227
228
229
230
231
232
233
# File 'lib/active_saga/stores/active_record.rb', line 226

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



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

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



235
236
237
238
239
240
241
242
# File 'lib/active_saga/stores/active_record.rb', line 235

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



289
290
291
# File 'lib/active_saga/stores/active_record.rb', line 289

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

#process_execution(execution_id) ⇒ Object



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

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



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

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



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/active_saga/stores/active_record.rb', line 354

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.id, 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



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/active_saga/stores/active_record.rb', line 244

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.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
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.id) unless steps.empty?
  build_execution(record)
end

#step_definition(execution, step) ⇒ Object



307
308
309
# File 'lib/active_saga/stores/active_record.rb', line 307

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

#transition_to_failed!(execution, step) ⇒ Object



383
384
385
386
387
388
389
390
391
# File 'lib/active_saga/stores/active_record.rb', line 383

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



138
139
140
141
142
143
144
145
# File 'lib/active_saga/stores/active_record.rb', line 138

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