RuState
A Rust implementation of statecharts inspired by XState. RuState provides a type-safe way to model and implement finite state machines and statecharts in Rust, with full support for model-based testing (MBT).
Features
- ✅ Finite state machines and statecharts
- ✅ Hierarchical states
- ✅ Parallel states
- ✅ Guards/conditions for transitions
- ✅ Actions/side effects
- ✅ Context (extended state)
- ✅ Typesafe API
- ✅ Serializable machines
- ✅ Model-based testing support
- ✅ Cross-crate integration patterns
- ✅ Code generation (JSON and Protocol Buffers)
Code Generation Features
RuState now supports code generation features to transform state machine definitions into different formats:
- JSON Export: Export statecharts to JSON format compatible with XState
- Protocol Buffers Export: Generate .proto files for cross-language compatibility
- Rust AST Analysis: Parse state machine definitions from Rust source code
Enable Code Generation
[]
# For JSON export only
= { = "0.2.5", = ["codegen"] }
# For Protocol Buffers generation
= { = "0.2.5", = ["proto"] }
Export Example
use ;
// Create your state machine
let machine = create_my_machine?;
// Export to JSON
let json_options = JsonExportOptions ;
machine.export_to_json?;
// Export to Protocol Buffers
let proto_options = ProtoExportOptions ;
machine.export_to_proto?;
Advanced Usage: Rust AST Analysis
With the codegen feature, RuState can analyze Rust source code to extract state machine definitions:
use ;
// Parse state machine definition from Rust source
let machine = parse_from_rust_file?;
println!;
This feature enables powerful tooling for documentation generation, visual representation, and integration with other languages and frameworks.
Model-Based Testing Integration
RuState now includes comprehensive model-based testing features:
- Automated Test Generation: Generate test cases from your state machine model
- Test Execution: Run tests directly against your state machine or export them
- Coverage Analysis: Measure state and transition coverage
- Model Checking: Verify properties like reachability, safety, and liveness
Key MBT Components:
- TestGenerator: Creates test cases for states, transitions, and loop coverage
- TestRunner: Executes test cases against your machine
- ModelChecker: Verifies model properties and detects deadlocks and unreachable states
Cross-Crate Integration Patterns
RuState provides patterns for integrating state machines across crates with type safety:
- Event Forwarding Pattern: Share state machine references and forward events between machines
- Context Sharing Pattern: Share context data between multiple state machines
- Hierarchical Integration Pattern: Connect parent-child state machines with traits
Enable with the integration feature:
[]
= { = "0.2.5", = ["integration"] }
Integration Example
use ;
// Create and share a state machine
let machine = create_machine;
let shared_machine = new;
// Forward events
shared_machine.send_event?;
See the examples/integration directory for complete integration examples.
Integration Patterns in Detail
RuState provides three main integration patterns for connecting state machines across crate boundaries in a type-safe way:
1. Event Forwarding Pattern
This pattern allows state machines to communicate by sending events to each other. It's useful when you need to coordinate multiple state machines with minimal coupling.
use ;
use SharedMachineRef;
// Create a child state machine
let child_machine = new
.state
.state
.initial
.transition
.build
.unwrap;
// Create a shared reference
let shared_child = new;
let shared_child_clone = shared_child.clone;
// Parent machine action that forwards events to child
let forward_action = new;
2. Context Sharing Pattern
This pattern allows multiple state machines to share data through a common context. It's ideal for scenarios where state machines need to access and modify shared state.
use ;
use SharedContext;
// Create shared context
let shared_context = new;
let context_for_a = shared_context.clone;
let context_for_b = shared_context.clone;
// Action that writes to shared context
let write_action = new;
// Action that reads from shared context
let read_action = new;
3. Hierarchical Integration Pattern
This pattern establishes parent-child relationships between state machines using traits. It's powerful for complex systems where you need to model hierarchical relationships with high cohesion but low coupling.
use ;
use ;
use ;
// Create a child state machine
let child_machine = new
.state
.state
.state
.initial
.transition
.transition
.build
.unwrap;
// Wrap with trait implementation
let child = new;
let child = new;
// Create action that monitors child machine state
let monitor_action = create_child_monitor_action;
// Create action that forwards events to child machine
let forward_action = create_event_forwarder_action;
Combining Integration Patterns
For complex systems, these patterns can be combined to create powerful integration strategies. See the examples/integration/combined_demo.rs for a complete example that demonstrates all three patterns working together.
For asynchronous integration capabilities, use the integration_async feature:
[]
= { = "0.2.4", = ["integration_async"] }
Usage Example
Simple State Machine
use ;
// Create states
let green = new;
let yellow = new;
let red = new;
// Create transitions
let green_to_yellow = new;
let yellow_to_red = new;
let red_to_green = new;
// Define actions
let log_green = new;
// Build the machine
let mut machine = new
.state
.state
.state
.initial
.transition
.transition
.transition
.on_entry
.build
.unwrap;
// Send an event to the machine
machine.send.unwrap;
Model-Based Testing Example
use ;
// Assuming you have a state machine defined as above...
let machine = /* ... */;
// Generate test cases
let mut generator = new;
let test_cases = generator.generate_all_transitions;
// Run tests
let mut runner = new;
let results = runner.run_tests;
println!;
// Coverage analysis
let coverage = results.get_coverage;
println!;
println!;
// Model checking
let mut checker = new;
// Define property to check
let property = Property ;
// Verify the property
let verification = checker.verify_property;
if verification.satisfied else
// Detect deadlocks
let deadlocks = checker.detect_deadlocks;
println!;
See the examples directory for complete examples.
Network and Remote Integration
For network-based state machine control and monitoring, check out rustate-grpc, which provides:
- Remote state machine creation and control via gRPC
- Real-time state change monitoring via streaming
- Type-safe client/server communication
- Cross-language support through protocol buffers
[]
= { = "0.1.0", = ["full"] }
See the rustate-grpc documentation for detailed usage examples.
Installation
Add this to your Cargo.toml:
[]
= "0.2.5"
Documentation
Core Concepts
- State: Represents a node in the state chart
- Transition: Defines how the machine moves between states in response to events
- Guard: Conditional logic that determines if a transition should occur
- Action: Side effects that execute during state transitions
- Context: Stores extended state for the machine
- TestGenerator: Creates test cases from your state machine model
- TestRunner: Executes test cases against your machine
- ModelChecker: Verifies properties and analyzes your state machine model
API Overview
State: Create simple, compound, parallel, or history statesTransition: Define transitions between states, including guards and actionsGuard: Create guard conditions for transitionsAction: Define actions/side effects for state transitionsContext: Store and retrieve extended state dataMachine: The runtime state machine instanceMachineBuilder: Fluent API for creating state machinesTestGenerator: Generate test cases from a state machine modelTestRunner: Run tests against your state machineModelChecker: Verify properties and analyze your state machine model
Future Directions
- Advanced model checking algorithms
- Property-based testing integration
- Test visualization tools
- Fuzzing-based MBT
- Temporal logic (LTL/CTL) property specification and verification
- Performance optimizations for large state machines
- ✅ Distributed system state machine coordination
- Enhanced WebAssembly (WASM) support
- Integration with visual state machine editors
- Automatic state machine model generation from existing systems
- Advanced concurrency model support
- Domain-specific language (DSL) for state machine definition
- Microcontroller-optimized version
License
MIT
テスト機能
RuStateには複数のテスト支援機能があります:
モデルベーステスト (MBT)
状態マシンのモデルに基づいて自動的にテストケースを生成します。
let machine = create_test_machine;
let mut generator = new;
// 状態カバレッジのテストケースを生成
let state_tests = generator.generate_all_states;
// 遷移カバレッジのテストケースを生成
let transition_tests = generator.generate_all_transitions;
プロパティベーステスト
proptest との統合により、ランダムなイベントシーケンスでプロパティを検証します。
let property = property
.given
.when
.then;
let runner = new;
let result = runner.verify_property;
XState互換モデルベーステスト (新機能)
XState v5互換のモデルベーステストインターフェースを提供します。
// ステートマシンからテストモデルを作成
let mut model = create_test_model;
// アサーションを追加
model.assert;
// アクターの実装を提供
model.provide;
// テストプランを作成(手動または自動生成)
let plan = XStateTestPlan ;
// または自動生成
let generated_plan = model.generate_paths;
// プランを実行
let results = execute_test_plan?;
モデル検査
状態マシンの性質(到達可能性、安全性など)を検証します。
let mut checker = new;
// 到達可能性プロパティの検証
let reachability = Property ;
let result = checker.verify_property;