state_machines-async 0.1.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 +7 -0
- data/LICENSE.txt +22 -0
- data/README.md +131 -0
- data/lib/state_machines/async/test_helper.rb +206 -0
- data/lib/state_machines/async/version.rb +7 -0
- data/lib/state_machines/async_mode/async_event_extensions.rb +45 -0
- data/lib/state_machines/async_mode/async_events.rb +270 -0
- data/lib/state_machines/async_mode/async_machine.rb +58 -0
- data/lib/state_machines/async_mode/async_transition_collection.rb +64 -0
- data/lib/state_machines/async_mode/thread_safe_state.rb +61 -0
- data/lib/state_machines/async_mode.rb +54 -0
- data/lib/state_machines/machine/async_extensions.rb +103 -0
- data/lib/state_machines-async.rb +6 -0
- metadata +156 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 665e119e9327f3f26d07b79dfc6beccdb44448b77516126f1e07e168f0146a8b
|
|
4
|
+
data.tar.gz: d70eb6cc45e813c52d9bea8c0488782d5b9738639377cff8ea635dd563e50555
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 245857344c362acfea9180f86dc512ff81728df22a634ba312697851252dc3124379bd46ec40b91f6b3479cfd4878f3e0f838dd9370c024ecb894c62c4c4f02e
|
|
7
|
+
data.tar.gz: 40127050bd98295b339d5164490139c76479209d1a9197c8a72e6bc410da5eab485d99a9c234fc0bdc49e57c4a011e24f37c7010d95899de4c99d0e2266bbae0
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Copyright (c) 2025-2026 Abdelkader Boudih
|
|
2
|
+
|
|
3
|
+
MIT License
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
6
|
+
a copy of this software and associated documentation files (the
|
|
7
|
+
"Software"), to deal in the Software without restriction, including
|
|
8
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
9
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
10
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
11
|
+
the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be
|
|
14
|
+
included in all copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
17
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
18
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
19
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
20
|
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
21
|
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
22
|
+
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# StateMachines::Async
|
|
2
|
+
|
|
3
|
+
[](https://github.com/state-machines/state_machines-async/actions/workflows/ruby.yml)
|
|
4
|
+
[](LICENSE.txt)
|
|
5
|
+
|
|
6
|
+
Async mode for [state_machines](https://github.com/state-machines/state_machines): state machines
|
|
7
|
+
whose events run as [async](https://github.com/socketry/async) tasks, with per-object
|
|
8
|
+
thread-safe state access (`concurrent-ruby`) and transitions claimed before they are performed, so
|
|
9
|
+
concurrent transitions out of one state perform once.
|
|
10
|
+
|
|
11
|
+
This gem owns async mode. The core `state_machines` gem ships none of it: without this gem loaded,
|
|
12
|
+
`state_machine ..., async: true` raises `ArgumentError` naming `state_machines-async`.
|
|
13
|
+
|
|
14
|
+
## Platform
|
|
15
|
+
|
|
16
|
+
CRuby (MRI) 4.0+ only. The async gem needs the Fiber scheduler and the io-event native extension,
|
|
17
|
+
which JRuby and TruffleRuby lack, so `require 'state_machines-async'` raises `LoadError` there
|
|
18
|
+
instead of running async machines synchronously.
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```ruby
|
|
23
|
+
gem 'state_machines-async'
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```ruby
|
|
27
|
+
require 'state_machines-async'
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
Enable async mode per machine with `async: true`; machines without it stay synchronous, and a
|
|
33
|
+
class can mix both:
|
|
34
|
+
|
|
35
|
+
```ruby
|
|
36
|
+
class AutonomousDrone
|
|
37
|
+
state_machine :status, async: true, initial: :docked do
|
|
38
|
+
event :launch do
|
|
39
|
+
transition docked: :flying
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
event :land do
|
|
43
|
+
transition flying: :docked
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Synchronous machine on the same class
|
|
48
|
+
state_machine :weapons, initial: :disarmed do
|
|
49
|
+
event :arm do
|
|
50
|
+
transition disarmed: :armed
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
An integration can make its machines async by default (`@defaults = { async: true }`); `async: false`
|
|
57
|
+
on a machine overrides that. `async:` is also accepted when reopening a machine (`state_machine :status, async: true`), and
|
|
58
|
+
`configure_async_mode!(enabled)` switches it from inside the machine definition.
|
|
59
|
+
|
|
60
|
+
### Async event methods
|
|
61
|
+
|
|
62
|
+
```ruby
|
|
63
|
+
drone = AutonomousDrone.new
|
|
64
|
+
|
|
65
|
+
Async do
|
|
66
|
+
task = drone.launch_async # => Async::Task
|
|
67
|
+
task.wait # => #<StateMachines::Transition ...> or false
|
|
68
|
+
|
|
69
|
+
drone.land_async!.wait # raises StateMachines::InvalidTransition on failure
|
|
70
|
+
|
|
71
|
+
drone.async_fire_event(:launch) # => Async::Task
|
|
72
|
+
drone.fire_events_concurrent(:land) # => [result, ...]
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Waits for the result, entering a reactor if needed
|
|
76
|
+
drone.fire_event_async(:launch) # => transition or false
|
|
77
|
+
drone.fire_event_async!(:land) # raises on failure
|
|
78
|
+
drone.fire_events_async(:launch, :arm) # => [result, result]
|
|
79
|
+
|
|
80
|
+
# Outside an Async context the task-returning methods raise
|
|
81
|
+
drone.launch_async # => RuntimeError: launch_async must be called within an Async context
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Concurrency
|
|
85
|
+
|
|
86
|
+
* Each object with an async machine gets its own `Concurrent::ReentrantReadWriteLock`, created on
|
|
87
|
+
demand (`state_machine_mutex`, `read_state_safely`, `write_state_safely`). A `dup`/`clone` gets
|
|
88
|
+
its own lock, and marshalling leaves the lock out.
|
|
89
|
+
* Async machines claim their transitions (`Machine#claims_transitions?`): of concurrent
|
|
90
|
+
transitions out of one state, from threads or from fibers of one reactor, the first is
|
|
91
|
+
performed and the others are refused with the `:contended` reason (see the core README's
|
|
92
|
+
Refusal Reasons).
|
|
93
|
+
* `Machine#create_async_transition_collection` builds a collection with `perform_async` (in a
|
|
94
|
+
reactor) and `perform_threaded`.
|
|
95
|
+
|
|
96
|
+
## Testing
|
|
97
|
+
|
|
98
|
+
`StateMachines::Async::TestHelper` includes the core's `StateMachines::TestHelper` and adds the
|
|
99
|
+
async assertions, so a test case includes only it:
|
|
100
|
+
|
|
101
|
+
```ruby
|
|
102
|
+
require 'state_machines/async/test_helper'
|
|
103
|
+
|
|
104
|
+
class DroneTest < Minitest::Test
|
|
105
|
+
include StateMachines::Async::TestHelper
|
|
106
|
+
|
|
107
|
+
def test_modes
|
|
108
|
+
drone = AutonomousDrone.new
|
|
109
|
+
|
|
110
|
+
assert_sm_async_mode(drone, :status)
|
|
111
|
+
assert_sm_sync_mode(drone, :weapons)
|
|
112
|
+
assert_sm_has_async(drone, %i[status])
|
|
113
|
+
assert_sm_async_methods(drone)
|
|
114
|
+
assert_sm_async_event_methods(drone, :launch)
|
|
115
|
+
assert_sm_thread_safe_methods(drone)
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Also available: `assert_sm_all_sync`, `assert_sm_no_async_methods`.
|
|
121
|
+
|
|
122
|
+
## Development
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
bundle install
|
|
126
|
+
bundle exec rake test # padded_cell
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT, see [LICENSE.txt](LICENSE.txt).
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'state_machines-async'
|
|
4
|
+
require 'state_machines/test_helper'
|
|
5
|
+
|
|
6
|
+
module StateMachines
|
|
7
|
+
module Async
|
|
8
|
+
# Assertions for async mode, on top of the core's StateMachines::TestHelper
|
|
9
|
+
# (which this includes, so a test case includes only this module).
|
|
10
|
+
#
|
|
11
|
+
# @example Minitest
|
|
12
|
+
# class DroneTest < Minitest::Test
|
|
13
|
+
# include StateMachines::Async::TestHelper
|
|
14
|
+
#
|
|
15
|
+
# def test_status_is_async
|
|
16
|
+
# assert_sm_async_mode(AutonomousDrone.new, :status)
|
|
17
|
+
# end
|
|
18
|
+
# end
|
|
19
|
+
module TestHelper
|
|
20
|
+
include StateMachines::TestHelper
|
|
21
|
+
|
|
22
|
+
# === Sync Mode Assertions ===
|
|
23
|
+
|
|
24
|
+
# Assert that a state machine is operating in synchronous mode
|
|
25
|
+
#
|
|
26
|
+
# @param object [Object] The object with state machines
|
|
27
|
+
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
28
|
+
# @param message [String, nil] Custom failure message
|
|
29
|
+
# @return [void]
|
|
30
|
+
# @raise [AssertionError] If the machine has async mode enabled
|
|
31
|
+
#
|
|
32
|
+
# @example
|
|
33
|
+
# user = User.new
|
|
34
|
+
# assert_sm_sync_mode(user) # Uses default :state machine
|
|
35
|
+
# assert_sm_sync_mode(user, :status) # Uses :status machine
|
|
36
|
+
def assert_sm_sync_mode(object, machine_name = :state, message = nil)
|
|
37
|
+
machine = object.class.state_machines[machine_name]
|
|
38
|
+
raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
|
|
39
|
+
|
|
40
|
+
async_enabled = machine.async_mode_enabled?
|
|
41
|
+
default_message = "Expected state machine '#{machine_name}' to be in sync mode, but async mode is enabled"
|
|
42
|
+
|
|
43
|
+
_sm_refute(async_enabled, message || default_message)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Assert that async methods are not available on a sync-only object
|
|
47
|
+
#
|
|
48
|
+
# @param object [Object] The object with state machines
|
|
49
|
+
# @param message [String, nil] Custom failure message
|
|
50
|
+
# @return [void]
|
|
51
|
+
# @raise [AssertionError] If async methods are available
|
|
52
|
+
#
|
|
53
|
+
# @example
|
|
54
|
+
# sync_only_car = Car.new # Car has no async: true machines
|
|
55
|
+
# assert_sm_no_async_methods(sync_only_car)
|
|
56
|
+
def assert_sm_no_async_methods(object, message = nil)
|
|
57
|
+
async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
|
|
58
|
+
available_async_methods = async_methods.select { |method| object.respond_to?(method) }
|
|
59
|
+
|
|
60
|
+
default_message = "Expected no async methods to be available, but found: #{available_async_methods.inspect}"
|
|
61
|
+
|
|
62
|
+
_sm_assert_empty(available_async_methods, message || default_message)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Assert that an object has no async-enabled state machines
|
|
66
|
+
#
|
|
67
|
+
# @param object [Object] The object with state machines
|
|
68
|
+
# @param message [String, nil] Custom failure message
|
|
69
|
+
# @return [void]
|
|
70
|
+
# @raise [AssertionError] If any machine has async mode enabled
|
|
71
|
+
#
|
|
72
|
+
# @example
|
|
73
|
+
# sync_only_vehicle = Vehicle.new # All machines are sync-only
|
|
74
|
+
# assert_sm_all_sync(sync_only_vehicle)
|
|
75
|
+
def assert_sm_all_sync(object, message = nil)
|
|
76
|
+
async_machines = []
|
|
77
|
+
|
|
78
|
+
object.class.state_machines.each do |name, machine|
|
|
79
|
+
async_machines << name if machine.async_mode_enabled?
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
default_message = "Expected all state machines to be sync-only, but these have async enabled: #{async_machines.inspect}"
|
|
83
|
+
|
|
84
|
+
_sm_assert_empty(async_machines, message || default_message)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# === Async Mode Assertions ===
|
|
88
|
+
|
|
89
|
+
# Assert that a state machine is operating in asynchronous mode
|
|
90
|
+
#
|
|
91
|
+
# @param object [Object] The object with state machines
|
|
92
|
+
# @param machine_name [Symbol] The name of the state machine (defaults to :state)
|
|
93
|
+
# @param message [String, nil] Custom failure message
|
|
94
|
+
# @return [void]
|
|
95
|
+
# @raise [AssertionError] If the machine doesn't have async mode enabled
|
|
96
|
+
#
|
|
97
|
+
# @example
|
|
98
|
+
# drone = AutonomousDrone.new
|
|
99
|
+
# assert_sm_async_mode(drone) # Uses default :state machine
|
|
100
|
+
# assert_sm_async_mode(drone, :teleporter_status) # Uses :teleporter_status machine
|
|
101
|
+
def assert_sm_async_mode(object, machine_name = :state, message = nil)
|
|
102
|
+
machine = object.class.state_machines[machine_name]
|
|
103
|
+
raise ArgumentError, "No state machine '#{machine_name}' found" unless machine
|
|
104
|
+
|
|
105
|
+
async_enabled = machine.async_mode_enabled?
|
|
106
|
+
default_message = "Expected state machine '#{machine_name}' to have async mode enabled, but it's in sync mode"
|
|
107
|
+
|
|
108
|
+
_sm_assert(async_enabled, message || default_message)
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Assert that async methods are available on an async-enabled object
|
|
112
|
+
#
|
|
113
|
+
# @param object [Object] The object with state machines
|
|
114
|
+
# @param message [String, nil] Custom failure message
|
|
115
|
+
# @return [void]
|
|
116
|
+
# @raise [AssertionError] If async methods are not available
|
|
117
|
+
#
|
|
118
|
+
# @example
|
|
119
|
+
# drone = AutonomousDrone.new # Has async: true machines
|
|
120
|
+
# assert_sm_async_methods(drone)
|
|
121
|
+
def assert_sm_async_methods(object, message = nil)
|
|
122
|
+
async_methods = %i[fire_event_async fire_events_async fire_event_async! async_fire_event]
|
|
123
|
+
available_async_methods = async_methods.select { |method| object.respond_to?(method) }
|
|
124
|
+
|
|
125
|
+
default_message = 'Expected async methods to be available, but found none'
|
|
126
|
+
|
|
127
|
+
_sm_refute_empty(available_async_methods, message || default_message)
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
# Assert that an object has async-enabled state machines
|
|
131
|
+
#
|
|
132
|
+
# @param object [Object] The object with state machines
|
|
133
|
+
# @param machine_names [Array<Symbol>] Expected async machine names
|
|
134
|
+
# @param message [String, nil] Custom failure message
|
|
135
|
+
# @return [void]
|
|
136
|
+
# @raise [AssertionError] If expected machines don't have async mode
|
|
137
|
+
#
|
|
138
|
+
# @example
|
|
139
|
+
# drone = AutonomousDrone.new
|
|
140
|
+
# assert_sm_has_async(drone, [:status, :teleporter_status, :shields])
|
|
141
|
+
def assert_sm_has_async(object, machine_names = nil, message = nil)
|
|
142
|
+
if machine_names
|
|
143
|
+
# Check specific machines
|
|
144
|
+
non_async_machines = machine_names.reject do |name|
|
|
145
|
+
machine = object.class.state_machines[name]
|
|
146
|
+
machine&.async_mode_enabled?
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
default_message = "Expected machines #{machine_names.inspect} to have async enabled, but these don't: #{non_async_machines.inspect}"
|
|
150
|
+
|
|
151
|
+
_sm_assert_empty(non_async_machines, message || default_message)
|
|
152
|
+
else
|
|
153
|
+
# Check that at least one machine has async
|
|
154
|
+
async_machines = object.class.state_machines.select do |_name, machine|
|
|
155
|
+
machine.async_mode_enabled?
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
default_message = 'Expected at least one state machine to have async enabled, but none found'
|
|
159
|
+
|
|
160
|
+
_sm_refute_empty(async_machines, message || default_message)
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# Assert that individual async event methods are available
|
|
165
|
+
#
|
|
166
|
+
# @param object [Object] The object with state machines
|
|
167
|
+
# @param event [Symbol] The event name
|
|
168
|
+
# @param message [String, nil] Custom failure message
|
|
169
|
+
# @return [void]
|
|
170
|
+
# @raise [AssertionError] If async event methods are not available
|
|
171
|
+
#
|
|
172
|
+
# @example
|
|
173
|
+
# drone = AutonomousDrone.new
|
|
174
|
+
# assert_sm_async_event_methods(drone, :launch) # Checks launch_async and launch_async!
|
|
175
|
+
def assert_sm_async_event_methods(object, event, message = nil)
|
|
176
|
+
async_method = :"#{event}_async"
|
|
177
|
+
async_bang_method = :"#{event}_async!"
|
|
178
|
+
|
|
179
|
+
has_async = object.respond_to?(async_method)
|
|
180
|
+
has_async_bang = object.respond_to?(async_bang_method)
|
|
181
|
+
|
|
182
|
+
_sm_assert(has_async, message || "Missing #{async_method} method")
|
|
183
|
+
_sm_assert(has_async_bang, message || "Missing #{async_bang_method} method")
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# Assert that an object has thread-safe state methods when async is enabled
|
|
187
|
+
#
|
|
188
|
+
# @param object [Object] The object with state machines
|
|
189
|
+
# @param message [String, nil] Custom failure message
|
|
190
|
+
# @return [void]
|
|
191
|
+
# @raise [AssertionError] If thread-safe methods are not available
|
|
192
|
+
#
|
|
193
|
+
# @example
|
|
194
|
+
# drone = AutonomousDrone.new
|
|
195
|
+
# assert_sm_thread_safe_methods(drone)
|
|
196
|
+
def assert_sm_thread_safe_methods(object, message = nil)
|
|
197
|
+
thread_safe_methods = %i[state_machine_mutex read_state_safely write_state_safely]
|
|
198
|
+
missing_methods = thread_safe_methods.reject { |method| object.respond_to?(method) }
|
|
199
|
+
|
|
200
|
+
default_message = "Expected thread-safe methods to be available, but missing: #{missing_methods.inspect}"
|
|
201
|
+
|
|
202
|
+
_sm_assert_empty(missing_methods, message || default_message)
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
end
|
|
206
|
+
end
|
|
@@ -0,0 +1,45 @@
|
|
|
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
|
|
@@ -0,0 +1,270 @@
|
|
|
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
|
|
@@ -0,0 +1,58 @@
|
|
|
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
|
|
@@ -0,0 +1,64 @@
|
|
|
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
|
|
@@ -0,0 +1,61 @@
|
|
|
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
|
+
# The core's per-object concurrency state, plus the lock
|
|
9
|
+
TRANSIENT_VARIABLES = (StateMachines::InstanceMethods::TRANSIENT_VARIABLES + %i[@_state_machine_mutex]).freeze
|
|
10
|
+
|
|
11
|
+
MUTEX_CREATION_LOCK = Thread::Mutex.new
|
|
12
|
+
|
|
13
|
+
# Gets or creates a reentrant mutex for thread-safe state operations on an object
|
|
14
|
+
# Each object gets its own mutex to avoid global locking
|
|
15
|
+
# Uses Concurrent::ReentrantReadWriteLock for better performance
|
|
16
|
+
def state_machine_mutex
|
|
17
|
+
@_state_machine_mutex || MUTEX_CREATION_LOCK.synchronize do
|
|
18
|
+
@_state_machine_mutex ||= Concurrent::ReentrantReadWriteLock.new
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Thread-safe version of state reading
|
|
23
|
+
# Ensures atomic read operations across concurrent threads
|
|
24
|
+
def read_state_safely(machine, attribute, ivar = false)
|
|
25
|
+
state_machine_mutex.with_read_lock do
|
|
26
|
+
machine.read(self, attribute, ivar)
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# Thread-safe version of state writing
|
|
31
|
+
# Ensures atomic write operations across concurrent threads
|
|
32
|
+
def write_state_safely(machine, attribute, value, ivar = false)
|
|
33
|
+
state_machine_mutex.with_write_lock do
|
|
34
|
+
machine.write(self, attribute, value, ivar)
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# A copy (+dup+ / +clone+) gets its own lock (created on demand) instead
|
|
39
|
+
# of sharing the original's.
|
|
40
|
+
#
|
|
41
|
+
# A class defining its own +initialize_copy+ must call +super+.
|
|
42
|
+
def initialize_copy(orig)
|
|
43
|
+
super
|
|
44
|
+
remove_instance_variable(:@_state_machine_mutex) if instance_variable_defined?(:@_state_machine_mutex)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Handle marshalling by excluding the mutex (will be recreated when needed)
|
|
48
|
+
def marshal_dump
|
|
49
|
+
vars = instance_variables - TRANSIENT_VARIABLES
|
|
50
|
+
vars.map { |var| [var, instance_variable_get(var)] }
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Restore marshalled object, mutex will be lazily recreated when needed
|
|
54
|
+
def marshal_load(data)
|
|
55
|
+
data.each do |var, value|
|
|
56
|
+
instance_variable_set(var, value)
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Async mode runs on the Fiber scheduler of the async gem, whose io-event
|
|
4
|
+
# native extension and scheduler support JRuby and TruffleRuby lack. Refuse
|
|
5
|
+
# to load there rather than run async machines synchronously.
|
|
6
|
+
if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'truffleruby'
|
|
7
|
+
raise LoadError, <<~ERROR
|
|
8
|
+
state_machines-async is not available on #{RUBY_ENGINE}.
|
|
9
|
+
|
|
10
|
+
The async gem requires native extensions (io-event) and Fiber scheduler
|
|
11
|
+
support, which #{RUBY_ENGINE} does not implement. Async mode runs on CRuby
|
|
12
|
+
(MRI) 4.0+ only; on #{RUBY_ENGINE}, use synchronous state machines.
|
|
13
|
+
ERROR
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
require 'async'
|
|
17
|
+
require 'concurrent-ruby'
|
|
18
|
+
require 'state_machines'
|
|
19
|
+
|
|
20
|
+
# Load all async mode components
|
|
21
|
+
require_relative 'async_mode/thread_safe_state'
|
|
22
|
+
require_relative 'async_mode/async_events'
|
|
23
|
+
require_relative 'async_mode/async_event_extensions'
|
|
24
|
+
require_relative 'async_mode/async_machine'
|
|
25
|
+
require_relative 'async_mode/async_transition_collection'
|
|
26
|
+
|
|
27
|
+
module StateMachines
|
|
28
|
+
# AsyncMode provides asynchronous state machine capabilities using the async gem
|
|
29
|
+
# This module enables concurrent, thread-safe state operations for high-performance applications
|
|
30
|
+
#
|
|
31
|
+
# @example Basic usage
|
|
32
|
+
# class AutonomousDrone < StarfleetShip
|
|
33
|
+
# state_machine :teleporter_status, async: true do
|
|
34
|
+
# event :power_up do
|
|
35
|
+
# transition offline: :charging
|
|
36
|
+
# end
|
|
37
|
+
# end
|
|
38
|
+
# end
|
|
39
|
+
#
|
|
40
|
+
# drone = AutonomousDrone.new
|
|
41
|
+
# Async do
|
|
42
|
+
# result = drone.fire_event_async(:power_up) # => true
|
|
43
|
+
# task = drone.power_up_async! # => Async::Task
|
|
44
|
+
# end
|
|
45
|
+
#
|
|
46
|
+
module AsyncMode
|
|
47
|
+
# All components are loaded from separate files:
|
|
48
|
+
# - ThreadSafeState: Mutex-based thread safety
|
|
49
|
+
# - AsyncEvents: Async event firing methods
|
|
50
|
+
# - AsyncEventExtensions: Event method generation
|
|
51
|
+
# - AsyncMachine: Machine-level async capabilities
|
|
52
|
+
# - AsyncTransitionCollection: Concurrent transition execution
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module StateMachines
|
|
4
|
+
class Machine
|
|
5
|
+
# Async mode for the Machine class: the +async:+ option on creation and on
|
|
6
|
+
# reopening, and the per-machine switch. Prepended, since it plugs into the
|
|
7
|
+
# core's Machine#creation_options, #after_definition,
|
|
8
|
+
# #claims_transitions?, #reopen_options and #reopen.
|
|
9
|
+
module AsyncExtensions
|
|
10
|
+
# A new machine also accepts +async:+.
|
|
11
|
+
#
|
|
12
|
+
# class Vehicle
|
|
13
|
+
# state_machine initial: :parked, async: true do
|
|
14
|
+
# event :ignite do
|
|
15
|
+
# transition parked: :idling
|
|
16
|
+
# end
|
|
17
|
+
# end
|
|
18
|
+
# end
|
|
19
|
+
def creation_options
|
|
20
|
+
super + %i[async]
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Turns async mode on or off for this machine.
|
|
24
|
+
#
|
|
25
|
+
# Example:
|
|
26
|
+
# class Vehicle
|
|
27
|
+
# state_machine initial: :parked do
|
|
28
|
+
# configure_async_mode! # Enable async for this machine
|
|
29
|
+
#
|
|
30
|
+
# event :ignite do
|
|
31
|
+
# transition parked: :idling
|
|
32
|
+
# end
|
|
33
|
+
# end
|
|
34
|
+
# end
|
|
35
|
+
def configure_async_mode!(enabled = true)
|
|
36
|
+
@async_mode_enabled = enabled ? true : false
|
|
37
|
+
return self unless @async_mode_enabled
|
|
38
|
+
|
|
39
|
+
owner_class.include(StateMachines::AsyncMode::ThreadSafeState)
|
|
40
|
+
owner_class.include(StateMachines::AsyncMode::AsyncEvents)
|
|
41
|
+
extend(StateMachines::AsyncMode::AsyncMachine)
|
|
42
|
+
|
|
43
|
+
# Extend events to generate async versions
|
|
44
|
+
events.each do |event|
|
|
45
|
+
event.extend(StateMachines::AsyncMode::AsyncEventExtensions)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
self
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Check if this specific machine instance has async mode enabled
|
|
52
|
+
def async_mode_enabled?
|
|
53
|
+
@async_mode_enabled || false
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# An async machine's transitions run concurrently, so they are claimed
|
|
57
|
+
# before they are performed. Another extension may claim them too.
|
|
58
|
+
def claims_transitions?
|
|
59
|
+
async_mode_enabled? || super
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# A reopened machine also accepts +async:+.
|
|
63
|
+
def reopen_options
|
|
64
|
+
super + %i[async]
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Applies +async:+ when a machine is reopened.
|
|
68
|
+
def reopen(options)
|
|
69
|
+
super
|
|
70
|
+
configure_async_mode!(options[:async]) if options.include?(:async)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
# Thread-safe version of state reading
|
|
74
|
+
def read_safely(object, attribute, ivar = false)
|
|
75
|
+
object.read_state_safely(self, attribute, ivar)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Thread-safe version of state writing
|
|
79
|
+
def write_safely(object, attribute, value, ivar = false)
|
|
80
|
+
object.write_state_safely(self, attribute, value, ivar)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Thread-safe callback execution for async operations
|
|
84
|
+
def run_callbacks_safely(type, object, context, transition)
|
|
85
|
+
object.state_machine_mutex.with_write_lock do
|
|
86
|
+
callbacks[type].each { |callback| callback.call(object, context, transition) }
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
protected
|
|
91
|
+
|
|
92
|
+
# Turns async mode on once the machine is defined, when +async:+ is
|
|
93
|
+
# set: by the caller, or by the integration's defaults unless the
|
|
94
|
+
# caller overrides them.
|
|
95
|
+
def after_definition(options)
|
|
96
|
+
super
|
|
97
|
+
configure_async_mode!(true) if options[:async]
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
prepend AsyncExtensions
|
|
102
|
+
end
|
|
103
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: state_machines-async
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Abdelkader Boudih
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: async
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - ">="
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: 2.25.0
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - ">="
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: 2.25.0
|
|
26
|
+
- !ruby/object:Gem::Dependency
|
|
27
|
+
name: concurrent-ruby
|
|
28
|
+
requirement: !ruby/object:Gem::Requirement
|
|
29
|
+
requirements:
|
|
30
|
+
- - ">="
|
|
31
|
+
- !ruby/object:Gem::Version
|
|
32
|
+
version: 1.3.5
|
|
33
|
+
type: :runtime
|
|
34
|
+
prerelease: false
|
|
35
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
36
|
+
requirements:
|
|
37
|
+
- - ">="
|
|
38
|
+
- !ruby/object:Gem::Version
|
|
39
|
+
version: 1.3.5
|
|
40
|
+
- !ruby/object:Gem::Dependency
|
|
41
|
+
name: state_machines
|
|
42
|
+
requirement: !ruby/object:Gem::Requirement
|
|
43
|
+
requirements:
|
|
44
|
+
- - ">="
|
|
45
|
+
- !ruby/object:Gem::Version
|
|
46
|
+
version: 0.302.0
|
|
47
|
+
type: :runtime
|
|
48
|
+
prerelease: false
|
|
49
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
50
|
+
requirements:
|
|
51
|
+
- - ">="
|
|
52
|
+
- !ruby/object:Gem::Version
|
|
53
|
+
version: 0.302.0
|
|
54
|
+
- !ruby/object:Gem::Dependency
|
|
55
|
+
name: bundler
|
|
56
|
+
requirement: !ruby/object:Gem::Requirement
|
|
57
|
+
requirements:
|
|
58
|
+
- - ">="
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: '0'
|
|
61
|
+
type: :development
|
|
62
|
+
prerelease: false
|
|
63
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
64
|
+
requirements:
|
|
65
|
+
- - ">="
|
|
66
|
+
- !ruby/object:Gem::Version
|
|
67
|
+
version: '0'
|
|
68
|
+
- !ruby/object:Gem::Dependency
|
|
69
|
+
name: minitest
|
|
70
|
+
requirement: !ruby/object:Gem::Requirement
|
|
71
|
+
requirements:
|
|
72
|
+
- - "~>"
|
|
73
|
+
- !ruby/object:Gem::Version
|
|
74
|
+
version: '6.0'
|
|
75
|
+
type: :development
|
|
76
|
+
prerelease: false
|
|
77
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
78
|
+
requirements:
|
|
79
|
+
- - "~>"
|
|
80
|
+
- !ruby/object:Gem::Version
|
|
81
|
+
version: '6.0'
|
|
82
|
+
- !ruby/object:Gem::Dependency
|
|
83
|
+
name: minitest-reporters
|
|
84
|
+
requirement: !ruby/object:Gem::Requirement
|
|
85
|
+
requirements:
|
|
86
|
+
- - ">="
|
|
87
|
+
- !ruby/object:Gem::Version
|
|
88
|
+
version: '0'
|
|
89
|
+
type: :development
|
|
90
|
+
prerelease: false
|
|
91
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
92
|
+
requirements:
|
|
93
|
+
- - ">="
|
|
94
|
+
- !ruby/object:Gem::Version
|
|
95
|
+
version: '0'
|
|
96
|
+
- !ruby/object:Gem::Dependency
|
|
97
|
+
name: rake
|
|
98
|
+
requirement: !ruby/object:Gem::Requirement
|
|
99
|
+
requirements:
|
|
100
|
+
- - ">="
|
|
101
|
+
- !ruby/object:Gem::Version
|
|
102
|
+
version: '0'
|
|
103
|
+
type: :development
|
|
104
|
+
prerelease: false
|
|
105
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
106
|
+
requirements:
|
|
107
|
+
- - ">="
|
|
108
|
+
- !ruby/object:Gem::Version
|
|
109
|
+
version: '0'
|
|
110
|
+
description: 'Asynchronous, thread-safe state machines for state_machines: async:
|
|
111
|
+
true, <event>_async methods and concurrent transitions, on the async gem (CRuby
|
|
112
|
+
only)'
|
|
113
|
+
email:
|
|
114
|
+
- terminale@gmail.com
|
|
115
|
+
executables: []
|
|
116
|
+
extensions: []
|
|
117
|
+
extra_rdoc_files: []
|
|
118
|
+
files:
|
|
119
|
+
- LICENSE.txt
|
|
120
|
+
- README.md
|
|
121
|
+
- lib/state_machines-async.rb
|
|
122
|
+
- lib/state_machines/async/test_helper.rb
|
|
123
|
+
- lib/state_machines/async/version.rb
|
|
124
|
+
- lib/state_machines/async_mode.rb
|
|
125
|
+
- lib/state_machines/async_mode/async_event_extensions.rb
|
|
126
|
+
- lib/state_machines/async_mode/async_events.rb
|
|
127
|
+
- lib/state_machines/async_mode/async_machine.rb
|
|
128
|
+
- lib/state_machines/async_mode/async_transition_collection.rb
|
|
129
|
+
- lib/state_machines/async_mode/thread_safe_state.rb
|
|
130
|
+
- lib/state_machines/machine/async_extensions.rb
|
|
131
|
+
homepage: https://github.com/state-machines/state_machines-async
|
|
132
|
+
licenses:
|
|
133
|
+
- MIT
|
|
134
|
+
metadata:
|
|
135
|
+
changelog_uri: https://github.com/state-machines/state_machines-async/blob/master/CHANGELOG.md
|
|
136
|
+
homepage_uri: https://github.com/state-machines/state_machines-async
|
|
137
|
+
source_code_uri: https://github.com/state-machines/state_machines-async
|
|
138
|
+
rubygems_mfa_required: 'true'
|
|
139
|
+
rdoc_options: []
|
|
140
|
+
require_paths:
|
|
141
|
+
- lib
|
|
142
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
143
|
+
requirements:
|
|
144
|
+
- - ">="
|
|
145
|
+
- !ruby/object:Gem::Version
|
|
146
|
+
version: '4.0'
|
|
147
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
148
|
+
requirements:
|
|
149
|
+
- - ">="
|
|
150
|
+
- !ruby/object:Gem::Version
|
|
151
|
+
version: '0'
|
|
152
|
+
requirements: []
|
|
153
|
+
rubygems_version: 4.0.20
|
|
154
|
+
specification_version: 4
|
|
155
|
+
summary: Async mode for state_machines
|
|
156
|
+
test_files: []
|