gen_fsm/handler.rs
1//! The FSM handler trait. Implementors define the state graph and
2//! event-handling logic.
3
4use std::fmt::Debug;
5
6use crate::event::{EventType, TimeoutKind};
7use crate::transition::Transition;
8
9/// User-implemented logic for a finite state machine.
10///
11/// The trait is intentionally small: pick a state type, an event type,
12/// a reply type, a stop reason, and write three methods (only
13/// [`Self::initial`] and [`Self::handle`] are required; [`Self::on_enter`]
14/// and [`Self::on_timeout`] have no-op defaults).
15pub trait FsmHandler: Sized + Send + 'static {
16 /// The set of states this FSM can be in. Typically a `Copy` enum
17 /// with no payload; the per-state context lives in `self`.
18 type State: Copy + Debug + PartialEq + Eq + Send + 'static;
19
20 /// Events the FSM accepts. Includes both external events and any
21 /// internal follow-ups posted via [`crate::Action::post_internal`].
22 type Event: Send + 'static;
23
24 /// Reply type for `Call` events.
25 type Reply: Send + 'static;
26
27 /// Reason this FSM stopped. Returned to the caller through
28 /// [`crate::FsmDriver::join`].
29 type Stop: Debug + Send + 'static;
30
31 /// The state the FSM starts in. Called once during driver
32 /// startup, before any events.
33 fn initial(&self) -> Self::State;
34
35 /// Handle one event in the given state. Return a [`Transition`]
36 /// describing where to go next and which side effects to apply.
37 ///
38 /// Called only for `Call`, `Cast`, `Info`, and `Internal`
39 /// events; `Enter` and `Timeout` events route to
40 /// [`Self::on_enter`] and [`Self::on_timeout`] respectively.
41 fn handle(
42 &mut self,
43 state: Self::State,
44 event_type: EventType,
45 event: Self::Event,
46 ) -> Transition<Self>;
47
48 /// Called once per transition into a state, before any mailbox
49 /// events for the new state. Default impl returns
50 /// `Transition::Keep(vec![])` (no-op).
51 ///
52 /// Override to do per-state setup (open file, start timer, log
53 /// entry, request resources).
54 fn on_enter(&mut self, state: Self::State) -> Transition<Self> {
55 let _ = state;
56 Transition::Keep(vec![])
57 }
58
59 /// Called when a timer fires. Default impl returns
60 /// `Transition::Keep(vec![])` (no-op).
61 ///
62 /// Override to react to state, event, or generic timeouts.
63 fn on_timeout(&mut self, state: Self::State, kind: TimeoutKind) -> Transition<Self> {
64 let _ = (state, kind);
65 Transition::Keep(vec![])
66 }
67}