Skip to main content

tokio_fsm/
core.rs

1//! Core runtime types for tokio-fsm.
2
3/// Represents a state transition in the FSM.
4///
5/// This type is returned by FSM handlers to indicate which state the machine
6/// should transition to next. It is usually created via the [`Transition::to`] helper.
7///
8/// # Example
9///
10/// ```rust
11/// # use tokio_fsm::Transition;
12/// # struct Running;
13/// async fn my_handler() -> Transition<Running> {
14///     // Perform some async logic...
15///     Transition::to(Running)
16/// }
17/// ```
18#[derive(Debug)]
19pub enum Transition<T> {
20    /// Transition to the specified target state.
21    To(T),
22}
23
24impl<T> Transition<T> {
25    /// Creates a new transition to the specified target state.
26    ///
27    /// The target state must be a valid state defined within the FSM.
28    #[must_use]
29    pub fn to(state: T) -> Self {
30        Self::To(state)
31    }
32
33    /// Extracts the target state from the transition.
34    ///
35    /// Internal-only: This is typically used by the generated event loop.
36    #[must_use]
37    pub fn into_state(self) -> T {
38        match self {
39            Self::To(state) => state,
40        }
41    }
42}
43
44/// Shutdown mode for the FSM.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum ShutdownMode {
47    /// Graceful shutdown: The event loop continues to process all remaining
48    /// events currently in the queue before terminating and returning the context.
49    Graceful,
50    /// Immediate shutdown: The event loop terminates immediately, dropping any
51    /// unprocessed events in the queue, and returns the current context.
52    Immediate,
53}
54
55/// Error type returned by the FSM background task.
56///
57/// This enum distinguishes between logical errors returned by your FSM handlers
58/// and runtime failures of the Tokio task itself (e.g., panics or cancellation).
59///
60/// # Type Parameters
61///
62/// * `E`: The logical error type defined in your `impl` block via `type Error = ...;`.
63#[derive(Debug, thiserror::Error)]
64pub enum TaskError<E> {
65    /// The FSM handler returned a logical error.
66    #[error("FSM error: {0}")]
67    Fsm(E),
68    /// The background task failed due to a panic or external cancellation.
69    #[error("Task join error: {0}")]
70    Join(#[from] tokio::task::JoinError),
71}