Class: StateMachines::AsyncMode::AsyncTransitionCollection

Inherits:
TransitionCollection show all
Defined in:
lib/state_machines/async_mode/async_transition_collection.rb

Overview

Async-aware transition collection that can execute transitions concurrently

Instance Attribute Summary

Attributes inherited from TransitionCollection

#options, #skip_actions, #skip_after, #use_transactions

Instance Method Summary collapse

Methods inherited from TransitionCollection

#initialize, #perform

Constructor Details

This class inherits a constructor from StateMachines::TransitionCollection

Instance Method Details

#perform_async(&block) ⇒ Object

Performs transitions asynchronously using Async Provides better concurrency for I/O-bound operations



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/state_machines/async_mode/async_transition_collection.rb', line 21

def perform_async(&block)
  reset

  unless defined?(::Async::Task) && ::Async::Task.current?
    return Async do
      perform_async(&block)
    end.wait
  end

  if valid?
    # Create async tasks for each transition
    tasks = map do |transition|
      Async do
        execute_transition(transition, &block)
      end
    end

    # Wait for all tasks to complete
    completed_transitions = []
    tasks.each do |task|
      begin
        result = task.wait
        completed_transitions << result if result
      rescue StandardError => e
        # Handle individual transition failures
        rollback
        raise AsyncTransitionError.new(object, map(&:machine), [e.message])
      end
    end

    # Check if all transitions succeeded
    @success = completed_transitions.length == length
  end

  success?
end

#perform_threaded(&block) ⇒ Object

Performs transitions concurrently using threads Better for CPU-bound operations but requires more careful synchronization



60
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
# File 'lib/state_machines/async_mode/async_transition_collection.rb', line 60

def perform_threaded(&block)
  reset

  if valid?
    # Use basic thread approach
    threads = []
    results = []
    results_mutex = Concurrent::ReentrantReadWriteLock.new

    each do |transition|
      threads << Thread.new do
        begin
          result = execute_transition(transition, &block)

          results_mutex.with_write_lock { results << result }
        rescue StandardError => e
          # Handle individual transition failures
          rollback
          raise AsyncTransitionError.new(object, [transition.machine], [e.message])
        end
      end
    end

    # Wait for all threads to complete
    threads.each(&:join)
    @success = results.length == length
  end

  success?
end