state_machines 0.201.0 → 0.300.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fcd3d5e6fc0f3982c8ddabc40480b43375d6e323957dd392ca4b3cc10f9c0f40
4
- data.tar.gz: 89556aa64bb82045527f260098dd801acce298be5ad873ed7f250805b7839c87
3
+ metadata.gz: fdbf8052e6f7ea2c8b05a007f232c67d3a41f4183bd0b0686e2fd6843105185c
4
+ data.tar.gz: 994775869a61cd7f5f55f63ce0e79b85566c7015395f33d4db3f92097532e182
5
5
  SHA512:
6
- metadata.gz: d44ae6b303dc577db3ed8aa70d7132521b8be94c3651fa9afe886e90c7561ebea686d1c743adc9464d08bd01d2903a4e75eabf7aa567abacab81d0b1c889fea4
7
- data.tar.gz: b04cbf3f1cb69b943fdf19aa91f37b3376f976c4ed28bd08ab4aed18af6473b3508c05fe52317f10f2627660a67a3e8c3e8481a520ba2985a5c7c37316499e51
6
+ metadata.gz: 8d5d0747286937d1b336d3e9628700afbd06c39d05d57123737733421d5b02889caa45884f6bc62c49a08b08c34fbb3816d4d10b4e3fd1684fcb3118afdb4d38
7
+ data.tar.gz: 11018072c682344a1bb6c7592c54d2d79a78dc06f78b97018edbdb1a214a6d5d6d6b6a522224519b1503364cf529a91b5a4a7e15004b049de85769022df7b500
data/README.md CHANGED
@@ -197,19 +197,19 @@ vehicle.state_transitions # => [#<StateMachines:Transition attribute=:stat
197
197
  vehicle.speed # => 0
198
198
  vehicle.moving? # => false
199
199
 
200
- vehicle.ignite # => true
200
+ vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>
201
201
  vehicle.parked? # => false
202
202
  vehicle.idling? # => true
203
203
  vehicle.speed # => 10
204
204
  vehicle # => #<Vehicle:0xb7cf4eac @state="idling", @seatbelt_on=true>
205
205
 
206
- vehicle.shift_up # => true
206
+ vehicle.shift_up # => #<StateMachines::Transition attribute=:state event=:shift_up from="idling" from_name=:idling to="first_gear" to_name=:first_gear>
207
207
  vehicle.speed # => 10
208
208
  vehicle.moving? # => true
209
209
  vehicle # => #<Vehicle:0xb7cf4eac @state="first_gear", @seatbelt_on=true>
210
210
 
211
211
  # A generic event helper is available to fire without going through the event's instance method
212
- vehicle.fire_state_event(:shift_up) # => true
212
+ vehicle.fire_state_event(:shift_up) # => #<StateMachines::Transition attribute=:state event=:shift_up ...>
213
213
 
214
214
  # Call state-driven behavior that's undefined for the state raises a NoMethodError
215
215
  vehicle.speed # => NoMethodError: super: no superclass method `speed' for #<Vehicle:0xb7cf4eac>
@@ -223,7 +223,7 @@ vehicle.state?(:parked) # => false
223
223
  vehicle.state?(:invalid) # => IndexError: :invalid is an invalid name
224
224
 
225
225
  # Transition callbacks can receive arguments
226
- vehicle.park(meter_number: '12345') # => true
226
+ vehicle.park(meter_number: '12345') # => #<StateMachines::Transition attribute=:state event=:park ...>
227
227
  vehicle.parked? # => true
228
228
  vehicle.parking_meter_number # => "12345"
229
229
 
@@ -232,7 +232,7 @@ vehicle.alarm_state # => 1
232
232
  vehicle.alarm_state_name # => :active
233
233
 
234
234
  vehicle.can_disable_alarm? # => true
235
- vehicle.disable_alarm # => true
235
+ vehicle.disable_alarm # => #<StateMachines::Transition attribute=:alarm_state event=:disable ...>
236
236
  vehicle.alarm_state # => 0
237
237
  vehicle.alarm_state_name # => :off
238
238
  vehicle.can_enable_alarm? # => true
@@ -246,6 +246,102 @@ vehicle.state_name # => :first_gear
246
246
  vehicle.alarm_state_name # => :active
247
247
 
248
248
  vehicle.fire_events!(:ignite, :enable_alarm) # => StateMachines:InvalidParallelTransition: Cannot run events in parallel: ignite, enable_alarm
249
+ ```
250
+
251
+ ## Refusal Reasons
252
+
253
+ An event method returns the performed `StateMachines::Transition` on success and
254
+ `false` when the event is refused, so `if vehicle.ignite` keeps working. (Compare
255
+ with `if`, not `== true`.) To tell *why* it was refused, every event gets a
256
+ `<event>_refusal` reader next to `can_<event>?`, `<event>_transition` and
257
+ `<event>!`. It returns the reason of the most recent attempt to fire that event
258
+ on that object, or `nil` once an attempt succeeds:
259
+
260
+ | Reason | Meaning |
261
+ |------------------|--------------------------------------------------------------------------|
262
+ | `:no_transition` | No transition is defined for the event from the current state |
263
+ | `:guard` | A transition from the current state exists, but its `if:`/`unless:` (or state guards) rejected it |
264
+ | `:halted` | A `before_transition` or `around_transition` callback halted it |
265
+ | `:action_failed` | The machine's action (e.g. `save`) did not succeed |
266
+ | `:contended` | Async mode only: a concurrent transition held or moved the attribute first |
267
+
268
+ ```ruby
269
+ vehicle = Vehicle.new # parked
270
+ vehicle.ignite_refusal # => nil (never refused)
271
+
272
+ vehicle.park # => false
273
+ vehicle.park_refusal # => :no_transition
274
+
275
+ vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
276
+ vehicle.ignite_refusal # => nil
277
+
278
+ # The bang method raises with the same reason
279
+ begin
280
+ vehicle.park!
281
+ rescue StateMachines::InvalidTransition => e
282
+ e.reason # => :no_transition
283
+ end
284
+
285
+ # A transition performed directly carries its reason too
286
+ transition = vehicle.shift_up_transition
287
+ transition.perform # => false (say a before_transition halted it)
288
+ transition.refusal # => :halted
289
+ vehicle.shift_up_refusal # => :halted
290
+ ```
291
+
292
+ The reason is kept per event and per object, so firing another event does not
293
+ overwrite it. The guard conditions are not evaluated a second time to tell
294
+ `:guard` from `:no_transition`.
295
+
296
+ Parallel events report a reason only for the events that caused the refusal; the
297
+ others read `nil`. An action failure is shared, so every event in the set reports
298
+ `:action_failed`:
299
+
300
+ ```ruby
301
+ vehicle.fire_events(:ignite, :enable_alarm) # => false
302
+ vehicle.ignite_refusal # => :no_transition
303
+ vehicle.enable_alarm_refusal # => nil
304
+
305
+ begin
306
+ vehicle.fire_events!(:ignite, :enable_alarm)
307
+ rescue StateMachines::InvalidParallelTransition => e
308
+ e.reasons # => {ignite: :no_transition}
309
+ end
310
+ ```
311
+
312
+ When the action fails because an event attribute it runs was refused (the ORM
313
+ integrations perform `state_event` / `alarm_state_event` inside `save`), the
314
+ fired event carries that inner reason, matching the bang method's message:
315
+ an `alarm_state_event` halted inside `save` makes `ignite` read `:halted`. A
316
+ plain action failure (`save` returning false, a failed validation) stays
317
+ `:action_failed`.
318
+
319
+ Every attempt replaces the previous reason, including one that ends in an
320
+ exception: a success whose `after_transition` raises, or a callback or guard
321
+ that raises before any outcome, leaves the reader at `nil`. (An action that
322
+ raises is `:action_failed`.)
323
+
324
+ A copy made with `dup` or `clone` starts with no reasons, since it has made no
325
+ attempts. A frozen object records nothing: the event still returns `false`, and
326
+ the reader returns `nil`.
327
+
328
+ The reader reports the most recent attempt **on the object**, not on the
329
+ caller. When several threads or fibers fire events on the same object
330
+ concurrently, another caller may overwrite the reason between your attempt and
331
+ your read. Use the bang method and rescue `StateMachines::InvalidTransition`,
332
+ whose `#reason` belongs to that call, or `StateMachines::Transition#refusal` on a
333
+ transition you performed yourself:
334
+
335
+ ```ruby
336
+ begin
337
+ vehicle.ignite!
338
+ rescue StateMachines::InvalidTransition => e
339
+ e.reason # => this call's reason, e.g. :contended
340
+ end
341
+ ```
342
+
343
+ The reader is also available on the event itself:
344
+ `Vehicle.state_machine.events[:park].refusal(vehicle)`.
249
345
 
250
346
  # Coordinated State Management
251
347
 
@@ -287,7 +383,7 @@ system = TorpedoSystem.new
287
383
  system.fire_torpedo # => false (bay doors are closed)
288
384
 
289
385
  system.open_bay_doors!
290
- system.fire_torpedo # => true (bay doors are now open)
386
+ system.fire_torpedo # => #<StateMachines::Transition ...> (bay doors are now open)
291
387
  ```
292
388
 
293
389
  ### Multiple State Guards
@@ -319,15 +415,25 @@ end
319
415
 
320
416
  ## Error Handling
321
417
 
322
- State guards provide comprehensive error checking:
418
+ A state guard must be a non-empty Hash of state machine name => state name; anything else raises
419
+ `ArgumentError` when the transition is defined.
420
+
421
+ Machine and state names are resolved when the guard is evaluated (the referenced machine may be
422
+ defined later in the class), so typos raise `ArgumentError` on the first `can_*?`/fire call:
323
423
 
324
424
  ```ruby
425
+ # Wrong shape - raises at definition time
426
+ transition green: :red, if_state: :shields
427
+ # => ArgumentError: :if_state must be a non-empty Hash of state machine name => state name, got :shields
428
+
325
429
  # Referencing a non-existent state machine
326
- event :invalid, if_state: { nonexistent_machine: :some_state }
430
+ transition green: :red, if_state: { nonexistent_machine: :some_state }
431
+ StarshipBridge.new.can_red_alert?
327
432
  # => ArgumentError: State machine 'nonexistent_machine' is not defined for StarshipBridge
328
433
 
329
434
  # Referencing a non-existent state
330
- event :another_invalid, if_state: { shields: :nonexistent_state }
435
+ transition green: :red, if_state: { shields: :nonexistent_state }
436
+ StarshipBridge.new.can_red_alert?
331
437
  # => ArgumentError: State 'nonexistent_state' is not defined in state machine 'shields'
332
438
  ```
333
439
 
@@ -340,7 +446,7 @@ This feature is powered by the [async](https://github.com/socketry/async) gem an
340
446
  ## Platform Compatibility
341
447
 
342
448
  **Supported Platforms:**
343
- * MRI Ruby (CRuby) 3.2+
449
+ * MRI Ruby (CRuby) 3.4+
344
450
  * Other Ruby engines with full Fiber scheduler support
345
451
 
346
452
  **Unsupported Platforms:**
@@ -395,7 +501,7 @@ drone = AutonomousDrone.new
395
501
  Async do
396
502
  # Async event firing - returns Async::Task
397
503
  task = drone.launch_async
398
- result = task.wait # => true
504
+ result = task.wait # => #<StateMachines::Transition ...>
399
505
 
400
506
  # Bang methods for strict error handling
401
507
  drone.power_up_async! # => Async::Task (raises on failure)
@@ -447,6 +553,7 @@ end
447
553
 
448
554
  *Note: These gems are only installed on supported platforms. JRuby/TruffleRuby won't attempt installation.*
449
555
 
556
+ ```ruby
450
557
  # Human-friendly names can be accessed for states/events
451
558
  Vehicle.human_state_name(:first_gear) # => "first gear"
452
559
  Vehicle.human_alarm_state_name(:active) # => "active"
@@ -616,6 +723,37 @@ machine = Vehicle.state_machine(:state)
616
723
  assert_after_transition(machine, on: :crash, do: :tow)
617
724
  ```
618
725
 
726
+ #### Refusal Reason Assertions
727
+
728
+ Assert *why* an event was refused (see [Refusal Reasons](#refusal-reasons)). Reasons are
729
+ validated against `:no_transition`, `:guard`, `:halted`, `:action_failed` and `:contended`, so a
730
+ typo raises `ArgumentError` instead of reporting a bogus refusal:
731
+
732
+ ```ruby
733
+ # Fires the non-bang event: it must return false and leave the state unchanged
734
+ assert_sm_refused(vehicle, :park) # Any reason; returns the reason
735
+ assert_sm_refused(vehicle, :ignite, :guard) # Specific reason
736
+
737
+ # Reads the most recent refusal without firing
738
+ vehicle.park
739
+ assert_sm_refusal(vehicle, :park, :no_transition)
740
+ vehicle.ignite
741
+ refute_sm_refusal(vehicle, :ignite) # Nil after a success
742
+
743
+ # The bang raises StateMachines::InvalidTransition with that #reason (returns the error)
744
+ assert_sm_raises_refusal(vehicle, :park, :no_transition)
745
+
746
+ # fire_events returns false and fire_events! raises InvalidParallelTransition with these #reasons
747
+ assert_sm_parallel_refused(vehicle, %i[park enable_alarm], { park: :no_transition })
748
+
749
+ # Namespaced machines accept the plain or the qualified event name
750
+ assert_sm_refusal(vehicle, :enable, :guard, machine_name: :alarm_state)
751
+ assert_sm_refusal(vehicle, :enable_alarm, :guard, machine_name: :alarm_state)
752
+ ```
753
+
754
+ RSpec-style aliases: `expect_to_be_refused`, `expect_refusal`, `expect_no_refusal`,
755
+ `expect_to_raise_refusal`, `expect_parallel_refused`.
756
+
619
757
  #### Multiple State Machine Support
620
758
 
621
759
  The TestHelper fully supports objects with multiple state machines:
@@ -685,7 +823,7 @@ method like so:
685
823
 
686
824
  ```ruby
687
825
  vehicle = Vehicle.create # => #<Vehicle id=1 state="parked">
688
- vehicle.ignite # => true
826
+ vehicle.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
689
827
  vehicle.state # => "idling"
690
828
  ```
691
829
 
@@ -986,7 +1124,7 @@ end
986
1124
 
987
1125
  vehicle = Vehicle.new # => #<Vehicle:0xb708412c @state="parked" ...>
988
1126
  vehicle.state # => "parked"
989
- vehicle.machine.ignite # => true
1127
+ vehicle.machine.ignite # => #<StateMachines::Transition attribute=:state event=:ignite ...>
990
1128
  vehicle.machine.state # => "idling"
991
1129
  vehicle.state # => "idling"
992
1130
  vehicle.machine.state_transitions # => [#<StateMachines:Transition ...>]
@@ -1001,7 +1139,7 @@ transitions.
1001
1139
 
1002
1140
  Ruby versions officially supported and tested:
1003
1141
 
1004
- * Ruby (MRI) 3.0.0+
1142
+ * Ruby (MRI) 3.4+
1005
1143
 
1006
1144
  For graphing state machine:
1007
1145
 
@@ -5,7 +5,7 @@ module StateMachines
5
5
  # Extensions to Event class for async bang methods
6
6
  module AsyncEventExtensions
7
7
  # Generate async bang methods for events when async mode is enabled
8
- def define_helper(scope, method, *args, &block)
8
+ def define_helper(scope, method, *args, &)
9
9
  result = super
10
10
 
11
11
  # If this is an async-enabled machine and we're defining an event method
@@ -7,12 +7,14 @@ module StateMachines
7
7
  # Fires an event asynchronously using Async
8
8
  # Returns an Async::Task that can be awaited for the result
9
9
  #
10
- # Example:
10
+ # @return [Async::Task] a task whose result is the performed
11
+ # {StateMachines::Transition}, or false if the event was refused
12
+ # @example
11
13
  # Async do
12
14
  # task = vehicle.async_fire_event(:ignite)
13
- # result = task.wait # => true/false
15
+ # result = task.wait # => #<StateMachines::Transition ...> or false
14
16
  # end
15
- def async_fire_event(event_name, *args)
17
+ def async_fire_event(event_name, *)
16
18
  # Find the machine that has this event
17
19
  machine = self.class.state_machines.values.find { |m| m.events[event_name] }
18
20
 
@@ -26,17 +28,19 @@ module StateMachines
26
28
  end
27
29
 
28
30
  Async do
29
- machine.events[event_name].fire(self, *args)
31
+ machine.events[event_name].fire(self, *)
30
32
  end
31
33
  end
32
34
 
33
35
  # Fires multiple events asynchronously across different state machines
34
36
  # Returns an array of Async::Tasks for concurrent execution
35
37
  #
36
- # Example:
38
+ # @return [Array<Async::Task>] one task per event, each resolving to the
39
+ # performed {StateMachines::Transition} or false
40
+ # @example
37
41
  # Async do
38
42
  # tasks = vehicle.async_fire_events(:ignite, :buy_insurance)
39
- # results = tasks.map(&:wait) # => [true, true]
43
+ # results = tasks.map(&:wait) # => [#<StateMachines::Transition ...>, #<StateMachines::Transition ...>]
40
44
  # end
41
45
  def async_fire_events(*event_names)
42
46
  event_names.map { |event_name| async_fire_event(event_name) }
@@ -45,9 +49,11 @@ module StateMachines
45
49
  # Fires an event asynchronously and waits for completion
46
50
  # This is a convenience method that creates and waits for the task
47
51
  #
48
- # Example:
49
- # result = vehicle.fire_event_async(:ignite) # => true/false
50
- def fire_event_async(event_name, *args)
52
+ # @return [StateMachines::Transition, false] the performed transition, or
53
+ # false if the event was refused
54
+ # @example
55
+ # result = vehicle.fire_event_async(:ignite) # => #<StateMachines::Transition ...> or false
56
+ def fire_event_async(event_name, *)
51
57
  raise NoMethodError, "undefined method `fire_event_async' for #{self}" unless has_async_machines?
52
58
  # Find the machine that has this event
53
59
  machine = self.class.state_machines.values.find { |m| m.events[event_name] }
@@ -58,11 +64,11 @@ module StateMachines
58
64
 
59
65
  if defined?(::Async::Task) && ::Async::Task.current?
60
66
  # Already in async context, just fire directly
61
- machine.events[event_name].fire(self, *args)
67
+ machine.events[event_name].fire(self, *)
62
68
  else
63
69
  # Create async context and wait for result
64
70
  Async do
65
- machine.events[event_name].fire(self, *args)
71
+ machine.events[event_name].fire(self, *)
66
72
  end.wait
67
73
  end
68
74
  end
@@ -70,8 +76,10 @@ module StateMachines
70
76
  # Fires multiple events asynchronously and waits for all completions
71
77
  # Returns results in the same order as the input events
72
78
  #
73
- # Example:
74
- # results = vehicle.fire_events_async(:ignite, :buy_insurance) # => [true, true]
79
+ # @return [Array<StateMachines::Transition, false>] the performed
80
+ # transition (or false) for each event, in input order
81
+ # @example
82
+ # results = vehicle.fire_events_async(:ignite, :buy_insurance) # => [#<StateMachines::Transition ...>, #<StateMachines::Transition ...>]
75
83
  def fire_events_async(*event_names)
76
84
  raise NoMethodError, "undefined method `fire_events_async' for #{self}" unless has_async_machines?
77
85
  if defined?(::Async::Task) && ::Async::Task.current?
@@ -100,7 +108,7 @@ module StateMachines
100
108
  # puts "Transition failed: #{e.message}"
101
109
  # end
102
110
  # end
103
- def async_fire_event!(event_name, *args)
111
+ def async_fire_event!(event_name, *)
104
112
  # Find the machine that has this event
105
113
  machine = self.class.state_machines.values.find { |m| m.events[event_name] }
106
114
 
@@ -114,8 +122,7 @@ module StateMachines
114
122
  end
115
123
 
116
124
  Async do
117
- # Use the bang version which raises exceptions on failure
118
- machine.events[event_name].fire(self, *args) || raise(StateMachines::InvalidTransition.new(self, machine, event_name))
125
+ fire_with_bang(machine, event_name, *)
119
126
  end
120
127
  end
121
128
 
@@ -129,7 +136,7 @@ module StateMachines
129
136
  # rescue StateMachines::InvalidTransition => e
130
137
  # puts "Transition failed: #{e.message}"
131
138
  # end
132
- def fire_event_async!(event_name, *args)
139
+ def fire_event_async!(event_name, *)
133
140
  raise NoMethodError, "undefined method `fire_event_async!' for #{self}" unless has_async_machines?
134
141
  # Find the machine that has this event
135
142
  machine = self.class.state_machines.values.find { |m| m.events[event_name] }
@@ -140,18 +147,18 @@ module StateMachines
140
147
 
141
148
  if defined?(::Async::Task) && ::Async::Task.current?
142
149
  # Already in async context, just fire directly with bang behavior
143
- machine.events[event_name].fire(self, *args) || raise(StateMachines::InvalidTransition.new(self, machine, event_name))
150
+ fire_with_bang(machine, event_name, *)
144
151
  else
145
152
  # Create async context and wait for result (may raise exception)
146
153
  Async do
147
- machine.events[event_name].fire(self, *args) || raise(StateMachines::InvalidTransition.new(self, machine, event_name))
154
+ fire_with_bang(machine, event_name, *)
148
155
  end.wait
149
156
  end
150
157
  end
151
158
 
152
159
  # Dynamically handle individual event async methods
153
160
  # This provides launch_async, launch_async!, arm_weapons_async, etc.
154
- def method_missing(method_name, *args, **kwargs, &block)
161
+ def method_missing(method_name, *, **, &)
155
162
  method_str = method_name.to_s
156
163
 
157
164
  # Check if this is an async event method
@@ -161,7 +168,7 @@ module StateMachines
161
168
 
162
169
  # Check if the base method exists and this machine is async-enabled
163
170
  if respond_to?(base_method) && async_method_for_event?(base_method)
164
- return handle_individual_event_async_bang(base_method, *args, **kwargs)
171
+ return handle_individual_event_async_bang(base_method, *, **)
165
172
  end
166
173
  elsif method_str.end_with?('_async')
167
174
  # Remove the _async suffix to get the base event method
@@ -169,7 +176,7 @@ module StateMachines
169
176
 
170
177
  # Check if the base method exists and this machine is async-enabled
171
178
  if respond_to?(base_method) && async_method_for_event?(base_method)
172
- return handle_individual_event_async(base_method, *args, **kwargs)
179
+ return handle_individual_event_async(base_method, *, **)
173
180
  end
174
181
  end
175
182
 
@@ -199,6 +206,11 @@ module StateMachines
199
206
 
200
207
  private
201
208
 
209
+ # Fires the event on the given machine, raising InvalidTransition on failure
210
+ def fire_with_bang(machine, event_name, *)
211
+ machine.events[event_name].fire(self, *) || raise(StateMachines::InvalidTransition.new(self, machine, event_name))
212
+ end
213
+
202
214
  # Check if this event method should have async versions
203
215
  def async_method_for_event?(event_method)
204
216
  # Find which machine contains this event
@@ -217,19 +229,19 @@ module StateMachines
217
229
  end
218
230
 
219
231
  # Handle individual event async methods (returns task)
220
- def handle_individual_event_async(event_method, *args, **kwargs)
232
+ def handle_individual_event_async(event_method, *, **)
221
233
 
222
234
  unless defined?(::Async::Task) && ::Async::Task.current?
223
235
  raise RuntimeError, "#{event_method}_async must be called within an Async context"
224
236
  end
225
237
 
226
238
  Async do
227
- send(event_method, *args, **kwargs)
239
+ send(event_method, *, **)
228
240
  end
229
241
  end
230
242
 
231
243
  # Handle individual event async bang methods (returns task, raises on failure)
232
- def handle_individual_event_async_bang(event_method, *args, **kwargs)
244
+ def handle_individual_event_async_bang(event_method, *, **)
233
245
  # Extract event name from method and use bang version
234
246
  bang_method = "#{event_method}!".to_sym
235
247
 
@@ -238,7 +250,7 @@ module StateMachines
238
250
  end
239
251
 
240
252
  Async do
241
- send(bang_method, *args, **kwargs)
253
+ send(bang_method, *, **)
242
254
  end
243
255
  end
244
256
 
@@ -24,13 +24,13 @@ module StateMachines
24
24
 
25
25
  # Fires an event asynchronously on the given object
26
26
  # Returns an Async::Task for concurrent execution
27
- def async_fire_event(object, event_name, *args)
27
+ def async_fire_event(object, event_name, *)
28
28
  unless defined?(::Async::Task) && ::Async::Task.current?
29
29
  raise RuntimeError, "async_fire_event must be called within an Async context"
30
30
  end
31
31
 
32
32
  Async do
33
- events[event_name].fire(object, *args)
33
+ events[event_name].fire(object, *)
34
34
  end
35
35
  end
36
36
 
@@ -16,99 +16,27 @@ 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
42
  result = yield
@@ -5,11 +5,18 @@ 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
+ # Lazily created state that is rebuilt on demand rather than marshalled
9
+ TRANSIENT_VARIABLES = [:@_state_machine_mutex, StateMachines::TransitionClaim::CLAIMS_VARIABLE].freeze
10
+
11
+ MUTEX_CREATION_LOCK = Thread::Mutex.new
12
+
8
13
  # Gets or creates a reentrant mutex for thread-safe state operations on an object
9
14
  # Each object gets its own mutex to avoid global locking
10
15
  # Uses Concurrent::ReentrantReadWriteLock for better performance
11
16
  def state_machine_mutex
12
- @_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
17
+ @_state_machine_mutex || MUTEX_CREATION_LOCK.synchronize do
18
+ @_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
19
+ end
13
20
  end
14
21
 
15
22
  # Thread-safe version of state reading
@@ -30,8 +37,7 @@ module StateMachines
30
37
 
31
38
  # Handle marshalling by excluding the mutex (will be recreated when needed)
32
39
  def marshal_dump
33
- # Get instance variables excluding the mutex
34
- vars = instance_variables.reject { |var| var == :@_state_machine_mutex }
40
+ vars = instance_variables - TRANSIENT_VARIABLES
35
41
  vars.map { |var| [var, instance_variable_get(var)] }
36
42
  end
37
43
 
@@ -40,7 +46,6 @@ module StateMachines
40
46
  data.each do |var, value|
41
47
  instance_variable_set(var, value)
42
48
  end
43
- # Don't set @_state_machine_mutex - let it be lazily created
44
49
  end
45
50
  end
46
51
  end