rs-statemachine 0.1.0

A Rust implementation of COLA-style state machine with fluent API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Real-world example: Traffic Light Control System
//!
//! This example demonstrates how to use different feature combinations
//! for a practical application.

use rs_statemachine::*;
use std::sync::Arc;

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
enum TrafficLightState {
    Red,
    Yellow,
    Green,
    FlashingYellow, // For maintenance or low-traffic periods
    Emergency,      // For emergency vehicle passage
}

impl State for TrafficLightState {}

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
enum TrafficLightEvent {
    Timer,
    EmergencyVehicleDetected,
    EmergencyCleared,
    MaintenanceMode,
    NormalMode,
    PedestrianRequest,
}

impl Event for TrafficLightEvent {}

#[derive(Debug, Clone)]
struct TrafficContext {
    intersection_id: String,
    traffic_density: f32, // 0.0 to 1.0
    pedestrian_waiting: bool,
    emergency_active: bool,
    time_in_state: std::time::Duration,
}

impl Context for TrafficContext {}

/// Build a traffic light system with configurable features
pub fn build_traffic_light_system(
) -> StateMachine<TrafficLightState, TrafficLightEvent, TrafficContext> {
    let mut builder =
        StateMachineBuilderFactory::create::<TrafficLightState, TrafficLightEvent, TrafficContext>(
        );

    // Configure the state machine based on available features
    configure_basic_transitions(&mut builder);

    #[cfg(feature = "extended")]
    configure_entry_exit_actions(&mut builder);

    #[cfg(feature = "guards")]
    configure_priority_transitions(&mut builder);

    #[cfg(feature = "timeout")]
    configure_timeouts(&mut builder);

    builder.set_fail_callback(Arc::new(|state, event, ctx| {
        eprintln!(
            "WARNING: Invalid transition from {:?} with {:?} at intersection {}",
            state, event, ctx.intersection_id
        );
    }));
    builder.id("TrafficLightController").build()
}

/// Configure basic state transitions
fn configure_basic_transitions<'a>(
    builder: &'a mut StateMachineBuilder<TrafficLightState, TrafficLightEvent, TrafficContext>,
) -> &'a mut StateMachineBuilder<TrafficLightState, TrafficLightEvent, TrafficContext> {
    // Normal traffic light cycle
    builder
        .external_transition()
        .from(TrafficLightState::Green)
        .to(TrafficLightState::Yellow)
        .on(TrafficLightEvent::Timer)
        .perform(|_s, _e, ctx| {
            println!("[{}] Changing to YELLOW", ctx.intersection_id);
        });

    builder
        .external_transition()
        .from(TrafficLightState::Yellow)
        .to(TrafficLightState::Red)
        .on(TrafficLightEvent::Timer)
        .perform(|_s, _e, ctx| {
            println!("[{}] Changing to RED", ctx.intersection_id);
        });

    builder
        .external_transition()
        .from(TrafficLightState::Red)
        .to(TrafficLightState::Green)
        .on(TrafficLightEvent::Timer)
        .when(|_s, _e, ctx| !ctx.emergency_active)
        .perform(|_s, _e, ctx| {
            println!("[{}] Changing to GREEN", ctx.intersection_id);
        });

    // Emergency vehicle handling
    builder
        .external_transitions()
        .from_among(vec![
            TrafficLightState::Green,
            TrafficLightState::Yellow,
            TrafficLightState::Red,
        ])
        .to(TrafficLightState::Emergency)
        .on(TrafficLightEvent::EmergencyVehicleDetected)
        .perform(|from, _e, ctx| {
            println!(
                "[{}] EMERGENCY MODE! Was in {:?}",
                ctx.intersection_id, from
            );
        });

    builder
        .external_transition()
        .from(TrafficLightState::Emergency)
        .to(TrafficLightState::Red)
        .on(TrafficLightEvent::EmergencyCleared)
        .perform(|_s, _e, ctx| {
            println!(
                "[{}] Emergency cleared, returning to RED",
                ctx.intersection_id
            );
        });

    // Maintenance mode
    builder
        .external_transitions()
        .from_among(vec![
            TrafficLightState::Green,
            TrafficLightState::Yellow,
            TrafficLightState::Red,
        ])
        .to(TrafficLightState::FlashingYellow)
        .on(TrafficLightEvent::MaintenanceMode)
        .perform(|_s, _e, ctx| {
            println!(
                "[{}] Entering maintenance mode - FLASHING YELLOW",
                ctx.intersection_id
            );
        });

    builder
        .external_transition()
        .from(TrafficLightState::FlashingYellow)
        .to(TrafficLightState::Red)
        .on(TrafficLightEvent::NormalMode)
        .perform(|_s, _e, ctx| {
            println!("[{}] Exiting maintenance mode", ctx.intersection_id);
        });

    builder
}

/// Configure entry and exit actions for states
#[cfg(feature = "extended")]
fn configure_entry_exit_actions(
    builder: &mut StateMachineBuilder<TrafficLightState, TrafficLightEvent, TrafficContext>,
) {
    // Entry actions
    builder.with_entry_action(TrafficLightState::Green, |_state, ctx| {
        println!(
            "[{}] GREEN light ON - Vehicles may proceed",
            ctx.intersection_id
        );
        // In a real system, this would control the actual light hardware
    });

    builder.with_entry_action(TrafficLightState::Yellow, |_state, ctx| {
        println!(
            "[{}] YELLOW light ON - Prepare to stop",
            ctx.intersection_id
        );
    });

    builder.with_entry_action(TrafficLightState::Red, |_state, ctx| {
        println!(
            "[{}] RED light ON - Vehicles must stop",
            ctx.intersection_id
        );
        if ctx.pedestrian_waiting {
            println!(
                "[{}] Pedestrian crossing signal activated",
                ctx.intersection_id
            );
        }
    });

    builder.with_entry_action(TrafficLightState::Emergency, |_state, ctx| {
        println!(
            "[{}] EMERGENCY MODE - All lights RED except emergency route",
            ctx.intersection_id
        );
        // Would trigger emergency protocols in real system
    });

    // Exit actions
    builder.with_exit_action(TrafficLightState::Green, |_state, ctx| {
        println!("[{}] GREEN light OFF", ctx.intersection_id);
    });

    builder.with_exit_action(TrafficLightState::Emergency, |_state, ctx| {
        println!("[{}] Exiting emergency mode", ctx.intersection_id);
    });
}

/// Configure priority-based transitions for complex scenarios
#[cfg(feature = "guards")]
fn configure_priority_transitions(
    builder: &mut StateMachineBuilder<TrafficLightState, TrafficLightEvent, TrafficContext>,
) {
    // High-priority pedestrian crossing during low traffic
    builder
        .external_transition()
        .from(TrafficLightState::Green)
        .to(TrafficLightState::Yellow)
        .on(TrafficLightEvent::PedestrianRequest)
        .when(|_s, _e, ctx| ctx.traffic_density < 0.3 && ctx.pedestrian_waiting)
        .with_priority(100)
        .perform(|_s, _e, ctx| {
            println!(
                "[{}] Pedestrian priority - changing to yellow",
                ctx.intersection_id
            );
        });

    // Normal pedestrian request
    builder
        .external_transition()
        .from(TrafficLightState::Green)
        .to(TrafficLightState::Yellow)
        .on(TrafficLightEvent::PedestrianRequest)
        .when(|_s, _e, ctx| {
            ctx.pedestrian_waiting && ctx.time_in_state > std::time::Duration::from_secs(10)
        })
        .with_priority(50)
        .perform(|_s, _e, ctx| {
            println!("[{}] Pedestrian request accepted", ctx.intersection_id);
        });

    // Rush hour handling - extend green time
    builder
        .internal_transition()
        .within(TrafficLightState::Green)
        .on(TrafficLightEvent::Timer)
        .when(|_s, _e, ctx| {
            ctx.traffic_density > 0.8 && ctx.time_in_state < std::time::Duration::from_secs(90)
        })
        .with_priority(200)
        .perform(|_s, _e, ctx| {
            println!(
                "[{}] High traffic - extending green phase",
                ctx.intersection_id
            );
        });
}

/// Configure timeouts for safety
#[cfg(feature = "timeout")]
fn configure_timeouts(
    builder: &mut StateMachineBuilder<TrafficLightState, TrafficLightEvent, TrafficContext>,
) {
    use std::time::Duration;

    // Safety timeout - Yellow shouldn't last too long
    builder.with_state_timeout(
        TrafficLightState::Yellow,
        Duration::from_secs(5),
        TrafficLightState::Red,
        TrafficLightEvent::Timer,
    );

    // Emergency timeout - Auto-clear if no manual clear
    builder.with_state_timeout(
        TrafficLightState::Emergency,
        Duration::from_secs(300), // 5 minutes
        TrafficLightState::Red,
        TrafficLightEvent::EmergencyCleared,
    );
}

/// Simulate the traffic light system
pub fn simulate_traffic_light_system() {
    println!("=== Traffic Light Control System Demo ===\n");

    let state_machine = build_traffic_light_system();

    let mut context = TrafficContext {
        intersection_id: "Main-St-First-Ave".to_string(),
        traffic_density: 0.5,
        pedestrian_waiting: false,
        emergency_active: false,
        time_in_state: std::time::Duration::from_secs(0),
    };

    // Normal cycle
    println!("--- Normal Traffic Cycle ---");
    let states_and_events = vec![
        (TrafficLightState::Green, TrafficLightEvent::Timer),
        (TrafficLightState::Yellow, TrafficLightEvent::Timer),
        (TrafficLightState::Red, TrafficLightEvent::Timer),
    ];

    for (state, event) in states_and_events {
        match state_machine.fire_event(state, event, context.clone()) {
            Ok(new_state) => {
                println!("  -> Now in {:?} state\n", new_state);
            }
            Err(e) => {
                eprintln!("  ERROR: {}\n", e);
            }
        }
        std::thread::sleep(std::time::Duration::from_millis(500));
    }

    // Emergency vehicle scenario
    println!("--- Emergency Vehicle Detected ---");
    context.emergency_active = true;

    match state_machine.fire_event(
        TrafficLightState::Green,
        TrafficLightEvent::EmergencyVehicleDetected,
        context.clone(),
    ) {
        Ok(new_state) => {
            println!("  -> Now in {:?} state\n", new_state);

            // Clear emergency after some time
            std::thread::sleep(std::time::Duration::from_secs(2));
            context.emergency_active = false;

            match state_machine.fire_event(
                new_state,
                TrafficLightEvent::EmergencyCleared,
                context.clone(),
            ) {
                Ok(cleared_state) => {
                    println!("  -> Emergency cleared, now in {:?} state\n", cleared_state);
                }
                Err(e) => eprintln!("  ERROR clearing emergency: {}\n", e),
            }
        }
        Err(e) => eprintln!("  ERROR handling emergency: {}\n", e),
    }

    // Feature-specific demonstrations
    #[cfg(feature = "history")]
    demonstrate_history(&state_machine);

    #[cfg(feature = "metrics")]
    demonstrate_metrics(&state_machine);

    #[cfg(feature = "visualization")]
    demonstrate_visualization(&state_machine);
}

#[cfg(feature = "history")]
fn demonstrate_history(
    state_machine: &StateMachine<TrafficLightState, TrafficLightEvent, TrafficContext>,
) {
    println!("--- Transition History ---");
    let history = state_machine.get_history();
    for (i, record) in history.iter().enumerate() {
        println!(
            "  {}. {:?} -> {:?} via {:?} ({})",
            i + 1,
            record.from,
            record.to,
            record.event,
            if record.success { "" } else { "" }
        );
    }
    println!();
}

#[cfg(feature = "metrics")]
fn demonstrate_metrics(
    state_machine: &StateMachine<TrafficLightState, TrafficLightEvent, TrafficContext>,
) {
    println!("--- Performance Metrics ---");
    let metrics = state_machine.get_metrics();
    println!("  Total transitions: {}", metrics.total_transitions);
    println!("  Success rate: {:.1}%", metrics.success_rate() * 100.0);
    if let Some(avg_time) = metrics.average_transition_time() {
        println!("  Average transition time: {:?}", avg_time);
    }
    println!("  State visits:");
    for (state, count) in &metrics.state_visit_counts {
        println!("    {}: {} times", state, count);
    }
    println!();
}

#[cfg(feature = "visualization")]
fn demonstrate_visualization(
    state_machine: &StateMachine<TrafficLightState, TrafficLightEvent, TrafficContext>,
) {
    println!("--- State Machine Visualization ---");
    println!("Saving to 'traffic_light.dot' and 'traffic_light.puml'");

    let dot = state_machine.to_dot();
    let plantuml = state_machine.to_plantuml();

    // In a real application, you would write these to files
    if let Err(e) = std::fs::write("traffic_light.dot", dot) {
        eprintln!("Failed to write DOT file: {}", e);
    }

    if let Err(e) = std::fs::write("traffic_light.puml", plantuml) {
        eprintln!("Failed to write PlantUML file: {}", e);
    }

    println!("  ✓ Visualization files created\n");
}

/// Example of using the traffic light system with different feature sets
fn main() {
    // Check which features are enabled and inform the user
    println!("Enabled features:");
    #[cfg(feature = "history")]
    println!("  ✓ history");
    #[cfg(feature = "extended")]
    println!("  ✓ extended");
    #[cfg(feature = "metrics")]
    println!("  ✓ metrics");
    #[cfg(feature = "guards")]
    println!("  ✓ guards");
    #[cfg(feature = "timeout")]
    println!("  ✓ timeout");
    #[cfg(feature = "visualization")]
    println!("  ✓ visualization");
    println!();

    // Run the simulation
    simulate_traffic_light_system();

    // Show how to use different feature combinations
    println!("--- Feature Combination Examples ---");

    #[cfg(all(feature = "history", feature = "metrics"))]
    {
        println!("With history + metrics: Full audit trail with performance analysis");
    }

    #[cfg(all(feature = "extended", feature = "guards"))]
    {
        println!("With extended + guards: Complex state logic with prioritized transitions");
    }

    #[cfg(not(any(feature = "history", feature = "extended", feature = "metrics")))]
    {
        println!("Running with minimal features - core functionality only");
    }
}