dust

Pipeline

Introduction

A pipeline sends one value through a sequence of asynchronous steps. Each step receives the value and a Next continuation: it may change the value, pass it on, or return without calling next to stop the remaining steps.

Use a pipeline when a flow has several independent stages that you want to compose, reuse, and test one by one, such as validating an order, authorizing a user, charging a card, and saving the result.

The type of the value stays the same through every pipe. Use then to transform it into the final result.

Writing pipes

Closure pipes

The shortest pipe is a closure wrapped with pipe:

rust
use dust::pipeline::{Pipeline, pipe};pub async fn total() -> dust::Result<i32> {    Pipeline::send(10)        .pipe(pipe(|value, next| async move { next(value + 5).await }))        .then_return()        .await}

A closure receives the value and next. It may do work before or after next:

rust
use dust::pipeline::{Pipeline, pipe};pub async fn total() -> dust::Result<i32> {    Pipeline::send(10)        .pipe(pipe(|value, next| async move {            println!("before: {value}");            let value = next(value + 5).await?;            println!("after: {value}");            Ok(value)        }))        .then_return()        .await}

Struct pipes

For a pipe with dependencies or a reusable name, implement Pipe. The trait returns a boxed future, so it works in a trait object:

rust
use dust::pipeline::{Next, Pipe};use dust::Result;use futures_util::future::BoxFuture;pub struct Order {    pub total: i32,    pub charged: bool,}pub struct ChargeCard;impl Pipe<Order> for ChargeCard {    fn handle<'a>(&'a self, mut order: Order, next: Next<Order>) -> BoxFuture<'a, Result<Order>> {        Box::pin(async move {            order.charged = true;            next(order).await        })    }}

A pipe that only needs to inspect or change the value can ignore next:

rust
use dust::pipeline::{Next, Pipe};use dust::Result;use futures_util::future::BoxFuture;pub struct NormalizeEmail;impl Pipe<Order> for NormalizeEmail {    fn handle<'a>(&'a self, mut order: Order, next: Next<Order>) -> BoxFuture<'a, Result<Order>> {        order.total = order.total.max(0);        Box::pin(next(order))    }}pub struct Order {    pub total: i32,}

Building a pipeline

Start with send, add pipes with pipe (one) or through / pipes (many), and finish with then or then_return:

rust
use dust::pipeline::Pipeline;pub async fn checkout(order: Order) -> dust::Result<bool> {    Pipeline::send(order)        .pipe(ValidateOrder)        .pipe(ChargeCard)        .then(|order| async move { Ok(order.charged) })        .await}pub struct Order {    pub charged: bool,}pub struct ValidateOrder;impl dust::pipeline::Pipe<Order> for ValidateOrder {    fn handle<'a>(        &'a self,        order: Order,        next: dust::pipeline::Next<Order>,    ) -> futures_util::future::BoxFuture<'a, dust::Result<Order>> {        Box::pin(next(order))    }}pub struct ChargeCard;impl dust::pipeline::Pipe<Order> for ChargeCard {    fn handle<'a>(        &'a self,        mut order: Order,        next: dust::pipeline::Next<Order>,    ) -> futures_util::future::BoxFuture<'a, dust::Result<Order>> {        Box::pin(async move {            order.charged = true;            next(order).await        })    }}

then runs after the pipes and receives the value that came out of the last pipe. then_return is the short form when the pipeline's value is the result:

rust
use dust::pipeline::Pipeline;pub async fn checkout(order: Order) -> dust::Result<Order> {    Pipeline::send(order).pipe(ValidateOrder).then_return().await}

Stopping early

A pipe that returns without calling next stops the remaining pipes. Its value still reaches then. This is useful when a later stage is unnecessary:

rust
use dust::pipeline::{Pipeline, pipe};pub async fn checkout(user: User) -> dust::Result<Vec<Order>> {    Pipeline::send(user)        .pipe(pipe(|user, next| async move {            if user.email_verified {                next(user).await            } else {                Ok(user)            }        }))        .pipe(pipe(|user, next| async move { next(load_orders(user).await?).await }))        .then(|user| async move { Ok(user.orders) })        .await}pub struct User {    pub email_verified: bool,    pub orders: Vec<Order>,}pub struct Order;pub async fn load_orders(user: User) -> dust::Result<User> {    Ok(user)}

A pipe that returns an error stops the pipeline as well. Calling next after the last pipe runs the pipeline's final continuation and returns the value.

Boxed pipes

through and pipes accept an iterator of boxed pipes. This is how you store a pipeline built at runtime or mix pipe types in one collection:

rust
use dust::pipeline::{Pipe, Pipeline};pub async fn checkout(order: Order) -> dust::Result<Order> {    let pipes: Vec<Box<dyn Pipe<Order>>> = vec![Box::new(ValidateOrder), Box::new(ChargeCard)];    Pipeline::send(order).through(pipes).then_return().await}

For one-off pipes, prefer pipe, which keeps the concrete type:

rust
Pipeline::send(order)    .pipe(ValidateOrder)    .pipe(ChargeCard)    .then_return()    .await?;

Errors

Pipes return dust::Result<T>. Use ? as usual; the first error stops the pipeline and reaches the caller unchanged. A pipe that can fail should return the error instead of panicking:

rust
use dust::pipeline::{Pipeline, pipe};pub async fn checkout(order: Order) -> dust::Result<Order> {    Pipeline::send(order)        .pipe(pipe(|order, next| async move {            let order = validate(order)?;            next(order).await        }))        .then_return()        .await}pub fn validate(order: Order) -> dust::Result<Order> {    Ok(order)}

Add context where the error crosses a boundary, as in any other framework code:

rust
use dust::ErrorContext as _;use dust::pipeline::{Pipeline, pipe};pub async fn checkout(order: Order) -> dust::Result<Order> {    Pipeline::send(order)        .pipe(pipe(|order, next| async move {            let order = validate(order).with_context(|| "while validating the order")?;            next(order).await        }))        .then_return()        .await}

Testing

Pipelines are ordinary async functions, so test them with #[tokio::test] or inside a #[dust::test] application test. Assert the order, the value each pipe receives, and the short-circuit case:

rust
#[tokio::test]async fn the_order_is_validated_before_it_is_charged() {    let result = Pipeline::send(order)        .pipe(ValidateOrder)        .pipe(ChargeCard)        .then_return()        .await        .unwrap();    assert!(result.charged);}

For a pipeline made of closures, test the final value. For a pipeline with side effects, use the same fakes and test services you use elsewhere in the application.

When not to use a pipeline

A pipeline keeps one value flowing through independent steps. Use something else when:

  • you need to run the steps in parallel; use task::join or futures;
  • the steps are really HTTP middleware; use middleware;
  • the work must survive a deploy or a crash; dispatch a queued job or a workflow;
  • only one step exists; call the function directly.

A pipeline is not a replacement for a queue or a workflow. It is a composition tool for the code that runs inside one request, command, or job.