# ESSM Cookbook
## Pattern: Event-Driven State Machine
ESSM leaves event dispatch to the user. Here's a sketch:
```rust
#[derive(Debug)]
enum Event {
Start,
Stop,
Tick,
}
trait EventHandler {
type Error;
fn handle(self, event: Event) -> Result<Self, ErrorState<Self::Error, ???, ???>>;
}
// For each state, implement EventHandler with a match on events:
impl EventHandler for Idle {
type Error = Infallible;
fn handle(self, event: Event) -> Result< ???, ???> {
match event {
Event::Start => Ok(self.try_transition()?), // -> Running
_ => Ok(self), // stay in Idle, or return an error
}
}
}
```
The async variant replaces `handle()` with `async fn handle()` and runs in a tokio event loop; the transition itself remains synchronous.
The `.try_transition()` call is available because `Idle` implements `Transition<Running>` (as defined above).
## Pattern: Self-Transition (State Update)
```rust
# use essm::{State, Transition, ErrorState};
# use core::convert::Infallible;
struct Counter { value: u32 }
impl State for Counter {}
impl Transition<Counter, Infallible> for Counter {
fn change(self, _ctx: &mut ()) -> Result<Counter, ErrorState<Infallible, Counter, Counter>> {
Ok(Counter { value: self.value + 1 })
}
}
```
## Pattern: Fallible State Construction
```rust
# use essm::{State, Transition, ErrorState};
struct Connecting { addr: &'static str }
impl State for Connecting {}
struct Connected { socket: &'static str }
impl State for Connected {}
#[derive(Debug)]
enum MyError { ConnectFailed }
impl Transition<Connected, MyError> for Connecting {
fn change(self, _ctx: &mut ()) -> Result<Connected, ErrorState<MyError, Connecting, Connected>> {
if self.addr == "bad" {
ErrorState::err_origin(MyError::ConnectFailed, self)
} else {
Ok(Connected { socket: self.addr })
}
}
}
```
## Pattern: Error Recovery
ESSM errors implement [`State`], so you can transition FROM an error state
back to a valid state.
### Generic blanket recovery
For simple cases where any error should reset to a known-safe state:
```rust
impl<E, S, T> Transition<Idle, E> for ErrorState<E, S, T> {
fn change(self, _ctx: &mut ()) -> Result<Idle, ErrorState<E, Self, Idle>> {
Ok(Idle)
}
}
```
### Source-specific recovery
When different error sources need different recovery strategies, use
concrete `ErrorState` instantiations:
```rust
// Parse failure: log and retry
impl Transition<Idle, ParseError> for ErrorState<ParseError, Parsing, Ready> {
fn change(self, _ctx: &mut ()) -> Result<Idle, ErrorState<ParseError, Self, Idle>> {
// Inspect self.at to decide retry strategy
Ok(Idle)
}
}
// Network failure: back off and reconnect
impl Transition<Disconnected, NetError> for ErrorState<NetError, Connecting, Connected> {
fn change(self, _ctx: &mut ()) -> Result<Disconnected, ErrorState<NetError, Self, Disconnected>> {
Ok(Disconnected)
}
}
```
### Usage
```rust
let next = match current.try_transition() {
Ok(state) => state,
Err(error_state) => {
// The error is a state; transition from it to recover
let recovered = error_state.try_transition().unwrap();
// Continue from recovered state
}
};
```
## Pattern: Bootstrap with Primordial
Use [`Primordial`] and [`InitialState`] to create the first state with
pipeline-enforced hooks:
```rust
use essm::{State, Transition, TransitionInfallible, Primordial, InitialStateInfallible, ErrorState};
use core::convert::Infallible;
#[derive(Debug)] struct Idle; impl State for Idle {}
#[derive(Debug)] struct Running; impl State for Running {}
impl Transition<Idle> for Primordial {
fn change(self, _: &mut ()) -> Result<Idle, ErrorState<Infallible, Primordial, Idle>> {
Ok(Idle)
}
}
impl Transition<Running> for Idle {
fn change(self, _: &mut ()) -> Result<Running, ErrorState<Infallible, Idle, Running>> {
Ok(Running)
}
}
let idle = Idle::new();
let running: Running = idle.transition();
```
For fallible construction, use `impl InitialState<MyError> for MyState {}`
and `try_new()`/`try_new_with()`.
## Pattern: Termination with Terminated
Use [`Terminated`] and [`TerminalState`] to end the state machine with
pipeline-enforced hooks:
```rust
use essm::{Terminated, TerminalStateInfallible, ErrorState};
use core::convert::Infallible;
impl Transition<Terminated> for Running {
fn change(self, _: &mut ()) -> Result<Terminated, ErrorState<Infallible, Running, Terminated>> {
Ok(Terminated)
}
}
let terminated = running.terminate();
```
## Pattern: State lifecycle without Primordial/Terminated
Primordial and Terminated are optional. States can be constructed directly
and destroyed by going out of scope. You must handle hooks manually:
```rust
let idle = Idle;
idle.enter::<(), Infallible>(&()).unwrap(); // manual on-entry check
idle.invariant::<Infallible>().unwrap(); // manual invariant check
// ... use the state ...
idle.leave::<(), Infallible>(&()).unwrap(); // manual on-exit check
// idle dropped here — Rust drops any Drop-implementing fields (Vec, String, etc.)
```
> **Note:** Rust E0509 forbids partial moves out of `Drop`-implementing types.
> Use [`Option::take()`](Option::take) or [`core::mem::take()`](core::mem::take)
> to extract field ownership in `change()` without destructuring. See the
> [README](#impl-drop-on-state-types) for a full example with caveats.
> Prefer [`TerminalState`] for structured teardown.
## Pattern: State Machine Wrapper with Enum Dispatch
ESSM provides typestate traits but no runtime state machine wrapper. Here's how to build one with an enum:
```rust
use essm::{State, Transition, ErrorState};
use core::convert::Infallible;
#[derive(Debug, Default)]
struct Idle;
impl State for Idle {}
#[derive(Debug, Default)]
struct Running;
impl State for Running {}
#[derive(Debug, Default)]
struct Stopped;
impl State for Stopped {}
// Each allowed transition requires an explicit impl
impl Transition<Running> for Idle {
fn change(self, _ctx: &mut ()) -> Result<Running, ErrorState<Infallible, Idle, Running>> {
Ok(Running)
}
}
// The wrapper enum
enum MachineState {
Idle(Idle),
Running(Running),
Stopped(Stopped),
}
impl MachineState {
fn start(self) -> Result<MachineState, ???> {
match self {
MachineState::Idle(s) => Ok(MachineState::Running(s.try_transition()?)),
other => Err(???), // not a valid transition from this state
}
}
}
```
(Note: the user fills in the error type; ESSM returns `ErrorState<Error, Self, Next>` which is type-specific per transition.)