use super::pipe::{Next, StepFn};
use crate::contracts::pipeline::Pipeable;
use std::future::Future;
use std::sync::Arc;
pub struct Pipeline<T, R = T> {
passable: Option<Box<T>>,
pipes: Vec<Arc<dyn Pipeable<T, R>>>,
}
impl<T, R> Clone for Pipeline<T, R> {
fn clone(&self) -> Self {
Self {
passable: None,
pipes: self.pipes.clone(),
}
}
}
impl<T: Send + 'static, R: Send + 'static> Default for Pipeline<T, R> {
fn default() -> Self {
Self::new()
}
}
impl<T: Send + 'static, R: Send + 'static> Pipeline<T, R> {
pub fn new() -> Self {
Self {
passable: None,
pipes: Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
self.pipes.is_empty()
}
pub fn send(mut self, passable: T) -> Self {
self.passable = Some(Box::new(passable));
self
}
pub fn through<I, P>(mut self, pipes: I) -> Self
where
I: IntoIterator<Item = P>,
P: Pipeable<T, R> + 'static,
{
self.pipes = pipes
.into_iter()
.map(|p| -> Arc<dyn Pipeable<T, R>> { Arc::new(p) })
.collect();
self
}
pub fn prepend<I, P>(mut self, pipes: I) -> Self
where
I: IntoIterator<Item = P>,
P: Pipeable<T, R> + 'static,
{
let prepended: Vec<Arc<dyn Pipeable<T, R>>> = pipes
.into_iter()
.map(|p| -> Arc<dyn Pipeable<T, R>> { Arc::new(p) })
.collect();
self.pipes.splice(0..0, prepended);
self
}
pub fn append<I, P>(mut self, pipes: I) -> Self
where
I: IntoIterator<Item = P>,
P: Pipeable<T, R> + 'static,
{
self.pipes.extend(
pipes
.into_iter()
.map(|p| -> Arc<dyn Pipeable<T, R>> { Arc::new(p) }),
);
self
}
pub fn pipe<P>(mut self, pipe: P) -> Self
where
P: Pipeable<T, R> + 'static,
{
self.pipes.push(Arc::new(pipe));
self
}
pub(crate) fn compose(&self, destination: StepFn<T, R>) -> StepFn<T, R> {
self.pipes.iter().rev().fold(destination, |next, pipe| {
let pipe = Arc::clone(pipe);
Arc::new(move |passable| {
let p = Arc::clone(&pipe);
let n = Next::new(Arc::clone(&next));
Box::pin(async move { p.handle(passable, n).await })
})
})
}
pub async fn then<F, Fut>(mut self, destination: F) -> R
where
F: Fn(T) -> Fut + Send + Sync + 'static,
Fut: Future<Output = R> + Send + 'static,
{
let passable = *self
.passable
.take()
.expect("Cannot execute pipeline without setting a passable payload via send()");
let dest: StepFn<T, R> = Arc::new(move |passable| Box::pin(destination(passable)));
let chain = self.compose(dest);
chain(passable).await
}
}
impl<T: Send + 'static> Pipeline<T, T> {
pub async fn then_return(self) -> T {
self.then(|passable| async move { passable }).await
}
}