Skip to main content

pipeline_toolkit/
step.rs

1use crate::{AccessSpec, Context};
2
3/// What a [`Step`] wants the [`Pipeline`](crate::Pipeline) to do next.
4///
5/// # Examples
6///
7/// ```
8/// use pipeline_toolkit::Flow;
9///
10/// let flow: Flow<i32> = Flow::Done(42);
11/// assert!(matches!(flow, Flow::Done(42)));
12/// ```
13pub enum Flow<Out> {
14    /// Move on to the next step, unchanged.
15    Continue,
16    /// Stop the pipeline and produce this as its output.
17    Done(Out),
18}
19
20/// The error type returned by [`Step::run`].
21///
22/// Wraps any `Send + Sync` [`std::error::Error`], so a step can propagate
23/// whatever failure it produces (I/O, parsing, a domain error) through
24/// [`Self::new`]'s `impl Into<Box<dyn Error>>` bound.
25///
26/// # Examples
27///
28/// ```
29/// use pipeline_toolkit::StepError;
30///
31/// let err = StepError::new("failed to load config");
32/// assert_eq!(err.to_string(), "failed to load config");
33/// ```
34#[derive(Debug, thiserror::Error)]
35#[error("{source}")]
36pub struct StepError {
37    source: Box<dyn std::error::Error + Send + Sync>,
38}
39
40impl StepError {
41    /// Wraps `source` as a [`StepError`].
42    ///
43    /// # Examples
44    ///
45    /// ```
46    /// use pipeline_toolkit::StepError;
47    ///
48    /// #[derive(Debug, thiserror::Error)]
49    /// #[error("connection refused")]
50    /// struct ConnectError;
51    ///
52    /// let err = StepError::new(ConnectError);
53    /// assert_eq!(err.to_string(), "connection refused");
54    /// ```
55    pub fn new(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
56        Self {
57            source: source.into(),
58        }
59    }
60
61    /// Consumes this error, returning the wrapped source downcast to `E` if
62    /// it was one, or the original [`StepError`] back otherwise.
63    ///
64    /// Used internally by [`Branch`](crate::Branch) to smuggle a full
65    /// [`PipelineError`](crate::PipelineError) across [`Step::run`]'s fixed
66    /// `StepError` return type, so a nested arm's
67    /// [`AccessViolation`](crate::AccessViolation)/`NoMatchingBranch`
68    /// surfaces from [`Pipeline::run`](crate::Pipeline::run) as itself
69    /// rather than wrapped in an outer [`PipelineError::Step`](crate::PipelineError::Step).
70    pub(crate) fn downcast<E: std::error::Error + Send + Sync + 'static>(self) -> Result<E, Self> {
71        match self.source.downcast::<E>() {
72            Ok(boxed) => Ok(*boxed),
73            Err(source) => Err(Self { source }),
74        }
75    }
76}
77
78/// A single unit of work in a [`Pipeline`](crate::Pipeline).
79///
80/// A step reads and writes typed values from the shared [`Context`] rather
81/// than taking or returning them directly, which is what lets
82/// [`PipelineBuilder`](crate::PipelineBuilder) wire arbitrary steps together
83/// and validate the wiring without knowing their concrete types.
84/// [`Self::access`] is the declaration
85/// [`PipelineBuilder::build`](crate::PipelineBuilder::build) and [`Context`]
86/// check that declaration against: a step's [`Self::run`] must not read,
87/// write, or take a type it didn't declare, or
88/// [`Pipeline::run`](crate::Pipeline::run) fails with
89/// [`PipelineError::AccessViolation`](crate::PipelineError::AccessViolation).
90///
91/// # Examples
92///
93/// ```
94/// use pipeline_toolkit::{AccessSpec, Context, Flow, Step, StepError};
95///
96/// struct Double;
97///
98/// #[async_trait::async_trait]
99/// impl Step<i32> for Double {
100///     fn name(&self) -> &str {
101///         "double"
102///     }
103///
104///     fn access(&self) -> AccessSpec {
105///         AccessSpec::new().reads::<i32>()
106///     }
107///
108///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
109///         let value = *ctx.get::<i32>().expect("declared as read");
110///         Ok(Flow::Done(value * 2))
111///     }
112/// }
113/// ```
114///
115/// See the [crate-level example](crate) for wiring a step like this into a
116/// running pipeline.
117#[async_trait::async_trait]
118pub trait Step<Out>: Send + Sync {
119    /// Must consistently return the same value for the lifetime of the
120    /// step. [`PipelineBuilder::build`](crate::PipelineBuilder::build) calls
121    /// this once and reuses the result for the rest of the pipeline's life
122    /// instead of calling it again at run time.
123    fn name(&self) -> &str;
124
125    /// Must consistently return an equivalent [`AccessSpec`] for the
126    /// lifetime of the step, for the same reason as [`Self::name`].
127    fn access(&self) -> AccessSpec;
128
129    /// Performs this step's work against the shared context.
130    ///
131    /// Returning [`Flow::Continue`] hands off to the next step;
132    /// [`Flow::Done`] stops the pipeline and produces that value as its
133    /// output.
134    ///
135    /// # Errors
136    ///
137    /// Returns a [`StepError`] wrapping whatever domain-specific failure
138    /// prevented this step from completing.
139    async fn run(&self, ctx: &mut Context) -> Result<Flow<Out>, StepError>;
140}
141
142#[cfg(test)]
143mod test {
144    use std::error::Error;
145    use std::fmt::Display;
146
147    use super::*;
148    use crate::test_support::block_on;
149
150    #[derive(Debug)]
151    struct DummyError(String);
152
153    impl Display for DummyError {
154        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
155            write!(f, "{}", self.0)
156        }
157    }
158
159    impl Error for DummyError {}
160
161    #[test]
162    fn new_wraps_source_error_accessible_via_source_downcast() {
163        let err = StepError::new(DummyError("boom".to_string()));
164        let source = err.source().expect("source should be present");
165        let dummy = source
166            .downcast_ref::<DummyError>()
167            .expect("source should downcast to DummyError");
168        assert_eq!(dummy.0, "boom");
169    }
170
171    #[test]
172    fn display_delegates_to_source_display() {
173        let err = StepError::new(DummyError("boom".to_string()));
174        assert_eq!(err.to_string(), "boom");
175    }
176
177    #[test]
178    fn new_accepts_str_via_into() {
179        let err = StepError::new("boom");
180        assert_eq!(err.to_string(), "boom");
181    }
182
183    #[test]
184    fn new_accepts_string_via_into() {
185        let err = StepError::new(String::from("boom"));
186        assert_eq!(err.to_string(), "boom");
187    }
188
189    #[test]
190    fn implements_std_error_trait_with_some_source() {
191        let err = StepError::new("boom");
192        let as_dyn: &dyn Error = &err;
193        assert!(as_dyn.source().is_some());
194    }
195
196    #[test]
197    fn new_accepts_empty_string_message() {
198        let err = StepError::new("");
199        assert_eq!(err.to_string(), "");
200    }
201
202    struct Marker(i32);
203
204    enum Outcome {
205        Continue,
206        Done(i32),
207        Err(&'static str),
208        InsertMarker(i32),
209    }
210
211    struct TestStep {
212        name: &'static str,
213        access: AccessSpec,
214        outcome: Outcome,
215    }
216
217    #[async_trait::async_trait]
218    impl Step<i32> for TestStep {
219        fn name(&self) -> &str {
220            self.name
221        }
222
223        fn access(&self) -> AccessSpec {
224            self.access.clone()
225        }
226
227        async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
228            match &self.outcome {
229                Outcome::Continue => Ok(Flow::Continue),
230                Outcome::Done(v) => Ok(Flow::Done(*v)),
231                Outcome::Err(msg) => Err(StepError::new(*msg)),
232                Outcome::InsertMarker(v) => {
233                    ctx.insert(Marker(*v));
234                    Ok(Flow::Continue)
235                }
236            }
237        }
238    }
239
240    #[test]
241    fn step_name_returns_configured_name() {
242        let step = TestStep {
243            name: "load",
244            access: AccessSpec::new(),
245            outcome: Outcome::Continue,
246        };
247        assert_eq!(step.name(), "load");
248    }
249
250    #[test]
251    fn step_access_returns_configured_spec() {
252        let step = TestStep {
253            name: "load",
254            access: AccessSpec::new().reads::<Marker>(),
255            outcome: Outcome::Continue,
256        };
257        assert!(step.access().can_read(std::any::TypeId::of::<Marker>()));
258    }
259
260    #[test]
261    fn step_run_returns_continue_variant() {
262        let step = TestStep {
263            name: "s",
264            access: AccessSpec::new(),
265            outcome: Outcome::Continue,
266        };
267        let mut ctx = Context::new();
268        let result = block_on(step.run(&mut ctx));
269        assert!(matches!(result, Ok(Flow::Continue)));
270    }
271
272    #[test]
273    fn step_run_returns_done_variant_with_value() {
274        let step = TestStep {
275            name: "s",
276            access: AccessSpec::new(),
277            outcome: Outcome::Done(42),
278        };
279        let mut ctx = Context::new();
280        let result = block_on(step.run(&mut ctx));
281        assert!(matches!(result, Ok(Flow::Done(42))));
282    }
283
284    #[test]
285    fn step_run_propagates_err_variant() {
286        let step = TestStep {
287            name: "s",
288            access: AccessSpec::new(),
289            outcome: Outcome::Err("boom"),
290        };
291        let mut ctx = Context::new();
292        match block_on(step.run(&mut ctx)) {
293            Err(err) => assert_eq!(err.to_string(), "boom"),
294            Ok(_) => panic!("expected Err"),
295        }
296    }
297
298    #[test]
299    fn step_run_receives_context_and_can_read_write_it() {
300        let step = TestStep {
301            name: "s",
302            access: AccessSpec::new(),
303            outcome: Outcome::InsertMarker(7),
304        };
305        let mut ctx = Context::new();
306        block_on(step.run(&mut ctx)).unwrap();
307        assert_eq!(ctx.get::<Marker>().map(|m| m.0), Some(7));
308    }
309
310    #[test]
311    fn step_trait_object_is_usable_as_dyn_step() {
312        let step: Box<dyn Step<i32>> = Box::new(TestStep {
313            name: "boxed",
314            access: AccessSpec::new(),
315            outcome: Outcome::Done(1),
316        });
317        assert_eq!(step.name(), "boxed");
318        let mut ctx = Context::new();
319        let result = block_on(step.run(&mut ctx));
320        assert!(matches!(result, Ok(Flow::Done(1))));
321    }
322}