Skip to main content

iscsi_client_rs/state_machine/
common.rs

1//! This module defines common traits and enums for the state machine.
2//! It provides the core building blocks for defining and executing state
3//! machines.
4
5// SPDX-License-Identifier: AGPL-3.0-or-later
6// Copyright (C) 2012-2025 Andrei Maltsev
7
8use std::future::Future;
9
10use anyhow::Result;
11use tokio_util::sync::CancellationToken;
12
13/// Represents the outcome of a state transition.
14pub enum Transition<S, R> {
15    /// Move to the next state.
16    Next(S, R),
17    /// Remain in the current state.
18    Stay(R),
19    /// The state machine has completed.
20    Done(R),
21}
22
23/// A trait for defining a state machine.
24pub trait StateMachine<Ctx, Resp>: Sized {
25    /// The future returned by the `step` method.
26    type StepResult<'a>: Future<Output = Resp> + Send + 'a
27    where
28        Self: 'a,
29        Resp: 'a,
30        Ctx: 'a;
31
32    /// Executes a single step of the state machine.
33    fn step<'a>(&'a self, ctx: &'a mut Ctx) -> Self::StepResult<'a>;
34}
35
36/// A trait for executing a state machine.
37pub trait StateMachineCtx<Ctx, Out = ()>: Sized {
38    /// Executes the state machine to completion.
39    fn execute(
40        &mut self,
41        cancel: &CancellationToken,
42    ) -> impl Future<Output = Result<Out>>;
43}