state_machines 0.301.1 → 0.302.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: 1fbe5b87d0377b8ca773d88116b21283e73f4001c75eb814a0d76c6206825c39
4
- data.tar.gz: dbd93191206e8be918c6ca0563209c9f29bcbc21082e4150f31c2160c1a0cd1a
3
+ metadata.gz: d47c876a9033878792c9d5e8ae2977c7619b2f8c451b92d1f8922c12179fe477
4
+ data.tar.gz: 1eaecf426befa4b880ed8500993b4e6df17ed19791e372d2266082d7d9ecf7a5
5
5
  SHA512:
6
- metadata.gz: 5b4403db39c1558e94c178ff79ef99eaf22d9a59834d7f136f06a9f752b57219716ccaf06f43e330230933c53ff8e63668514a9295b9b57042e38a20de4066cb
7
- data.tar.gz: a4e9785c78c2c0046ba15e6d04949eb46cc8112b4b5ccf9194fe971b618b94f534e58cb12099e99217c9cd3bc6d47d1f5f88f9c28af5a0f2ca0c588cf29adeef
6
+ metadata.gz: 591f02a586b9862805cde1e22e28c5e09924a00394685d15128e40aa9d535e2510c3bd9d064b34aefaaaa958f388bd135238cf1589f017e869372bbe9889053b
7
+ data.tar.gz: 22fd97f9598b4c245960d4f9df573950b64c5cdb9247142769a97db5aefb610069c12e119f70a028983b4336574c21d8041bc0127d2475ef89ae60849e36729c
data/README.md CHANGED
@@ -37,7 +37,6 @@ Below is an example of many of the features offered by this plugin, including:
37
37
  * Transition callbacks
38
38
  * Conditional transitions
39
39
  * Coordinated state management guards
40
- * Asynchronous state machines (async: true)
41
40
  * State-driven instance behavior
42
41
  * Customized state values
43
42
  * Parallel events
@@ -263,7 +262,7 @@ on that object, or `nil` once an attempt succeeds:
263
262
  | `:guard` | A transition from the current state exists, but its `if:`/`unless:` (or state guards) rejected it |
264
263
  | `:halted` | A `before_transition` or `around_transition` callback halted it |
265
264
  | `: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 |
265
+ | `:contended` | A concurrent transition held or moved the attribute first (only machines that claim their transitions, e.g. [state_machines-async](https://github.com/state-machines/state_machines-async)) |
267
266
 
268
267
  ```ruby
269
268
  vehicle = Vehicle.new # parked
@@ -447,119 +446,15 @@ StarshipBridge.new.can_red_alert?
447
446
 
448
447
  # Asynchronous State Machines
449
448
 
450
- State machines can operate asynchronously for high-performance applications. This is ideal for I/O-bound tasks, such as in web servers or other concurrent environments, where you don't want a long-running state transition (like one involving a network call) to block the entire thread.
449
+ Async mode (`state_machine ..., async: true`, `<event>_async` methods, `fire_event_async`) lives
450
+ in the [state_machines-async](https://github.com/state-machines/state_machines-async) gem. Without it
451
+ loaded, `async: true` raises `ArgumentError` naming the gem rather than being ignored.
451
452
 
452
- This feature is powered by the [async](https://github.com/socketry/async) gem and uses `concurrent-ruby` for enterprise-grade thread safety.
453
-
454
- ## Platform Compatibility
455
-
456
- **Supported Platforms:**
457
- * MRI Ruby (CRuby) 3.4+
458
- * Other Ruby engines with full Fiber scheduler support
459
-
460
- **Unsupported Platforms:**
461
- * JRuby - Falls back to synchronous mode with warnings
462
- * TruffleRuby - Falls back to synchronous mode with warnings
463
-
464
- ## Basic Async Usage
465
-
466
- Enable async mode by adding `async: true` to your state machine declaration:
467
-
468
- ```ruby
469
- class AutonomousDrone < StarfleetShip
470
- # Async-enabled state machine for autonomous operation
471
- state_machine :status, async: true, initial: :docked do
472
- event :launch do
473
- transition docked: :flying
474
- end
475
-
476
- event :land do
477
- transition flying: :docked
478
- end
479
- end
480
-
481
- # Mixed configuration: some machines async, others sync
482
- state_machine :teleporter_status, async: true, initial: :offline do
483
- event :power_up do
484
- transition offline: :charging
485
- end
486
-
487
- event :teleport do
488
- transition ready: :teleporting
489
- end
490
- end
491
-
492
- # Weapons remain synchronous for safety
493
- state_machine :weapons, initial: :disarmed do
494
- event :arm do
495
- transition disarmed: :armed
496
- end
497
- end
498
- end
499
- ```
500
-
501
- ## Async Event Methods
502
-
503
- Async-enabled machines automatically generate async versions of event methods:
504
-
505
- ```ruby
506
- drone = AutonomousDrone.new
507
-
508
- # Within an Async context
509
- Async do
510
- # Async event firing - returns Async::Task
511
- task = drone.launch_async
512
- result = task.wait # => #<StateMachines::Transition ...>
513
-
514
- # Bang methods for strict error handling
515
- drone.power_up_async! # => Async::Task (raises on failure)
516
-
517
- # Generic async event firing
518
- drone.fire_event_async(:teleport) # => Async::Task
519
- end
520
-
521
- # Outside Async context - raises error
522
- drone.launch_async # => RuntimeError: launch_async must be called within an Async context
523
- ```
524
-
525
- ## Thread Safety
526
-
527
- Async state machines use enterprise-grade thread safety with `concurrent-ruby`:
528
-
529
- ```ruby
530
- # Concurrent operations are automatically thread-safe
531
- threads = []
532
- 10.times do
533
- threads << Thread.new do
534
- Async do
535
- drone.launch_async.wait
536
- drone.land_async.wait
537
- end
538
- end
539
- end
540
- threads.each(&:join)
541
- ```
542
-
543
- ## Performance Considerations
544
-
545
- * **Thread Safety**: Uses `Concurrent::ReentrantReadWriteLock` for optimal read/write performance.
546
- * **Memory**: Each async-enabled object gets its own mutex (lazy-loaded).
547
- * **Marshalling**: Objects with async state machines can be serialized (mutex excluded/recreated).
548
- * **Mixed Mode**: You can mix async and sync state machines in the same class.
549
-
550
- ## Dependencies
551
-
552
- Async functionality requires:
553
-
554
- ```ruby
555
- # Gemfile (automatically scoped to MRI Ruby)
556
- platform :ruby do
557
- gem 'async', '>= 2.25.0'
558
- gem 'concurrent-ruby', '>= 1.3.5'
559
- end
560
- ```
561
-
562
- *Note: These gems are only installed on supported platforms. JRuby/TruffleRuby won't attempt installation.*
453
+ Extensions plug into machine hooks: `Machine#claims_transitions?` makes `TransitionCollection#perform`
454
+ claim the machine's attribute before performing (concurrent transitions out of one state then perform once,
455
+ the others are refused as `:contended`); `Machine#creation_options` / `Machine#after_definition` let a new
456
+ machine accept an extension's option (from the caller or the integration's defaults), and
457
+ `Machine#reopen_options` / `Machine#reopen` let a reopened machine accept it.
563
458
 
564
459
  ```ruby
565
460
  # Human-friendly names can be accessed for states/events
@@ -225,8 +225,10 @@ module StateMachines
225
225
  # - :halted - a before_transition or around_transition callback halted the
226
226
  # transition
227
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
228
+ # - :contended - a concurrent transition held or moved the attribute
229
+ # first; only on machines that claim their transitions (see
230
+ # {StateMachines::Machine#claims_transitions?}), such as async mode
231
+ # machines of state_machines-async
230
232
  #
231
233
  # When the event was fired in parallel with others (see
232
234
  # {StateMachines::InstanceMethods#fire_events}), only the events that caused
@@ -22,9 +22,9 @@ 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
25
+ # Per-object concurrency state, created on demand: the transition claims.
26
+ # Never copied (see #initialize_copy).
27
+ TRANSIENT_VARIABLES = %i[@_state_machine_transition_claims].freeze
28
28
 
29
29
  # Runs one or more events in parallel. All events will run through the
30
30
  # following steps:
@@ -147,8 +147,8 @@ module StateMachines
147
147
 
148
148
  # A copy (+dup+ / +clone+) has made no attempt to fire an event, so it
149
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.
150
+ # also gets its own transition claims (created on demand) instead of
151
+ # sharing the original's.
152
152
  #
153
153
  # A class defining its own +initialize_copy+ must call +super+.
154
154
  #
@@ -3,9 +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
6
+ # Machine options that an extension gem provides, mapped to that gem.
7
+ # A loaded extension consumes its option before the core validates the
8
+ # options, so the core meeting one means the gem is not loaded.
9
+ EXTENSION_OPTIONS = { async: 'state_machines-async' }.freeze
9
10
 
10
11
  # Attempts to find or create a state machine for the given class. For
11
12
  # example,
@@ -19,7 +20,8 @@ module StateMachines
19
20
  # superclasses, then a copy of that machine will be created and stored
20
21
  # in the new owner class (the original will remain unchanged).
21
22
  #
22
- # Reopening an existing machine applies +:initial+ and +:async+;
23
+ # Reopening an existing machine applies the options in
24
+ # Machine#reopen_options (+:initial+, plus any a loaded extension adds);
23
25
  # any other option raises ArgumentError instead of being ignored.
24
26
  def find_or_create(owner_class, *args, &)
25
27
  options = args.last.is_a?(Hash) ? args.pop : {}
@@ -31,10 +33,12 @@ module StateMachines
31
33
  owner_class.state_machines.values.first))) || nil
32
34
 
33
35
  if machine
34
- unsupported = options.keys - REOPEN_OPTIONS
36
+ reopenable = machine.reopen_options
37
+ unsupported = options.keys - reopenable
38
+ assert_extensions_loaded!(unsupported)
35
39
  unless unsupported.empty?
36
40
  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"
41
+ "#{name.inspect} on #{owner_class}; reopening it accepts only #{reopenable.map(&:inspect).join(', ')}"
38
42
  end
39
43
 
40
44
  # Only create a new copy if changes are being made to the machine in
@@ -43,8 +47,7 @@ module StateMachines
43
47
  machine = machine.clone
44
48
  machine.owner_class = owner_class
45
49
  end
46
- machine.initial_state = options[:initial] if options.include?(:initial)
47
- machine.configure_async_mode!(options[:async]) if options.include?(:async)
50
+ machine.reopen(options)
48
51
 
49
52
  # Evaluate DSL
50
53
  machine.instance_eval(&) if block_given?
@@ -60,6 +63,22 @@ module StateMachines
60
63
  raise NotImplementedError
61
64
  end
62
65
 
66
+ # Raises ArgumentError naming the gem when +keys+ holds an option of
67
+ # EXTENSION_OPTIONS, whose gem is then not loaded, so that the option is
68
+ # neither ignored nor reported as merely unknown.
69
+ #
70
+ # @api private
71
+ # @param keys [Array<Symbol>] option names the core does not accept
72
+ # @return [void]
73
+ def assert_extensions_loaded!(keys)
74
+ option = keys.find { |key| EXTENSION_OPTIONS.key?(key) }
75
+ return unless option
76
+
77
+ gem_name = EXTENSION_OPTIONS.fetch(option)
78
+ raise ArgumentError, "The #{option.inspect} state machine option is provided by the #{gem_name} gem, " \
79
+ "which is not loaded; add it to your Gemfile and require '#{gem_name}'"
80
+ end
81
+
63
82
  # Default messages to use for validation errors in ORM integrations
64
83
  # Thread-safe access via atomic operations on simple values
65
84
  attr_accessor :ignore_method_conflicts
@@ -15,14 +15,17 @@ module StateMachines
15
15
  end
16
16
 
17
17
  # Validate options including integration-specific options
18
- valid_keys = %i[attribute initial initialize action plural namespace integration messages use_transactions async]
18
+ valid_keys = creation_options
19
19
  valid_keys += @integration.integration_options if @integration
20
+ self.class.assert_extensions_loaded!(options.keys - valid_keys)
20
21
  StateMachines::OptionsValidator.assert_valid_keys!(options, valid_keys)
21
22
 
22
23
  if @integration
23
24
  extend @integration
24
25
 
25
26
  options = (@integration.defaults || {}).merge(options)
27
+ # An integration default can supply an extension's option too
28
+ self.class.assert_extensions_loaded!(options.keys - valid_keys)
26
29
  end
27
30
 
28
31
  # Add machine-wide defaults
@@ -40,7 +43,6 @@ module StateMachines
40
43
  @use_transactions = options[:use_transactions]
41
44
  @initialize_state = options[:initialize]
42
45
  @action_hook_defined = false
43
- @async_requested = options[:async]
44
46
  @integration_options = @integration ? options.slice(*@integration.integration_options).freeze : {}.freeze
45
47
 
46
48
  self.owner_class = owner_class
@@ -56,8 +58,7 @@ module StateMachines
56
58
  # Evaluate DSL
57
59
  instance_eval(&) if block_given?
58
60
 
59
- # Configure async mode if requested, after owner_class is set and DSL is evaluated
60
- configure_async_mode!(true) if @async_requested
61
+ after_definition(options)
61
62
 
62
63
  self.initial_state = options[:initial] unless sibling_machines.any?
63
64
  end
@@ -73,8 +74,6 @@ module StateMachines
73
74
  @states = @states.dup
74
75
  @states.machine = self
75
76
  @callbacks = { before: @callbacks[:before].dup, after: @callbacks[:after].dup, failure: @callbacks[:failure].dup }
76
- @async_requested = orig.instance_variable_get(:@async_requested)
77
- @async_mode_enabled = orig.instance_variable_get(:@async_mode_enabled)
78
77
  end
79
78
 
80
79
  # Sets the class which is the owner of this state machine. Any methods
@@ -14,7 +14,6 @@ require_relative 'machine/event_methods'
14
14
  require_relative 'machine/callbacks'
15
15
  require_relative 'machine/rendering'
16
16
  require_relative 'machine/integration'
17
- require_relative 'machine/async_extensions'
18
17
  require_relative 'syntax_validator'
19
18
 
20
19
  module StateMachines
@@ -597,11 +596,65 @@ module StateMachines
597
596
  @action_hook_defined || (!self_only && owner_class.state_machines.any? { |_name, machine| machine.action == action && machine != self && machine.action_hook?(true) })
598
597
  end
599
598
 
599
+ # Whether objects may perform this machine's transitions concurrently, from
600
+ # several threads or fibers at once. When true,
601
+ # TransitionCollection#perform claims the machine's attribute on the
602
+ # object before performing (see StateMachines::TransitionClaim), so of
603
+ # concurrent transitions out of one state only the first is performed and
604
+ # the others are refused as :contended.
605
+ #
606
+ # The core's machines do not claim. An extension that performs
607
+ # transitions concurrently overrides this, as state_machines-async does
608
+ # for the machines it runs in async mode.
609
+ #
610
+ # @return [Boolean]
611
+ def claims_transitions?
612
+ false
613
+ end
614
+
615
+ # The options a new machine accepts, besides its integration's
616
+ # (StateMachines::Integrations::Base::ClassMethods#integration_options).
617
+ # An extension adding an option appends it here and applies it in
618
+ # #after_definition.
619
+ #
620
+ # @return [Array<Symbol>]
621
+ def creation_options
622
+ %i[attribute initial initialize action plural namespace integration messages use_transactions]
623
+ end
624
+
625
+ # The options a reopened machine accepts (see
626
+ # StateMachines::Machine.find_or_create); the others only apply when it is
627
+ # created. An extension adding a reopenable option appends it here and
628
+ # applies it in #reopen.
629
+ #
630
+ # @return [Array<Symbol>]
631
+ def reopen_options
632
+ %i[initial]
633
+ end
634
+
635
+ # Applies the options given when this machine is reopened, before the
636
+ # reopening block is evaluated.
637
+ #
638
+ # @param options [Hash] the options, limited to #reopen_options
639
+ # @return [void]
640
+ def reopen(options)
641
+ self.initial_state = options[:initial] if options.include?(:initial)
642
+ end
643
+
600
644
  protected
601
645
 
602
646
  # Runs additional initialization hooks. By default, this is a no-op.
603
647
  def after_initialize; end
604
648
 
649
+ # Runs once a new machine's definition block has been evaluated, before
650
+ # its initial state is set, with its options: the caller's merged over
651
+ # the integration's defaults. By default, this is a no-op; an extension
652
+ # applies its #creation_options here.
653
+ #
654
+ # @param _options [Hash] the machine's options
655
+ # @return [void]
656
+ def after_definition(_options); end
657
+
605
658
  # Always yields
606
659
  def transaction(_object)
607
660
  yield
@@ -346,72 +346,9 @@ module StateMachines
346
346
  _assert_transition_callback(:after, machine_or_class, options, message)
347
347
  end
348
348
 
349
- # === Sync Mode Assertions ===
349
+ # === Execution Assertions ===
350
350
 
351
- # Assert that a state machine is operating in synchronous mode
352
- #
353
- # @param object [Object] The object with state machines
354
- # @param machine_name [Symbol] The name of the state machine (defaults to :state)
355
- # @param message [String, nil] Custom failure message
356
- # @return [void]
357
- # @raise [AssertionError] If the machine has async mode enabled
358
- #
359
- # @example
360
- # user = User.new
361
- # assert_sm_sync_mode(user) # Uses default :state machine
362
- # assert_sm_sync_mode(user, :status) # Uses :status machine
363
- def assert_sm_sync_mode(object, machine_name = :state, message = nil)
364
- machine = object.class.state_machines[machine_name]
365
- raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
366
-
367
- async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
368
- default_message = "Expected state machine '#{machine_name}' to be in sync mode, but async mode is enabled"
369
-
370
- _sm_refute(async_enabled, message || default_message)
371
- end
372
-
373
- # Assert that async methods are not available on a sync-only object
374
- #
375
- # @param object [Object] The object with state machines
376
- # @param message [String, nil] Custom failure message
377
- # @return [void]
378
- # @raise [AssertionError] If async methods are available
379
- #
380
- # @example
381
- # sync_only_car = Car.new # Car has no async: true machines
382
- # assert_sm_no_async_methods(sync_only_car)
383
- def assert_sm_no_async_methods(object, message = nil)
384
- async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
385
- available_async_methods = async_methods.select { |method| object.respond_to?(method) }
386
-
387
- default_message = "Expected no async methods to be available, but found: #{available_async_methods.inspect}"
388
-
389
- _sm_assert_empty(available_async_methods, message || default_message)
390
- end
391
-
392
- # Assert that an object has no async-enabled state machines
393
- #
394
- # @param object [Object] The object with state machines
395
- # @param message [String, nil] Custom failure message
396
- # @return [void]
397
- # @raise [AssertionError] If any machine has async mode enabled
398
- #
399
- # @example
400
- # sync_only_vehicle = Vehicle.new # All machines are sync-only
401
- # assert_sm_all_sync(sync_only_vehicle)
402
- def assert_sm_all_sync(object, message = nil)
403
- async_machines = []
404
-
405
- object.class.state_machines.each do |name, machine|
406
- async_machines << name if machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
407
- end
408
-
409
- default_message = "Expected all state machines to be sync-only, but these have async enabled: #{async_machines.inspect}"
410
-
411
- _sm_assert_empty(async_machines, message || default_message)
412
- end
413
-
414
- # Assert that synchronous event execution works correctly
351
+ # Assert that firing a bang event transitions to the expected state
415
352
  #
416
353
  # @param object [Object] The object with state machines
417
354
  # @param event [Symbol] The event to trigger
@@ -432,7 +369,7 @@ module StateMachines
432
369
  # Execute event synchronously
433
370
  result = object.send("#{event}!")
434
371
 
435
- # Verify immediate state change (no async delay)
372
+ # Verify the state changed by the time the event returned
436
373
  final_state = object.send(machine_name)
437
374
 
438
375
  # Check that transition succeeded
@@ -446,154 +383,30 @@ module StateMachines
446
383
  _sm_assert(correct_final_state, message || default_message)
447
384
  end
448
385
 
449
- # Assert that event execution is immediate (no async delay)
386
+ # Assert that event execution is immediate: the state has changed when the
387
+ # bang event returns, and it returned the performed transition rather than
388
+ # something to wait on. Decided by what the call did, not by how long it
389
+ # took, so a slow runner (a cold JIT) cannot fail it.
450
390
  #
451
391
  # @param object [Object] The object with state machines
452
392
  # @param event [Symbol] The event to trigger
453
393
  # @param machine_name [Symbol] The name of the state machine (defaults to :state)
454
394
  # @param message [String, nil] Custom failure message
455
395
  # @return [void]
456
- # @raise [AssertionError] If execution appears to be async
396
+ # @raise [AssertionError] If the event did not complete before returning
457
397
  #
458
398
  # @example
459
399
  # car = Car.new
460
400
  # assert_sm_immediate_execution(car, :start)
461
401
  def assert_sm_immediate_execution(object, event, machine_name = :state, message = nil)
462
402
  initial_state = object.send(machine_name)
463
-
464
- # Record start time and execute
465
- start_time = Time.now
466
- object.send("#{event}!")
467
- execution_time = Time.now - start_time
468
-
403
+ result = object.send("#{event}!")
469
404
  final_state = object.send(machine_name)
470
- state_changed = initial_state != final_state
471
-
472
- # Should complete very quickly (under 10ms for sync operations)
473
- is_immediate = execution_time < 0.01
474
-
475
- default_message = "Expected immediate sync execution of '#{event}', but took #{execution_time}s (likely async)"
476
-
477
- _sm_assert(state_changed, 'Event should trigger state change')
478
- _sm_assert(is_immediate, message || default_message)
479
- end
480
-
481
- # === Async Mode Assertions ===
482
-
483
- # Assert that a state machine is operating in asynchronous mode
484
- #
485
- # @param object [Object] The object with state machines
486
- # @param machine_name [Symbol] The name of the state machine (defaults to :state)
487
- # @param message [String, nil] Custom failure message
488
- # @return [void]
489
- # @raise [AssertionError] If the machine doesn't have async mode enabled
490
- #
491
- # @example
492
- # drone = AutonomousDrone.new
493
- # assert_sm_async_mode(drone) # Uses default :state machine
494
- # assert_sm_async_mode(drone, :teleporter_status) # Uses :teleporter_status machine
495
- def assert_sm_async_mode(object, machine_name = :state, message = nil)
496
- machine = object.class.state_machines[machine_name]
497
- raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
498
-
499
- async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
500
- default_message = "Expected state machine '#{machine_name}' to have async mode enabled, but it's in sync mode"
501
-
502
- _sm_assert(async_enabled, message || default_message)
503
- end
504
-
505
- # Assert that async methods are available on an async-enabled object
506
- #
507
- # @param object [Object] The object with state machines
508
- # @param message [String, nil] Custom failure message
509
- # @return [void]
510
- # @raise [AssertionError] If async methods are not available
511
- #
512
- # @example
513
- # drone = AutonomousDrone.new # Has async: true machines
514
- # assert_sm_async_methods(drone)
515
- def assert_sm_async_methods(object, message = nil)
516
- async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
517
- available_async_methods = async_methods.select { |method| object.respond_to?(method) }
518
-
519
- default_message = 'Expected async methods to be available, but found none'
520
-
521
- _sm_refute_empty(available_async_methods, message || default_message)
522
- end
523
-
524
- # Assert that an object has async-enabled state machines
525
- #
526
- # @param object [Object] The object with state machines
527
- # @param machine_names [Array<Symbol>] Expected async machine names
528
- # @param message [String, nil] Custom failure message
529
- # @return [void]
530
- # @raise [AssertionError] If expected machines don't have async mode
531
- #
532
- # @example
533
- # drone = AutonomousDrone.new
534
- # assert_sm_has_async(drone, [:status, :teleporter_status, :shields])
535
- def assert_sm_has_async(object, machine_names = nil, message = nil)
536
- if machine_names
537
- # Check specific machines
538
- non_async_machines = machine_names.reject do |name|
539
- machine = object.class.state_machines[name]
540
- machine&.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
541
- end
542
-
543
- default_message = "Expected machines #{machine_names.inspect} to have async enabled, but these don't: #{non_async_machines.inspect}"
544
-
545
- _sm_assert_empty(non_async_machines, message || default_message)
546
- else
547
- # Check that at least one machine has async
548
- async_machines = object.class.state_machines.select do |_name, machine|
549
- machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
550
- end
551
-
552
- default_message = 'Expected at least one state machine to have async enabled, but none found'
553
-
554
- _sm_refute_empty(async_machines, message || default_message)
555
- end
556
- end
557
-
558
- # Assert that individual async event methods are available
559
- #
560
- # @param object [Object] The object with state machines
561
- # @param event [Symbol] The event name
562
- # @param message [String, nil] Custom failure message
563
- # @return [void]
564
- # @raise [AssertionError] If async event methods are not available
565
- #
566
- # @example
567
- # drone = AutonomousDrone.new
568
- # assert_sm_async_event_methods(drone, :launch) # Checks launch_async and launch_async!
569
- def assert_sm_async_event_methods(object, event, message = nil)
570
- async_method = :"#{event}_async"
571
- async_bang_method = :"#{event}_async!"
572
-
573
- has_async = object.respond_to?(async_method)
574
- has_async_bang = object.respond_to?(async_bang_method)
575
-
576
- _sm_assert(has_async, message || "Missing #{async_method} method")
577
- _sm_assert(has_async_bang, message || "Missing #{async_bang_method} method")
578
- end
579
-
580
- # Assert that an object has thread-safe state methods when async is enabled
581
- #
582
- # @param object [Object] The object with state machines
583
- # @param message [String, nil] Custom failure message
584
- # @return [void]
585
- # @raise [AssertionError] If thread-safe methods are not available
586
- #
587
- # @example
588
- # drone = AutonomousDrone.new
589
- # assert_sm_thread_safe_methods(drone)
590
- def assert_sm_thread_safe_methods(object, message = nil)
591
- thread_safe_methods = %i[state_machine_mutex read_state_safely write_state_safely]
592
- missing_methods = thread_safe_methods.reject { |method| object.respond_to?(method) }
593
405
 
594
- default_message = "Expected thread-safe methods to be available, but missing: #{missing_methods.inspect}"
406
+ default_message = "Expected immediate execution of '#{event}' to return the performed transition, but it returned #{result.class}"
595
407
 
596
- _sm_assert_empty(missing_methods, message || default_message)
408
+ _sm_assert(initial_state != final_state, message || "Event #{event} should change #{machine_name} before returning")
409
+ _sm_assert(result.is_a?(StateMachines::Transition), message || default_message)
597
410
  end
598
411
 
599
412
  # === Refusal Reason Assertions ===
@@ -26,9 +26,10 @@ module StateMachines
26
26
  LOCK = Thread::Mutex.new
27
27
 
28
28
  class << self
29
- # Claims an attribute for every given transition whose machine runs in
30
- # async mode, ordered by attribute so that collections over the same
31
- # attributes claim them in the same order.
29
+ # Claims an attribute for every given transition whose machine claims
30
+ # transitions (Machine#claims_transitions?), ordered by attribute so that
31
+ # collections over the same attributes claim them in the same order. A
32
+ # collection without such a transition is granted an empty set.
32
33
  #
33
34
  # Returns the granted claims, or nil when an attribute is held by another
34
35
  # active owner or has left the transition's source state. Every exit
@@ -41,7 +42,7 @@ module StateMachines
41
42
  # attribute could not be claimed, when the claim is refused
42
43
  # @return [Array<StateMachines::TransitionClaim>, nil]
43
44
  def claim(transitions)
44
- claimable = transitions.select { |transition| transition.machine.async_mode_enabled? }
45
+ claimable = transitions.select { |transition| transition.machine.claims_transitions? }
45
46
  granted = []
46
47
  admitted = false
47
48
 
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module StateMachines
4
- VERSION = '0.301.1'
4
+ VERSION = '0.302.0'
5
5
  end