xmachines-workflow 6.0.0

The record protocol of a statechart run, as serde types: chunks of events, time and work results in, events, snapshots and rejections out, faults as data
Documentation
//! A run as a stream stage: [`workflow`] reads chunks from a stream and
//! gives their records and faults as a stream, over `futures_core::Stream`
//! alone, so it runs on any executor, or none, and on every target.

use std::collections::VecDeque;
use std::pin::Pin;
use std::task::{Context, Poll};

use futures_core::Stream;

use crate::input::Chunk;
use crate::record::Fault;
use crate::step::Stepper;

/// The stream of [`workflow`]: the opening records, then the records of
/// each chunk of its source, in order, and each fault as an `Err`.
#[derive(Debug)]
pub struct Workflow<S, St: Stepper> {
    source: S,
    stepper: St,
    ready: VecDeque<Result<St::Record, Fault>>,
    /// Whether the stream ends once `ready` is given: the source ended, or
    /// the run had a fault it can't go on from.
    ended: bool,
}

/// A run as a stream: `stepper` applies each chunk `source` gives, and the
/// stream gives `opening`, then each chunk's records, then, of a chunk that
/// was a fault, the fault as an `Err`. A fault the run goes on after
/// ([`crate::FaultCode::is_recoverable`]) is followed by the next chunk's
/// records; any other ends the stream after it.
///
/// Backpressure is the poll itself: nothing is read from `source` until the
/// last chunk's records are taken. No clock, no timer, no task: time is an
/// input, as in the stepper.
///
/// ```
/// use std::sync::Arc;
/// use std::task::{Context, Poll, Waker};
/// use serde_json::{json, Value};
/// use futures_core::Stream;
/// use xmachines_runtime::{Machine, Registry};
/// use xmachines_workflow::{workflow, Chunk, Options, Run};
///
/// /// A stream of the chunks of a list, ready at once.
/// struct Chunks(std::vec::IntoIter<Chunk<Value>>);
/// impl Stream for Chunks {
///     type Item = Chunk<Value>;
///     fn poll_next(mut self: std::pin::Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
///         Poll::Ready(self.0.next())
///     }
/// }
///
/// let machine = Arc::new(Machine::<Value, Value>::from_json(
///     &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
///     &Registry::new(),
/// ).unwrap());
/// let (run, opening) = Run::open(machine, Options::default()).unwrap();
/// let chunks = Chunks(vec![Chunk::One(json!({ "type": "go" }))].into_iter());
/// let mut records = workflow(chunks, run, opening);
/// let mut cx = Context::from_waker(Waker::noop());
/// let mut seqs = Vec::new();
/// while let Poll::Ready(Some(record)) = std::pin::Pin::new(&mut records).poll_next(&mut cx) {
///     seqs.push(record.unwrap().seq());
/// }
/// assert_eq!(seqs, [0, 1]);
/// ```
pub fn workflow<S, St>(source: S, stepper: St, opening: Vec<St::Record>) -> Workflow<S, St>
where
    S: Stream<Item = Chunk<St::Input>>,
    St: Stepper,
{
    Workflow { source, stepper, ready: opening.into_iter().map(Ok).collect(), ended: false }
}

impl<S, St: Stepper> Workflow<S, St> {
    /// The stepper, as the stream left it: its `seq`, a checkpoint of it.
    pub fn stepper(&self) -> &St {
        &self.stepper
    }
}

impl<S, St> Stream for Workflow<S, St>
where
    S: Stream<Item = Chunk<St::Input>> + Unpin,
    St: Stepper + Unpin,
    St::Record: Unpin,
{
    type Item = Result<St::Record, Fault>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        loop {
            if let Some(item) = this.ready.pop_front() {
                return Poll::Ready(Some(item));
            }
            if this.ended {
                return Poll::Ready(None);
            }
            match Pin::new(&mut this.source).poll_next(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(None) => this.ended = true,
                Poll::Ready(Some(chunk)) => {
                    let mut records = Vec::new();
                    let result = this.stepper.apply(chunk, &mut records);
                    this.ready.extend(records.into_iter().map(Ok));
                    if let Err(fault) = result {
                        this.ended = !fault.code.is_recoverable();
                        this.ready.push_back(Err(fault));
                    }
                }
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.ready.len(), if self.ended { Some(self.ready.len()) } else { None })
    }
}