state_machines 0.202.0 → 0.301.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +160 -14
  3. data/lib/state_machines/async_mode/async_event_extensions.rb +6 -10
  4. data/lib/state_machines/async_mode/async_events.rb +56 -72
  5. data/lib/state_machines/async_mode/async_machine.rb +3 -5
  6. data/lib/state_machines/async_mode/async_transition_collection.rb +32 -104
  7. data/lib/state_machines/async_mode/thread_safe_state.rb +8 -4
  8. data/lib/state_machines/branch.rb +35 -22
  9. data/lib/state_machines/callback.rb +4 -4
  10. data/lib/state_machines/core.rb +1 -0
  11. data/lib/state_machines/error.rb +37 -0
  12. data/lib/state_machines/event.rb +125 -2
  13. data/lib/state_machines/event_collection.rb +6 -1
  14. data/lib/state_machines/extensions.rb +22 -0
  15. data/lib/state_machines/helper_module.rb +1 -0
  16. data/lib/state_machines/machine/class_methods.rb +15 -3
  17. data/lib/state_machines/machine/configuration.rb +5 -3
  18. data/lib/state_machines/machine/event_methods.rb +5 -0
  19. data/lib/state_machines/machine/helper_generators.rb +3 -1
  20. data/lib/state_machines/machine/utilities.rb +1 -1
  21. data/lib/state_machines/machine.rb +8 -0
  22. data/lib/state_machines/machine_collection.rb +7 -6
  23. data/lib/state_machines/macro_methods.rb +4 -4
  24. data/lib/state_machines/path.rb +1 -0
  25. data/lib/state_machines/path_collection.rb +1 -0
  26. data/lib/state_machines/state_context.rb +1 -0
  27. data/lib/state_machines/stdio_renderer.rb +8 -6
  28. data/lib/state_machines/syntax_validator.rb +3 -3
  29. data/lib/state_machines/test_helper.rb +228 -27
  30. data/lib/state_machines/transition.rb +19 -5
  31. data/lib/state_machines/transition_claim.rb +118 -0
  32. data/lib/state_machines/transition_collection.rb +142 -18
  33. data/lib/state_machines/version.rb +1 -1
  34. metadata +8 -7
@@ -16,119 +16,47 @@ module StateMachines
16
16
 
17
17
  # Async-aware transition collection that can execute transitions concurrently
18
18
  class AsyncTransitionCollection < TransitionCollection
19
- # Performs transitions asynchronously using Async
20
- # Provides better concurrency for I/O-bound operations
21
- def perform_async(&block)
22
- reset
23
-
24
- unless defined?(::Async::Task) && ::Async::Task.current?
25
- return Async do
26
- perform_async(&block)
27
- end.wait
28
- end
29
-
30
- if valid?
31
- # Create async tasks for each transition
32
- tasks = map do |transition|
33
- Async do
34
- execute_transition(transition, &block)
35
- end
36
- end
37
-
38
- # Wait for all tasks to complete
39
- completed_transitions = []
40
- tasks.each do |task|
41
- begin
42
- result = task.wait
43
- completed_transitions << result if result
44
- rescue StandardError => e
45
- # Handle individual transition failures
46
- rollback
47
- raise AsyncTransitionError.new(object, map(&:machine), [e.message])
48
- end
49
- end
50
-
51
- # Check if all transitions succeeded
52
- @success = completed_transitions.length == length
53
- end
54
-
55
- success?
19
+ # Performs the collection inside an Async task, entering a reactor when
20
+ # the caller is not already in one.
21
+ #
22
+ # The callbacks and the action belong to the collection, not to one
23
+ # transition, so they run once. What is asynchronous is the collection as
24
+ # a whole, which is what lets an I/O-bound action yield to its reactor.
25
+ def perform_async(&)
26
+ return perform(&) if defined?(::Async::Task) && ::Async::Task.current?
27
+
28
+ Async { perform(&) }.wait
56
29
  end
57
30
 
58
- # Performs transitions concurrently using threads
59
- # Better for CPU-bound operations but requires more careful synchronization
60
- def perform_threaded(&block)
61
- reset
62
-
63
- if valid?
64
- # Use basic thread approach
65
- threads = []
66
- results = []
67
- results_mutex = Concurrent::ReentrantReadWriteLock.new
68
-
69
- each do |transition|
70
- threads << Thread.new do
71
- begin
72
- result = execute_transition(transition, &block)
73
-
74
- results_mutex.with_write_lock { results << result }
75
- rescue StandardError => e
76
- # Handle individual transition failures
77
- rollback
78
- raise AsyncTransitionError.new(object, [transition.machine], [e.message])
79
- end
80
- end
81
- end
82
-
83
- # Wait for all threads to complete
84
- threads.each(&:join)
85
- @success = results.length == length
86
- end
87
-
88
- success?
31
+ # Performs the collection on another thread and waits for its result.
32
+ def perform_threaded(&)
33
+ Thread.new { perform(&) }.value
89
34
  end
90
35
 
91
36
  private
92
37
 
93
- # Runs a single transition either via event attributes or the standard
94
- # callback/transaction flow, returning the transition on completion
95
- def execute_transition(transition, &block)
96
- if use_event_attributes? && !block_given?
97
- transition.transient = true
98
- transition.machine.write_safely(object, :event_transition, transition)
99
- run_actions
100
- else
101
- within_transaction do
102
- catch(:halt) { run_callbacks(&block) }
103
- rollback unless success?
104
- end
105
- end
106
-
107
- transition
108
- end
109
-
110
38
  # Override run_actions to be thread-safe when needed
111
- def run_actions(&block)
39
+ def run_actions(&)
112
40
  catch_exceptions do
113
41
  @success = if block_given?
114
- result = yield
115
- actions.each { |action| results[action] = result }
116
- !!result
117
- else
118
- actions.compact.each do |action|
119
- next if skip_actions
120
-
121
- # Use thread-safe write for results
122
- if object.respond_to?(:state_machine_mutex)
123
- object.state_machine_mutex.with_write_lock do
124
- results[action] = object.send(action)
125
- end
126
- else
127
- results[action] = object.send(action)
128
- end
129
- end
130
- results.values.all?
131
- end
42
+ result = yield
43
+ actions.each { |action| results[action] = result }
44
+ !!result
45
+ else
46
+ actions.compact.each do |action|
47
+ next if skip_actions
48
+
49
+ # Use thread-safe write for results
50
+ if object.respond_to?(:state_machine_mutex)
51
+ object.state_machine_mutex.with_write_lock do
52
+ results[action] = object.send(action)
53
+ end
54
+ else
55
+ results[action] = object.send(action)
56
+ end
57
+ end
58
+ results.values.all?
59
+ end
132
60
  end
133
61
  end
134
62
  end
@@ -5,11 +5,17 @@ module StateMachines
5
5
  # Thread-safe state operations for async-enabled state machines
6
6
  # Uses concurrent-ruby for enterprise-grade thread safety
7
7
  module ThreadSafeState
8
+ TRANSIENT_VARIABLES = StateMachines::InstanceMethods::TRANSIENT_VARIABLES
9
+
10
+ MUTEX_CREATION_LOCK = Thread::Mutex.new
11
+
8
12
  # Gets or creates a reentrant mutex for thread-safe state operations on an object
9
13
  # Each object gets its own mutex to avoid global locking
10
14
  # Uses Concurrent::ReentrantReadWriteLock for better performance
11
15
  def state_machine_mutex
12
- @_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
16
+ @_state_machine_mutex || MUTEX_CREATION_LOCK.synchronize do
17
+ @_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
18
+ end
13
19
  end
14
20
 
15
21
  # Thread-safe version of state reading
@@ -30,8 +36,7 @@ module StateMachines
30
36
 
31
37
  # Handle marshalling by excluding the mutex (will be recreated when needed)
32
38
  def marshal_dump
33
- # Get instance variables excluding the mutex
34
- vars = instance_variables.reject { |var| var == :@_state_machine_mutex }
39
+ vars = instance_variables - TRANSIENT_VARIABLES
35
40
  vars.map { |var| [var, instance_variable_get(var)] }
36
41
  end
37
42
 
@@ -40,7 +45,6 @@ module StateMachines
40
45
  data.each do |var, value|
41
46
  instance_variable_set(var, value)
42
47
  end
43
- # Don't set @_state_machine_mutex - let it be lazily created
44
48
  end
45
49
  end
46
50
  end
@@ -16,6 +16,14 @@ module StateMachines
16
16
  # The condition that must *not* be met on an object
17
17
  attr_reader :unless_condition
18
18
 
19
+ # Conditions on the state of other machines
20
+ attr_reader :if_state_condition, :unless_state_condition,
21
+ :if_all_states_condition, :unless_all_states_condition,
22
+ :if_any_state_condition, :unless_any_state_condition
23
+
24
+ # The state guards that are set, keyed by option
25
+ attr_reader :state_guards
26
+
19
27
  # The requirement for verifying the event being matched
20
28
  attr_reader :event_requirement
21
29
 
@@ -34,12 +42,20 @@ module StateMachines
34
42
  # Build conditionals
35
43
  @if_condition = options.delete(:if)
36
44
  @unless_condition = options.delete(:unless)
37
- @if_state_condition = options.delete(:if_state)
38
- @unless_state_condition = options.delete(:unless_state)
39
- @if_all_states_condition = options.delete(:if_all_states)
40
- @unless_all_states_condition = options.delete(:unless_all_states)
41
- @if_any_state_condition = options.delete(:if_any_state)
42
- @unless_any_state_condition = options.delete(:unless_any_state)
45
+ @if_state_condition = build_state_guard(options, :if_state)
46
+ @unless_state_condition = build_state_guard(options, :unless_state)
47
+ @if_all_states_condition = build_state_guard(options, :if_all_states)
48
+ @unless_all_states_condition = build_state_guard(options, :unless_all_states)
49
+ @if_any_state_condition = build_state_guard(options, :if_any_state)
50
+ @unless_any_state_condition = build_state_guard(options, :unless_any_state)
51
+ @state_guards = {
52
+ if_state: @if_state_condition,
53
+ unless_state: @unless_state_condition,
54
+ if_all_states: @if_all_states_condition,
55
+ unless_all_states: @unless_all_states_condition,
56
+ if_any_state: @if_any_state_condition,
57
+ unless_any_state: @unless_any_state_condition
58
+ }.compact.freeze
43
59
 
44
60
  # Build event requirement
45
61
  @event_requirement = build_matcher(options, :on, :except_on)
@@ -94,7 +110,7 @@ module StateMachines
94
110
  def matches?(object, query = {})
95
111
  !match(object, query).nil?
96
112
  end
97
-
113
+
98
114
  # Alias for Minitest's assert_match
99
115
  alias =~ matches?
100
116
 
@@ -134,7 +150,7 @@ module StateMachines
134
150
  end
135
151
 
136
152
  def draw(graph, event, valid_states, io = $stdout)
137
- machine.renderer.draw_branch(self, graph, event, valid_states, io)
153
+ event.machine.renderer.draw_branch(self, graph, event, valid_states, io)
138
154
  end
139
155
 
140
156
  protected
@@ -158,6 +174,15 @@ module StateMachines
158
174
  end
159
175
  end
160
176
 
177
+ # Frozen copy, since branches are shared with subclasses
178
+ def build_state_guard(options, option)
179
+ conditions = options.delete(option)
180
+ return if conditions.nil?
181
+ raise ArgumentError, ":#{option} must be a non-empty Hash of state machine name => state name, got #{conditions.inspect}" unless conditions.is_a?(Hash) && !conditions.empty?
182
+
183
+ conditions.dup.freeze
184
+ end
185
+
161
186
  # Verifies that all configured requirements (event and state) match the
162
187
  # given query. If a match is found, then a hash containing the
163
188
  # event/state requirements that passed will be returned; otherwise, nil.
@@ -199,16 +224,6 @@ module StateMachines
199
224
 
200
225
  return false unless if_passes && unless_passes
201
226
 
202
- # Consolidate all state guards
203
- state_guards = {
204
- if_state: @if_state_condition,
205
- unless_state: @unless_state_condition,
206
- if_all_states: @if_all_states_condition,
207
- unless_all_states: @unless_all_states_condition,
208
- if_any_state: @if_any_state_condition,
209
- unless_any_state: @unless_any_state_condition
210
- }.compact
211
-
212
227
  return true if state_guards.empty?
213
228
 
214
229
  validate_and_check_state_guards(object, state_guards)
@@ -221,14 +236,12 @@ module StateMachines
221
236
  case guard_type
222
237
  when :if_state, :if_all_states
223
238
  conditions.all? { |machine, state| check_state(object, machine, state) }
224
- when :unless_state
239
+ when :unless_state, :unless_any_state
225
240
  conditions.none? { |machine, state| check_state(object, machine, state) }
226
241
  when :if_any_state
227
242
  conditions.any? { |machine, state| check_state(object, machine, state) }
228
243
  when :unless_all_states
229
244
  !conditions.all? { |machine, state| check_state(object, machine, state) }
230
- when :unless_any_state
231
- conditions.none? { |machine, state| check_state(object, machine, state) }
232
245
  end
233
246
  end
234
247
  end
@@ -240,7 +253,7 @@ module StateMachines
240
253
  state = machine.states[state_name]
241
254
  raise ArgumentError, "State '#{state_name}' is not defined in state machine '#{machine_name}'" unless state
242
255
 
243
- state.matches?(object.send(machine_name))
256
+ state.matches?(machine.read(object, :state))
244
257
  end
245
258
  end
246
259
  end
@@ -176,15 +176,15 @@ module StateMachines
176
176
  # For all other types of callbacks, this will evaluate each method in
177
177
  # order. The callback will only halt if the resulting value from the
178
178
  # method passes the terminator.
179
- def run_methods(object, context = {}, index = 0, *args, &block)
179
+ def run_methods(object, context = {}, index = 0, *, &)
180
180
  case type
181
181
  when :around
182
182
  current_method = @methods[index]
183
183
  if current_method
184
184
  yielded = false
185
- evaluate_method(object, current_method, *args) do
185
+ evaluate_method(object, current_method, *) do
186
186
  yielded = true
187
- run_methods(object, context, index + 1, *args, &block)
187
+ run_methods(object, context, index + 1, *, &)
188
188
  end
189
189
 
190
190
  throw :halt unless yielded
@@ -193,7 +193,7 @@ module StateMachines
193
193
  end
194
194
  else
195
195
  @methods.each do |method|
196
- result = evaluate_method(object, method, *args)
196
+ result = evaluate_method(object, method, *)
197
197
  throw :halt if @terminator&.call(result)
198
198
  end
199
199
  end
@@ -19,6 +19,7 @@ require 'state_machines/matcher'
19
19
  require 'state_machines/matcher_helpers'
20
20
 
21
21
  require 'state_machines/transition'
22
+ require 'state_machines/transition_claim'
22
23
  require 'state_machines/transition_collection'
23
24
 
24
25
  require 'state_machines/branch'
@@ -64,11 +64,19 @@ module StateMachines
64
64
  # The current state value for the machine
65
65
  attr_reader :from
66
66
 
67
+ # Why the transition was refused: the reason recorded for the event on the
68
+ # object when the error was built.
69
+ #
70
+ # @return [:no_transition, :guard, :halted, :action_failed, :contended, nil]
71
+ # @see StateMachines::Event#refusal
72
+ attr_reader :reason
73
+
67
74
  def initialize(object, machine, event) # :nodoc:
68
75
  @machine = machine
69
76
  @from_state = machine.states.match!(object)
70
77
  @from = machine.read(object, :state)
71
78
  @event = machine.events.fetch(event)
79
+ @reason = @event.refusal(object)
72
80
  errors = machine.errors_for(object)
73
81
 
74
82
  message = "Cannot transition #{machine.name} via :#{self.event} from #{from_name.inspect}"
@@ -102,11 +110,40 @@ module StateMachines
102
110
  # The set of events that failed the transition(s)
103
111
  attr_reader :events
104
112
 
113
+ # The refusal reason of each event that caused the failure, keyed by the
114
+ # event name as given. Events refused only because another one was are
115
+ # left out.
116
+ #
117
+ # @return [Hash{Symbol => Symbol}]
118
+ # @see StateMachines::Event#refusal
119
+ attr_reader :reasons
120
+
105
121
  def initialize(object, events) # :nodoc:
106
122
  @events = events
123
+ @reasons = refusal_reasons(object, events)
107
124
 
108
125
  super(object, "Cannot run events in parallel: #{events * ', '}")
109
126
  end
127
+
128
+ private
129
+
130
+ # Reads the recorded refusal reason of each given event on the object,
131
+ # finding each event across the object's machines by its qualified name.
132
+ #
133
+ # @param object [Object] the object the events were fired on
134
+ # @param events [Array<Symbol>] the qualified event names that were fired
135
+ # @return [Hash{Symbol => Symbol}] the reason per event name, leaving out
136
+ # events without one (and every event when the object has no machines)
137
+ def refusal_reasons(object, events)
138
+ return {} unless object.class.respond_to?(:state_machines)
139
+
140
+ machines = object.class.state_machines.values
141
+ events.each_with_object({}) do |event_name, reasons|
142
+ event = machines.lazy.filter_map { |machine| machine.events[event_name, :qualified_name] }.first
143
+ reason = event&.refusal(object)
144
+ reasons[event_name] = reason if reason
145
+ end
146
+ end
110
147
  end
111
148
 
112
149
  # A method was called in an invalid state context
@@ -9,6 +9,28 @@ module StateMachines
9
9
  class Event
10
10
  include MatcherHelpers
11
11
 
12
+ # The object instance variable holding the most recent refusal reason per
13
+ # machine and event
14
+ REFUSALS_VARIABLE = :@_state_machine_refusals
15
+
16
+ # Serialises the creation and updates of an object's refusal reasons, so
17
+ # that concurrent attempts on one object do not lose each other's reason
18
+ REFUSALS_LOCK = Thread::Mutex.new
19
+
20
+ class << self
21
+ # Forgets every refusal reason recorded on the given object, e.g. when
22
+ # it is copied or reloaded.
23
+ #
24
+ # @api private
25
+ # @param object [Object] the object whose reasons are forgotten
26
+ # @return [void]
27
+ def clear_refusals(object)
28
+ return if object.frozen? || !object.instance_variable_defined?(REFUSALS_VARIABLE)
29
+
30
+ object.remove_instance_variable(REFUSALS_VARIABLE)
31
+ end
32
+ end
33
+
12
34
  # The state machine for which this event is defined
13
35
  attr_accessor :machine
14
36
 
@@ -161,21 +183,116 @@ module StateMachines
161
183
 
162
184
  # Attempts to perform the next available transition on the given object.
163
185
  # If no transitions can be made, then this will return false, otherwise
164
- # true.
186
+ # the performed {StateMachines::Transition}.
165
187
  #
166
188
  # Any additional arguments are passed to the StateMachines::Transition#perform
167
189
  # instance method.
190
+ #
191
+ # The reason for a refusal is recorded on the object and can be read back
192
+ # with {#refusal} (or the generated `*_refusal` helper).
193
+ #
194
+ # @return [StateMachines::Transition, false] the performed transition, or
195
+ # false if the event was refused
196
+ # @see #refusal
168
197
  def fire(object, *event_args)
169
198
  machine.reset(object)
170
199
 
171
- if (transition = transition_for(object, {}, *event_args))
200
+ transition = begin
201
+ transition_for(object, {}, *event_args)
202
+ rescue StandardError
203
+ # A guard raised before this attempt had an outcome
204
+ record_refusal(object, nil)
205
+ raise
206
+ end
207
+
208
+ if transition
172
209
  transition.perform(*event_args)
173
210
  else
211
+ record_refusal(object, refusal_without_transition(object))
174
212
  on_failure(object, *event_args)
175
213
  false
176
214
  end
177
215
  end
178
216
 
217
+ # The reason the most recent attempt to fire this event on the given object
218
+ # was refused.
219
+ #
220
+ # The reasons are:
221
+ # - :no_transition - no transition is defined for the event from the
222
+ # object's current state
223
+ # - :guard - a transition is defined from the current state, but its :if /
224
+ # :unless / state guards rejected it
225
+ # - :halted - a before_transition or around_transition callback halted the
226
+ # transition
227
+ # - :action_failed - the machine's action (e.g. save) did not succeed
228
+ # - :contended - in async mode, a concurrent transition held or moved the
229
+ # attribute first
230
+ #
231
+ # When the event was fired in parallel with others (see
232
+ # {StateMachines::InstanceMethods#fire_events}), only the events that caused
233
+ # the refusal carry a reason; the others read nil. When the action failed
234
+ # because an event attribute it performed was refused (see
235
+ # {StateMachines::TransitionCollection#perform}), the event carries that
236
+ # inner reason.
237
+ #
238
+ # The reason describes the most recent attempt *on the object*, whichever
239
+ # caller made it: it is not tied to a caller. When several threads or
240
+ # fibers fire events on the same object concurrently, each should rely on
241
+ # its own result - the bang method's {StateMachines::InvalidTransition#reason}
242
+ # (or {StateMachines::Transition#refusal} of a transition it performed) -
243
+ # rather than on this reader, which another caller may have overwritten.
244
+ #
245
+ # A frozen object records no reason, so this reads nil for it. A copy
246
+ # (+dup+ / +clone+) starts with no reasons, as it has made no attempt.
247
+ #
248
+ # @param object [Object] the object the event was fired on
249
+ # @return [:no_transition, :guard, :halted, :action_failed, :contended, nil]
250
+ # the refusal reason, or nil if the most recent attempt succeeded, raised
251
+ # before an outcome, or none was made
252
+ # @example
253
+ # vehicle.state # => "idling"
254
+ # vehicle.ignite # => false
255
+ # vehicle.class.state_machine.events[:ignite].refusal(vehicle) # => :no_transition
256
+ # vehicle.ignite_refusal # => :no_transition
257
+ def refusal(object)
258
+ return if object.frozen?
259
+
260
+ refusals = object.instance_variable_get(REFUSALS_VARIABLE)
261
+ refusals && refusals[[machine.name, name]]
262
+ end
263
+
264
+ # Records the reason the event was refused on the given object, or clears
265
+ # it when reason is nil. Nothing is recorded on a frozen object.
266
+ #
267
+ # @param object [Object] the object the event was fired on
268
+ # @param reason [Symbol, nil] the refusal reason (see {#refusal}), or nil
269
+ # to clear it
270
+ # @return [void]
271
+ def record_refusal(object, reason) # :nodoc:
272
+ return if object.frozen?
273
+
274
+ key = [machine.name, name]
275
+ REFUSALS_LOCK.synchronize do
276
+ refusals = object.instance_variable_get(REFUSALS_VARIABLE)
277
+ if reason
278
+ (refusals || object.instance_variable_set(REFUSALS_VARIABLE, {}))[key] = reason
279
+ else
280
+ refusals&.delete(key)
281
+ end
282
+ end
283
+ end
284
+
285
+ # Why no transition could be built for the object. The conditions are not
286
+ # evaluated again.
287
+ #
288
+ # @param object [Object] the object the event was fired on
289
+ # @return [:guard, :no_transition] :guard when a branch matches the current
290
+ # state but its conditions rejected it, otherwise :no_transition
291
+ def refusal_without_transition(object) # :nodoc:
292
+ query = { from: machine.states.match!(object).name, guard: false }
293
+ branches.any? { |branch| branch.matches?(object, query) } ? :guard : :no_transition
294
+ end
295
+
179
296
  # Marks the object as invalid and runs any failure callbacks associated with
180
297
  # this event. This should get called anytime this event fails to transition.
181
298
  def on_failure(object, *args)
@@ -238,6 +355,12 @@ module StateMachines
238
355
  machine.event(name).fire(object, *args, **kwargs)
239
356
  end
240
357
 
358
+ # Gets the reason the most recent attempt to fire the event was refused,
359
+ # or nil if it succeeded
360
+ machine.define_helper(:instance, "#{qualified_name}_refusal") do |machine, object|
361
+ machine.event(name).refusal(object)
362
+ end
363
+
241
364
  # Fires the event, raising an exception if it fails
242
365
  machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args, **kwargs|
243
366
  object.send(qualified_name, *args, **kwargs) || raise(StateMachines::InvalidTransition.new(object, machine, name))
@@ -129,7 +129,12 @@ module StateMachines
129
129
  if event = self[event_name.to_sym, :name]
130
130
  event.transition_for(object) || begin
131
131
  # No valid transition: invalidate
132
- machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]]) if invalidate
132
+ if invalidate
133
+ reason = event.refusal_without_transition(object)
134
+ event.record_refusal(object, reason)
135
+ TransitionCollection.report_nested_refusal(object, reason)
136
+ machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]])
137
+ end
133
138
  false
134
139
  end
135
140
  else
@@ -22,6 +22,10 @@ module StateMachines
22
22
  end
23
23
 
24
24
  module InstanceMethods
25
+ # Per-object concurrency state, created on demand: the lock and the
26
+ # transition claims. Never copied nor marshalled.
27
+ TRANSIENT_VARIABLES = %i[@_state_machine_mutex @_state_machine_transition_claims].freeze
28
+
25
29
  # Runs one or more events in parallel. All events will run through the
26
30
  # following steps:
27
31
  # * Before callbacks
@@ -141,6 +145,24 @@ module StateMachines
141
145
  fire_events(*(events + [run_action])) || raise(StateMachines::InvalidParallelTransition.new(self, events))
142
146
  end
143
147
 
148
+ # A copy (+dup+ / +clone+) has made no attempt to fire an event, so it
149
+ # starts with no refusal reasons instead of sharing the original's. It
150
+ # also gets its own lock and transition claims (created on demand)
151
+ # instead of sharing the original's.
152
+ #
153
+ # A class defining its own +initialize_copy+ must call +super+.
154
+ #
155
+ # @param orig [Object] the object being copied
156
+ # @return [void]
157
+ # @see StateMachines::Event#refusal
158
+ def initialize_copy(orig)
159
+ super
160
+ StateMachines::Event.clear_refusals(self)
161
+ TRANSIENT_VARIABLES.each do |ivar|
162
+ remove_instance_variable(ivar) if instance_variable_defined?(ivar)
163
+ end
164
+ end
165
+
144
166
  protected
145
167
 
146
168
  def initialize_state_machines(options = {}, &) # :nodoc:
@@ -5,6 +5,7 @@ module StateMachines
5
5
  # state machine
6
6
  class HelperModule < Module # :nodoc:
7
7
  def initialize(machine, kind)
8
+ super()
8
9
  @machine = machine
9
10
  @kind = kind
10
11
  end
@@ -3,6 +3,10 @@
3
3
  module StateMachines
4
4
  class Machine
5
5
  module ClassMethods
6
+ # Options a reopened machine accepts; the others only apply when it is
7
+ # created.
8
+ REOPEN_OPTIONS = %i[initial async].freeze
9
+
6
10
  # Attempts to find or create a state machine for the given class. For
7
11
  # example,
8
12
  #
@@ -14,6 +18,9 @@ module StateMachines
14
18
  # If a machine of the given name already exists in one of the class's
15
19
  # superclasses, then a copy of that machine will be created and stored
16
20
  # in the new owner class (the original will remain unchanged).
21
+ #
22
+ # Reopening an existing machine applies +:initial+ and +:async+;
23
+ # any other option raises ArgumentError instead of being ignored.
17
24
  def find_or_create(owner_class, *args, &)
18
25
  options = args.last.is_a?(Hash) ? args.pop : {}
19
26
  name = args.first || :state
@@ -24,15 +31,20 @@ module StateMachines
24
31
  owner_class.state_machines.values.first))) || nil
25
32
 
26
33
  if machine
34
+ unsupported = options.keys - REOPEN_OPTIONS
35
+ unless unsupported.empty?
36
+ raise ArgumentError, "Cannot change #{unsupported.map(&:inspect).join(', ')} of existing state machine " \
37
+ "#{name.inspect} on #{owner_class}; reopening it accepts only :initial and :async"
38
+ end
39
+
27
40
  # Only create a new copy if changes are being made to the machine in
28
41
  # a subclass
29
42
  if machine.owner_class != owner_class && (options.any? || block_given?)
30
43
  machine = machine.clone
31
- machine.initial_state = options[:initial] if options.include?(:initial)
32
44
  machine.owner_class = owner_class
33
- # Configure async mode if requested in options
34
- machine.configure_async_mode!(options[:async]) if options.include?(:async)
35
45
  end
46
+ machine.initial_state = options[:initial] if options.include?(:initial)
47
+ machine.configure_async_mode!(options[:async]) if options.include?(:async)
36
48
 
37
49
  # Evaluate DSL
38
50
  machine.instance_eval(&) if block_given?