Skip to main content

ranvier_core/
transition.rs

1//! # Transition: Typed State Transformation
2//!
3//! The `Transition` trait defines the contract for state transformations within a Decision Tree.
4//!
5//! ## Design Philosophy
6//!
7//! * **Explicit Input/Output**: Every transition declares `From` and `To` types
8//! * **No Hidden Effects**: All effects must go through the `Bus`
9//! * **Outcome-Based Control Flow**: Returns `Outcome` not `Result`
10
11use crate::bus::{Bus, BusAccessPolicy};
12use crate::outcome::Outcome;
13use async_trait::async_trait;
14use std::fmt::Debug;
15
16/// Resource requirement for a transition.
17///
18/// This trait is used to mark types that can be injected as resources.
19/// Implementations should usually be a struct representing a bundle of resources.
20pub trait ResourceRequirement: Send + Sync + 'static {}
21
22/// Blanket implementation for () if no resources are needed.
23impl ResourceRequirement for () {}
24
25/// The contract for a Typed State Transition.
26///
27/// `Transition` converts state `From` to `Outcome<To, Error>`.
28/// All transitions are async and receive access to the `Bus` for resource injection.
29///
30/// ## Example
31///
32/// ```rust
33/// use async_trait::async_trait;
34/// use ranvier_core::prelude::*;
35///
36/// # #[derive(Clone)]
37/// # struct ValidateUser;
38/// # #[async_trait::async_trait]
39/// # impl Transition<String, String> for ValidateUser {
40/// #     type Error = std::convert::Infallible;
41/// #     type Resources = ();
42/// #     async fn run(
43/// #         &self,
44/// #         input: String,
45/// #         _resources: &Self::Resources,
46/// #         _bus: &mut Bus,
47/// #     ) -> Outcome<String, Self::Error> {
48/// #         Outcome::next(format!("validated: {}", input))
49/// #     }
50/// # }
51/// #
52/// # #[async_trait::async_trait]
53/// # impl Transition<i32, i32> for DoubleValue {
54/// #     type Error = std::convert::Infallible;
55/// #     type Resources = ();
56/// #     async fn run(
57/// #         &self,
58/// #         input: i32,
59/// #         _resources: &Self::Resources,
60/// #         _bus: &mut Bus,
61/// #     ) -> Outcome<i32, Self::Error> {
62/// #         Outcome::next(input * 2)
63/// #     }
64/// # }
65/// # struct DoubleValue;
66/// ```
67#[async_trait]
68pub trait Transition<From, To>: Send + Sync + 'static
69where
70    From: Send + 'static,
71    To: Send + 'static,
72{
73    /// Domain-specific error type (e.g., AuthError, ValidationError)
74    type Error: Send + Sync + Debug + 'static;
75
76    /// The type of resources required by this transition.
77    /// This follows the "Hard-Wired Types" principle from the Master Plan.
78    type Resources: ResourceRequirement;
79
80    /// Execute the transition.
81    ///
82    /// # Parameters
83    ///
84    /// * `state` - The input state of type `From`
85    /// * `resources` - Typed access to required resources
86    /// * `bus` - The base Bus (for cross-cutting concerns like telemetry)
87    ///
88    /// # Returns
89    ///
90    /// An `Outcome<To, Self::Error>` determining the next step.
91    /// Returns a human-readable label for this transition.
92    /// Defaults to the type name.
93    fn label(&self) -> String {
94        let full = std::any::type_name::<Self>();
95        full.split("::").last().unwrap_or(full).to_string()
96    }
97
98    /// Returns a detailed description of what this transition does.
99    fn description(&self) -> Option<String> {
100        None
101    }
102
103    /// Optional transition-scoped Bus access policy (M143).
104    ///
105    /// Default is unrestricted access for backward compatibility.
106    fn bus_access_policy(&self) -> Option<BusAccessPolicy> {
107        None
108    }
109
110    /// Execute the transition.
111    ///
112    /// # Parameters
113    ///
114    /// * `state` - The input state of type `From`
115    /// * `resources` - Typed access to required resources
116    /// * `bus` - The base Bus (for cross-cutting concerns like telemetry)
117    ///
118    /// # Returns
119    ///
120    /// An `Outcome<To, Self::Error>` determining the next step.
121    async fn run(
122        &self,
123        state: From,
124        resources: &Self::Resources,
125        bus: &mut Bus,
126    ) -> Outcome<To, Self::Error>;
127}
128
129/// Blanket implementation for `Arc<T>` where `T: Transition`.
130///
131/// This allows sharing transitions across multiple Axons.
132#[async_trait]
133impl<T, From, To> Transition<From, To> for std::sync::Arc<T>
134where
135    T: Transition<From, To> + Send + Sync + 'static,
136    From: Send + 'static,
137    To: Send + 'static,
138{
139    type Error = T::Error;
140    type Resources = T::Resources;
141
142    async fn run(
143        &self,
144        state: From,
145        resources: &Self::Resources,
146        bus: &mut Bus,
147    ) -> Outcome<To, Self::Error> {
148        self.as_ref().run(state, resources, bus).await
149    }
150
151    fn bus_access_policy(&self) -> Option<BusAccessPolicy> {
152        self.as_ref().bus_access_policy()
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    struct AddOne;
161
162    #[async_trait]
163    impl Transition<i32, i32> for AddOne {
164        type Error = std::convert::Infallible;
165        type Resources = ();
166
167        async fn run(
168            &self,
169            state: i32,
170            _resources: &Self::Resources,
171            _bus: &mut Bus,
172        ) -> Outcome<i32, Self::Error> {
173            Outcome::Next(state + 1)
174        }
175    }
176
177    #[tokio::test]
178    async fn test_transition_basic() {
179        let mut bus = Bus::new();
180        let result = AddOne.run(41, &(), &mut bus).await;
181        assert!(matches!(result, Outcome::Next(42)));
182    }
183}