state_machines 0.301.2 → 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: 4f3fa05a4995ba6d3ff323c8cbf7303a061bf082237353066c01b023129d4c7f
4
- data.tar.gz: c56a60d5f74f1da251670ff4f5c782d68837a6db2f2f4c200d744adebe620b7f
3
+ metadata.gz: d47c876a9033878792c9d5e8ae2977c7619b2f8c451b92d1f8922c12179fe477
4
+ data.tar.gz: 1eaecf426befa4b880ed8500993b4e6df17ed19791e372d2266082d7d9ecf7a5
5
5
  SHA512:
6
- metadata.gz: f6ef8c77f4652d1281e4b66252e0f72395efc2143180b1e91cb437ac7934ca5d9238f3e9b56c5ab3ca7ede1e3a4123fe3ffde899b02f565601b056e7477f0884
7
- data.tar.gz: 643d203b7719acd77ec70df09bd4c46b722127bf0529e3108285ac5120ea5b0269fe195e09448664cdabcf70a86232a6496ff8f33e8e4943bc64d806b00c28d6
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
@@ -447,16 +384,16 @@ module StateMachines
447
384
  end
448
385
 
449
386
  # Assert that event execution is immediate: the state has changed when the
450
- # bang event returns, and it returned no async task to wait on. Decided by
451
- # what the call did, not by how long it took, so a slow runner (a cold
452
- # JIT) cannot fail it.
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.
453
390
  #
454
391
  # @param object [Object] The object with state machines
455
392
  # @param event [Symbol] The event to trigger
456
393
  # @param machine_name [Symbol] The name of the state machine (defaults to :state)
457
394
  # @param message [String, nil] Custom failure message
458
395
  # @return [void]
459
- # @raise [AssertionError] If the event did not complete synchronously
396
+ # @raise [AssertionError] If the event did not complete before returning
460
397
  #
461
398
  # @example
462
399
  # car = Car.new
@@ -466,129 +403,10 @@ module StateMachines
466
403
  result = object.send("#{event}!")
467
404
  final_state = object.send(machine_name)
468
405
 
469
- deferred = defined?(::Async::Task) && result.is_a?(::Async::Task)
470
- default_message = "Expected immediate sync execution of '#{event}', but it returned #{result.class} (async)"
406
+ default_message = "Expected immediate execution of '#{event}' to return the performed transition, but it returned #{result.class}"
471
407
 
472
408
  _sm_assert(initial_state != final_state, message || "Event #{event} should change #{machine_name} before returning")
473
- _sm_assert(!deferred, message || default_message)
474
- end
475
-
476
- # === Async Mode Assertions ===
477
-
478
- # Assert that a state machine is operating in asynchronous mode
479
- #
480
- # @param object [Object] The object with state machines
481
- # @param machine_name [Symbol] The name of the state machine (defaults to :state)
482
- # @param message [String, nil] Custom failure message
483
- # @return [void]
484
- # @raise [AssertionError] If the machine doesn't have async mode enabled
485
- #
486
- # @example
487
- # drone = AutonomousDrone.new
488
- # assert_sm_async_mode(drone) # Uses default :state machine
489
- # assert_sm_async_mode(drone, :teleporter_status) # Uses :teleporter_status machine
490
- def assert_sm_async_mode(object, machine_name = :state, message = nil)
491
- machine = object.class.state_machines[machine_name]
492
- raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
493
-
494
- async_enabled = machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
495
- default_message = "Expected state machine '#{machine_name}' to have async mode enabled, but it's in sync mode"
496
-
497
- _sm_assert(async_enabled, message || default_message)
498
- end
499
-
500
- # Assert that async methods are available on an async-enabled object
501
- #
502
- # @param object [Object] The object with state machines
503
- # @param message [String, nil] Custom failure message
504
- # @return [void]
505
- # @raise [AssertionError] If async methods are not available
506
- #
507
- # @example
508
- # drone = AutonomousDrone.new # Has async: true machines
509
- # assert_sm_async_methods(drone)
510
- def assert_sm_async_methods(object, message = nil)
511
- async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
512
- available_async_methods = async_methods.select { |method| object.respond_to?(method) }
513
-
514
- default_message = 'Expected async methods to be available, but found none'
515
-
516
- _sm_refute_empty(available_async_methods, message || default_message)
517
- end
518
-
519
- # Assert that an object has async-enabled state machines
520
- #
521
- # @param object [Object] The object with state machines
522
- # @param machine_names [Array<Symbol>] Expected async machine names
523
- # @param message [String, nil] Custom failure message
524
- # @return [void]
525
- # @raise [AssertionError] If expected machines don't have async mode
526
- #
527
- # @example
528
- # drone = AutonomousDrone.new
529
- # assert_sm_has_async(drone, [:status, :teleporter_status, :shields])
530
- def assert_sm_has_async(object, machine_names = nil, message = nil)
531
- if machine_names
532
- # Check specific machines
533
- non_async_machines = machine_names.reject do |name|
534
- machine = object.class.state_machines[name]
535
- machine&.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
536
- end
537
-
538
- default_message = "Expected machines #{machine_names.inspect} to have async enabled, but these don't: #{non_async_machines.inspect}"
539
-
540
- _sm_assert_empty(non_async_machines, message || default_message)
541
- else
542
- # Check that at least one machine has async
543
- async_machines = object.class.state_machines.select do |_name, machine|
544
- machine.respond_to?(:async_mode_enabled?) && machine.async_mode_enabled?
545
- end
546
-
547
- default_message = 'Expected at least one state machine to have async enabled, but none found'
548
-
549
- _sm_refute_empty(async_machines, message || default_message)
550
- end
551
- end
552
-
553
- # Assert that individual async event methods are available
554
- #
555
- # @param object [Object] The object with state machines
556
- # @param event [Symbol] The event name
557
- # @param message [String, nil] Custom failure message
558
- # @return [void]
559
- # @raise [AssertionError] If async event methods are not available
560
- #
561
- # @example
562
- # drone = AutonomousDrone.new
563
- # assert_sm_async_event_methods(drone, :launch) # Checks launch_async and launch_async!
564
- def assert_sm_async_event_methods(object, event, message = nil)
565
- async_method = :"#{event}_async"
566
- async_bang_method = :"#{event}_async!"
567
-
568
- has_async = object.respond_to?(async_method)
569
- has_async_bang = object.respond_to?(async_bang_method)
570
-
571
- _sm_assert(has_async, message || "Missing #{async_method} method")
572
- _sm_assert(has_async_bang, message || "Missing #{async_bang_method} method")
573
- end
574
-
575
- # Assert that an object has thread-safe state methods when async is enabled
576
- #
577
- # @param object [Object] The object with state machines
578
- # @param message [String, nil] Custom failure message
579
- # @return [void]
580
- # @raise [AssertionError] If thread-safe methods are not available
581
- #
582
- # @example
583
- # drone = AutonomousDrone.new
584
- # assert_sm_thread_safe_methods(drone)
585
- def assert_sm_thread_safe_methods(object, message = nil)
586
- thread_safe_methods = %i[state_machine_mutex read_state_safely write_state_safely]
587
- missing_methods = thread_safe_methods.reject { |method| object.respond_to?(method) }
588
-
589
- default_message = "Expected thread-safe methods to be available, but missing: #{missing_methods.inspect}"
590
-
591
- _sm_assert_empty(missing_methods, message || default_message)
409
+ _sm_assert(result.is_a?(StateMachines::Transition), message || default_message)
592
410
  end
593
411
 
594
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.2'
4
+ VERSION = '0.302.0'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: state_machines
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.301.2
4
+ version: 0.302.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Abdelkader Boudih
@@ -62,12 +62,6 @@ files:
62
62
  - LICENSE.txt
63
63
  - README.md
64
64
  - lib/state_machines.rb
65
- - lib/state_machines/async_mode.rb
66
- - lib/state_machines/async_mode/async_event_extensions.rb
67
- - lib/state_machines/async_mode/async_events.rb
68
- - lib/state_machines/async_mode/async_machine.rb
69
- - lib/state_machines/async_mode/async_transition_collection.rb
70
- - lib/state_machines/async_mode/thread_safe_state.rb
71
65
  - lib/state_machines/branch.rb
72
66
  - lib/state_machines/callback.rb
73
67
  - lib/state_machines/core.rb
@@ -83,7 +77,6 @@ files:
83
77
  - lib/state_machines/integrations/base.rb
84
78
  - lib/state_machines/machine.rb
85
79
  - lib/state_machines/machine/action_hooks.rb
86
- - lib/state_machines/machine/async_extensions.rb
87
80
  - lib/state_machines/machine/callbacks.rb
88
81
  - lib/state_machines/machine/class_methods.rb
89
82
  - lib/state_machines/machine/configuration.rb
@@ -1,45 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Extensions to Event class for async bang methods
6
- module AsyncEventExtensions
7
- # Generate async bang methods for events when async mode is enabled
8
- def define_helper(scope, method, *args, &)
9
- result = super
10
-
11
- # If this is an async-enabled machine and we're defining an event method
12
- if scope == :instance && method !~ /_async!?$/ && machine.async_mode_enabled?
13
- qualified_name = method.to_s
14
-
15
- # Create async version that returns a task
16
- machine.define_helper(scope, "#{qualified_name}_async") do |_machine, object, *method_args, **kwargs|
17
- # Find the machine that has this event
18
- target_machine = object.class.state_machines.values.find { |m| m.events[name] }
19
-
20
- raise "#{qualified_name}_async must be called within an Async context" unless defined?(::Async::Task) && ::Async::Task.current?
21
-
22
- Async do
23
- target_machine.events[name].fire(object, *method_args, **kwargs)
24
- end
25
- end
26
-
27
- # Create async bang version that raises exceptions when awaited
28
- machine.define_helper(scope, "#{qualified_name}_async!") do |_machine, object, *method_args, **kwargs|
29
- # Find the machine that has this event
30
- target_machine = object.class.state_machines.values.find { |m| m.events[name] }
31
-
32
- raise "#{qualified_name}_async! must be called within an Async context" unless defined?(::Async::Task) && ::Async::Task.current?
33
-
34
- Async do
35
- # Use fire method which will raise exceptions on invalid transitions
36
- target_machine.events[name].fire(object, *method_args, **kwargs) || raise(StateMachines::InvalidTransition.new(object, target_machine, name))
37
- end
38
- end
39
- end
40
-
41
- result
42
- end
43
- end
44
- end
45
- end
@@ -1,270 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Async-aware event firing capabilities using the async gem
6
- module AsyncEvents
7
- # Fires an event asynchronously using Async
8
- # Returns an Async::Task that can be awaited for the result
9
- #
10
- # @return [Async::Task] a task whose result is the performed
11
- # {StateMachines::Transition}, or false if the event was refused
12
- # @example
13
- # Async do
14
- # task = vehicle.async_fire_event(:ignite)
15
- # result = task.wait # => #<StateMachines::Transition ...> or false
16
- # end
17
- def async_fire_event(event_name, *)
18
- # Find the machine that has this event
19
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
20
-
21
- raise ArgumentError, "Event #{event_name} not found in any state machine" unless machine
22
-
23
- # Must be called within an Async context
24
- raise 'async_fire_event must be called within an Async context. Use: Async { vehicle.async_fire_event(:event) }' unless defined?(::Async::Task) && ::Async::Task.current?
25
-
26
- Async do
27
- machine.events[event_name].fire(self, *)
28
- end
29
- end
30
-
31
- # Fires multiple events asynchronously across different state machines
32
- # Returns an array of Async::Tasks for concurrent execution
33
- #
34
- # @return [Array<Async::Task>] one task per event, each resolving to the
35
- # performed {StateMachines::Transition} or false
36
- # @example
37
- # Async do
38
- # tasks = vehicle.async_fire_events(:ignite, :buy_insurance)
39
- # results = tasks.map(&:wait) # => [#<StateMachines::Transition ...>, #<StateMachines::Transition ...>]
40
- # end
41
- def async_fire_events(*event_names)
42
- event_names.map { |event_name| async_fire_event(event_name) }
43
- end
44
-
45
- # Fires an event asynchronously and waits for completion
46
- # This is a convenience method that creates and waits for the task
47
- #
48
- # @return [StateMachines::Transition, false] the performed transition, or
49
- # false if the event was refused
50
- # @example
51
- # result = vehicle.fire_event_async(:ignite) # => #<StateMachines::Transition ...> or false
52
- def fire_event_async(event_name, *)
53
- raise NoMethodError, "undefined method `fire_event_async' for #{self}" unless has_async_machines?
54
-
55
- # Find the machine that has this event
56
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
57
-
58
- raise ArgumentError, "Event #{event_name} not found in any state machine" unless machine
59
-
60
- if defined?(::Async::Task) && ::Async::Task.current?
61
- # Already in async context, just fire directly
62
- machine.events[event_name].fire(self, *)
63
- else
64
- # Create async context and wait for result
65
- Async do
66
- machine.events[event_name].fire(self, *)
67
- end.wait
68
- end
69
- end
70
-
71
- # Fires multiple events asynchronously and waits for all completions
72
- # Returns results in the same order as the input events
73
- #
74
- # @return [Array<StateMachines::Transition, false>] the performed
75
- # transition (or false) for each event, in input order
76
- # @example
77
- # results = vehicle.fire_events_async(:ignite, :buy_insurance) # => [#<StateMachines::Transition ...>, #<StateMachines::Transition ...>]
78
- def fire_events_async(*event_names)
79
- raise NoMethodError, "undefined method `fire_events_async' for #{self}" unless has_async_machines?
80
-
81
- if defined?(::Async::Task) && ::Async::Task.current?
82
- # Already in async context, run concurrently
83
- tasks = event_names.map { |event_name| async_fire_event(event_name) }
84
- tasks.map(&:wait)
85
- else
86
- # Create async context and run concurrently
87
- Async do
88
- tasks = event_names.map { |event_name| async_fire_event(event_name) }
89
- tasks.map(&:wait)
90
- end.wait
91
- end
92
- end
93
-
94
- # Fires an event asynchronously using Async and raises exception on failure
95
- # Returns an Async::Task that raises StateMachines::InvalidTransition when awaited
96
- #
97
- # Example:
98
- # Async do
99
- # begin
100
- # task = vehicle.async_fire_event!(:ignite)
101
- # result = task.wait
102
- # puts "Event fired successfully!"
103
- # rescue StateMachines::InvalidTransition => e
104
- # puts "Transition failed: #{e.message}"
105
- # end
106
- # end
107
- def async_fire_event!(event_name, *)
108
- # Find the machine that has this event
109
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
110
-
111
- raise ArgumentError, "Event #{event_name} not found in any state machine" unless machine
112
-
113
- # Must be called within an Async context
114
- raise 'async_fire_event! must be called within an Async context. Use: Async { vehicle.async_fire_event!(:event) }' unless defined?(::Async::Task) && ::Async::Task.current?
115
-
116
- Async do
117
- fire_with_bang(machine, event_name, *)
118
- end
119
- end
120
-
121
- # Fires an event asynchronously and waits for result, raising exceptions on failure
122
- # This is a convenience method that creates and waits for the task
123
- #
124
- # Example:
125
- # begin
126
- # result = vehicle.fire_event_async!(:ignite)
127
- # puts "Event fired successfully!"
128
- # rescue StateMachines::InvalidTransition => e
129
- # puts "Transition failed: #{e.message}"
130
- # end
131
- def fire_event_async!(event_name, *)
132
- raise NoMethodError, "undefined method `fire_event_async!' for #{self}" unless has_async_machines?
133
-
134
- # Find the machine that has this event
135
- machine = self.class.state_machines.values.find { |m| m.events[event_name] }
136
-
137
- raise ArgumentError, "Event #{event_name} not found in any state machine" unless machine
138
-
139
- if defined?(::Async::Task) && ::Async::Task.current?
140
- # Already in async context, just fire directly with bang behavior
141
- fire_with_bang(machine, event_name, *)
142
- else
143
- # Create async context and wait for result (may raise exception)
144
- Async do
145
- fire_with_bang(machine, event_name, *)
146
- end.wait
147
- end
148
- end
149
-
150
- # Dynamically handle individual event async methods
151
- # This provides launch_async, launch_async!, arm_weapons_async, etc.
152
- def method_missing(method_name, *, **, &)
153
- method_str = method_name.to_s
154
-
155
- # Check if this is an async event method
156
- if method_str.end_with?('_async!')
157
- # Remove the _async! suffix to get the base event method
158
- base_method = method_str.chomp('_async!').to_sym
159
-
160
- # Check if the base method exists and this machine is async-enabled
161
- return handle_individual_event_async_bang(base_method, *, **) if respond_to?(base_method) && async_method_for_event?(base_method)
162
- elsif method_str.end_with?('_async')
163
- # Remove the _async suffix to get the base event method
164
- base_method = method_str.chomp('_async').to_sym
165
-
166
- # Check if the base method exists and this machine is async-enabled
167
- return handle_individual_event_async(base_method, *, **) if respond_to?(base_method) && async_method_for_event?(base_method)
168
- end
169
-
170
- # If not an async method, call the original method_missing
171
- super
172
- end
173
-
174
- # Check if we should respond to async methods for this event
175
- def respond_to_missing?(method_name, include_private = false)
176
- # Only provide async methods if this object has async-enabled machines
177
- return super unless has_async_machines?
178
-
179
- method_str = method_name.to_s
180
-
181
- if method_str.end_with?('_async!') || method_str.end_with?('_async')
182
- base_method = method_str.chomp('_async!').chomp('_async').to_sym
183
- return respond_to?(base_method) && async_method_for_event?(base_method)
184
- end
185
-
186
- super
187
- end
188
-
189
- # Check if this object has any async-enabled state machines
190
- def has_async_machines?
191
- self.class.state_machines.any? { |_name, machine| machine.async_mode_enabled? }
192
- end
193
-
194
- private
195
-
196
- # Fires the event on the given machine, raising InvalidTransition on failure
197
- def fire_with_bang(machine, event_name, *)
198
- machine.events[event_name].fire(self, *) || raise(StateMachines::InvalidTransition.new(self, machine, event_name))
199
- end
200
-
201
- # Check if this event method should have async versions
202
- def async_method_for_event?(event_method)
203
- # Find which machine contains this event
204
- self.class.state_machines.each do |_name, machine|
205
- next unless machine.async_mode_enabled?
206
-
207
- # Check if this event method belongs to this machine
208
- machine.events.each do |event|
209
- qualified_name = event.qualified_name
210
- return true if qualified_name.to_sym == event_method || :"#{qualified_name}!" == event_method
211
- end
212
- end
213
- false
214
- end
215
-
216
- # Handle individual event async methods (returns task)
217
- def handle_individual_event_async(event_method, *, **)
218
- raise "#{event_method}_async must be called within an Async context" unless defined?(::Async::Task) && ::Async::Task.current?
219
-
220
- Async do
221
- send(event_method, *, **)
222
- end
223
- end
224
-
225
- # Handle individual event async bang methods (returns task, raises on failure)
226
- def handle_individual_event_async_bang(event_method, *, **)
227
- # Extract event name from method and use bang version
228
- bang_method = :"#{event_method}!"
229
-
230
- raise "#{event_method}_async! must be called within an Async context" unless defined?(::Async::Task) && ::Async::Task.current?
231
-
232
- Async do
233
- send(bang_method, *, **)
234
- end
235
- end
236
-
237
- # Extract event name from method name, handling namespaced events
238
- def extract_event_name(method_name)
239
- method_str = method_name.to_s
240
-
241
- # Find the machine and event for this method
242
- self.class.state_machines.each do |_name, machine|
243
- machine.events.each do |event|
244
- qualified_name = event.qualified_name
245
- return event.name if qualified_name.to_s == method_str || "#{qualified_name}!" == method_str
246
- end
247
- end
248
-
249
- # Fallback: assume the method name is the event name
250
- method_str.chomp('!').to_sym
251
- end
252
-
253
- public
254
-
255
- # Fires multiple events concurrently within an async context
256
- # This method should be called from within an Async block
257
- #
258
- # Example:
259
- # Async do
260
- # results = vehicle.fire_events_concurrent(:ignite, :buy_insurance)
261
- # end
262
- def fire_events_concurrent(*event_names)
263
- raise 'fire_events_concurrent must be called within an Async context' unless defined?(::Async::Task) && ::Async::Task.current?
264
-
265
- tasks = async_fire_events(*event_names)
266
- tasks.map(&:wait)
267
- end
268
- end
269
- end
270
- end
@@ -1,58 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Enhanced machine class with async capabilities
6
- module AsyncMachine
7
- # Thread-safe state reading for machines
8
- def read_safely(object, attribute, ivar = false)
9
- if object.respond_to?(:read_state_safely)
10
- object.read_state_safely(self, attribute, ivar)
11
- else
12
- read(object, attribute, ivar)
13
- end
14
- end
15
-
16
- # Thread-safe state writing for machines
17
- def write_safely(object, attribute, value, ivar = false)
18
- if object.respond_to?(:write_state_safely)
19
- object.write_state_safely(self, attribute, value, ivar)
20
- else
21
- write(object, attribute, value, ivar)
22
- end
23
- end
24
-
25
- # Fires an event asynchronously on the given object
26
- # Returns an Async::Task for concurrent execution
27
- def async_fire_event(object, event_name, *)
28
- raise 'async_fire_event must be called within an Async context' unless defined?(::Async::Task) && ::Async::Task.current?
29
-
30
- Async do
31
- events[event_name].fire(object, *)
32
- end
33
- end
34
-
35
- # Creates an async-aware transition collection
36
- # Supports concurrent transition execution with proper synchronization
37
- def create_async_transition_collection(transitions, options = {})
38
- if defined?(AsyncTransitionCollection)
39
- AsyncTransitionCollection.new(transitions, options)
40
- else
41
- # Fallback to regular collection if async collection isn't available
42
- TransitionCollection.new(transitions, options)
43
- end
44
- end
45
-
46
- # Thread-safe callback execution for async operations
47
- def run_callbacks_safely(type, object, context, transition)
48
- if object.respond_to?(:state_machine_mutex)
49
- object.state_machine_mutex.with_read_lock do
50
- callbacks[type].each { |callback| callback.call(object, context, transition) }
51
- end
52
- else
53
- callbacks[type].each { |callback| callback.call(object, context, transition) }
54
- end
55
- end
56
- end
57
- end
58
- end
@@ -1,64 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Error class for async-specific transition failures
6
- class AsyncTransitionError < StateMachines::Error
7
- def initialize(object, machines, failed_events)
8
- @object = object
9
- @machines = machines
10
- @failed_events = failed_events
11
- super("Failed to perform async transitions: #{failed_events.join(', ')}")
12
- end
13
-
14
- attr_reader :object, :machines, :failed_events
15
- end
16
-
17
- # Async-aware transition collection that can execute transitions concurrently
18
- class AsyncTransitionCollection < TransitionCollection
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
29
- end
30
-
31
- # Performs the collection on another thread and waits for its result.
32
- def perform_threaded(&)
33
- Thread.new { perform(&) }.value
34
- end
35
-
36
- private
37
-
38
- # Override run_actions to be thread-safe when needed
39
- def run_actions(&)
40
- catch_exceptions do
41
- @success = if block_given?
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
60
- end
61
- end
62
- end
63
- end
64
- end
@@ -1,51 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module StateMachines
4
- module AsyncMode
5
- # Thread-safe state operations for async-enabled state machines
6
- # Uses concurrent-ruby for enterprise-grade thread safety
7
- module ThreadSafeState
8
- TRANSIENT_VARIABLES = StateMachines::InstanceMethods::TRANSIENT_VARIABLES
9
-
10
- MUTEX_CREATION_LOCK = Thread::Mutex.new
11
-
12
- # Gets or creates a reentrant mutex for thread-safe state operations on an object
13
- # Each object gets its own mutex to avoid global locking
14
- # Uses Concurrent::ReentrantReadWriteLock for better performance
15
- def state_machine_mutex
16
- @_state_machine_mutex || MUTEX_CREATION_LOCK.synchronize do
17
- @_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
18
- end
19
- end
20
-
21
- # Thread-safe version of state reading
22
- # Ensures atomic read operations across concurrent threads
23
- def read_state_safely(machine, attribute, ivar = false)
24
- state_machine_mutex.with_read_lock do
25
- machine.read(self, attribute, ivar)
26
- end
27
- end
28
-
29
- # Thread-safe version of state writing
30
- # Ensures atomic write operations across concurrent threads
31
- def write_state_safely(machine, attribute, value, ivar = false)
32
- state_machine_mutex.with_write_lock do
33
- machine.write(self, attribute, value, ivar)
34
- end
35
- end
36
-
37
- # Handle marshalling by excluding the mutex (will be recreated when needed)
38
- def marshal_dump
39
- vars = instance_variables - TRANSIENT_VARIABLES
40
- vars.map { |var| [var, instance_variable_get(var)] }
41
- end
42
-
43
- # Restore marshalled object, mutex will be lazily recreated when needed
44
- def marshal_load(data)
45
- data.each do |var, value|
46
- instance_variable_set(var, value)
47
- end
48
- end
49
- end
50
- end
51
- end
@@ -1,64 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- # Ruby Engine Compatibility Check
4
- # The async gem requires native extensions and Fiber scheduler support
5
- # which are not available on JRuby or TruffleRuby
6
- if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'truffleruby'
7
- raise LoadError, <<~ERROR
8
- StateMachines::AsyncMode is not available on #{RUBY_ENGINE}.
9
-
10
- The async gem requires native extensions (io-event) and Fiber scheduler support
11
- which are not implemented in #{RUBY_ENGINE}. AsyncMode is only supported on:
12
-
13
- • MRI Ruby (CRuby) 3.2+
14
- • Other Ruby engines with full Fiber scheduler support
15
-
16
- If you need async support on #{RUBY_ENGINE}, consider using:
17
- • java.util.concurrent classes (JRuby)
18
- • Native threading libraries for your platform
19
- • Or stick with synchronous state machines
20
- ERROR
21
- end
22
-
23
- # Load required gems with version constraints
24
- gem 'async', '>= 2.25.0'
25
- gem 'concurrent-ruby', '>= 1.3.5' # Security is not negotiable - enterprise-grade thread safety required
26
-
27
- require 'async'
28
- require 'concurrent-ruby'
29
-
30
- # Load all async mode components
31
- require_relative 'async_mode/thread_safe_state'
32
- require_relative 'async_mode/async_events'
33
- require_relative 'async_mode/async_event_extensions'
34
- require_relative 'async_mode/async_machine'
35
- require_relative 'async_mode/async_transition_collection'
36
-
37
- module StateMachines
38
- # AsyncMode provides asynchronous state machine capabilities using the async gem
39
- # This module enables concurrent, thread-safe state operations for high-performance applications
40
- #
41
- # @example Basic usage
42
- # class AutonomousDrone < StarfleetShip
43
- # state_machine :teleporter_status, async: true do
44
- # event :power_up do
45
- # transition offline: :charging
46
- # end
47
- # end
48
- # end
49
- #
50
- # drone = AutonomousDrone.new
51
- # Async do
52
- # result = drone.fire_event_async(:power_up) # => true
53
- # task = drone.power_up_async! # => Async::Task
54
- # end
55
- #
56
- module AsyncMode
57
- # All components are loaded from separate files:
58
- # - ThreadSafeState: Mutex-based thread safety
59
- # - AsyncEvents: Async event firing methods
60
- # - AsyncEventExtensions: Event method generation
61
- # - AsyncMachine: Machine-level async capabilities
62
- # - AsyncTransitionCollection: Concurrent transition execution
63
- end
64
- end
@@ -1,88 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- # This file provides optional async extensions for the Machine class.
4
- # It should only be loaded when async functionality is explicitly requested.
5
-
6
- module StateMachines
7
- class Machine
8
- # AsyncMode extensions for the Machine class
9
- # Provides async-aware methods while maintaining backward compatibility
10
- module AsyncExtensions
11
- # Instance methods added to Machine for async support
12
-
13
- # Configure this specific machine instance for async mode
14
- #
15
- # Example:
16
- # class Vehicle
17
- # state_machine initial: :parked do
18
- # configure_async_mode! # Enable async for this machine
19
- #
20
- # event :ignite do
21
- # transition parked: :idling
22
- # end
23
- # end
24
- # end
25
- def configure_async_mode!(enabled = true)
26
- if enabled
27
- begin
28
- require 'state_machines/async_mode'
29
- @async_mode_enabled = true
30
-
31
- owner_class.include(StateMachines::AsyncMode::ThreadSafeState)
32
- owner_class.include(StateMachines::AsyncMode::AsyncEvents)
33
- extend(StateMachines::AsyncMode::AsyncMachine)
34
-
35
- # Extend events to generate async versions
36
- events.each do |event|
37
- event.extend(StateMachines::AsyncMode::AsyncEventExtensions)
38
- end
39
- rescue LoadError => e
40
- # Fallback to sync mode with warning (only once per class)
41
- unless owner_class.instance_variable_get(:@async_fallback_warned)
42
- warn <<~WARNING
43
- ⚠️ #{owner_class.name}: Async mode requested but not available on #{RUBY_ENGINE}.
44
-
45
- #{e.message}
46
-
47
- ⚠️ Falling back to synchronous mode. Results may be unpredictable due to engine limitations.
48
- For production async support, use MRI Ruby (CRuby) 3.2+
49
- WARNING
50
- owner_class.instance_variable_set(:@async_fallback_warned, true)
51
- end
52
-
53
- @async_mode_enabled = false
54
- end
55
- else
56
- @async_mode_enabled = false
57
- end
58
-
59
- self
60
- end
61
-
62
- # Check if this specific machine instance has async mode enabled
63
- def async_mode_enabled?
64
- @async_mode_enabled || false
65
- end
66
-
67
- # Thread-safe version of state reading
68
- def read_safely(object, attribute, ivar = false)
69
- object.read_state_safely(self, attribute, ivar)
70
- end
71
-
72
- # Thread-safe version of state writing
73
- def write_safely(object, attribute, value, ivar = false)
74
- object.write_state_safely(self, attribute, value, ivar)
75
- end
76
-
77
- # Thread-safe callback execution for async operations
78
- def run_callbacks_safely(type, object, context, transition)
79
- object.state_machine_mutex.with_write_lock do
80
- callbacks[type].each { |callback| callback.call(object, context, transition) }
81
- end
82
- end
83
- end
84
-
85
- # Include async extensions by default (but only load AsyncMode when requested)
86
- include AsyncExtensions
87
- end
88
- end