Skip to main content

xmachines_workflow/
stream.rs

1//! A run as a stream stage: [`workflow`] reads chunks from a stream and
2//! gives their records and faults as a stream, over `futures_core::Stream`
3//! alone, so it runs on any executor, or none, and on every target.
4
5use std::collections::VecDeque;
6use std::pin::Pin;
7use std::task::{Context, Poll};
8
9use futures_core::Stream;
10
11use crate::input::Chunk;
12use crate::record::Fault;
13use crate::step::Stepper;
14
15/// The stream of [`workflow`]: the opening records, then the records of
16/// each chunk of its source, in order, and each fault as an `Err`.
17#[derive(Debug)]
18pub struct Workflow<S, St: Stepper> {
19    source: S,
20    stepper: St,
21    ready: VecDeque<Result<St::Record, Fault>>,
22    /// Whether the stream ends once `ready` is given: the source ended, or
23    /// the run had a fault it can't go on from.
24    ended: bool,
25}
26
27/// A run as a stream: `stepper` applies each chunk `source` gives, and the
28/// stream gives `opening`, then each chunk's records, then, of a chunk that
29/// was a fault, the fault as an `Err`. A fault the run goes on after
30/// ([`crate::FaultCode::is_recoverable`]) is followed by the next chunk's
31/// records; any other ends the stream after it.
32///
33/// Backpressure is the poll itself: nothing is read from `source` until the
34/// last chunk's records are taken. No clock, no timer, no task: time is an
35/// input, as in the stepper.
36///
37/// ```
38/// use std::sync::Arc;
39/// use std::task::{Context, Poll, Waker};
40/// use serde_json::{json, Value};
41/// use futures_core::Stream;
42/// use xmachines_runtime::{Machine, Registry};
43/// use xmachines_workflow::{workflow, Chunk, Options, Run};
44///
45/// /// A stream of the chunks of a list, ready at once.
46/// struct Chunks(std::vec::IntoIter<Chunk<Value>>);
47/// impl Stream for Chunks {
48///     type Item = Chunk<Value>;
49///     fn poll_next(mut self: std::pin::Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
50///         Poll::Ready(self.0.next())
51///     }
52/// }
53///
54/// let machine = Arc::new(Machine::<Value, Value>::from_json(
55///     &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
56///     &Registry::new(),
57/// ).unwrap());
58/// let (run, opening) = Run::open(machine, Options::default()).unwrap();
59/// let chunks = Chunks(vec![Chunk::One(json!({ "type": "go" }))].into_iter());
60/// let mut records = workflow(chunks, run, opening);
61/// let mut cx = Context::from_waker(Waker::noop());
62/// let mut seqs = Vec::new();
63/// while let Poll::Ready(Some(record)) = std::pin::Pin::new(&mut records).poll_next(&mut cx) {
64///     seqs.push(record.unwrap().seq());
65/// }
66/// assert_eq!(seqs, [0, 1]);
67/// ```
68pub fn workflow<S, St>(source: S, stepper: St, opening: Vec<St::Record>) -> Workflow<S, St>
69where
70    S: Stream<Item = Chunk<St::Input>>,
71    St: Stepper,
72{
73    Workflow { source, stepper, ready: opening.into_iter().map(Ok).collect(), ended: false }
74}
75
76impl<S, St: Stepper> Workflow<S, St> {
77    /// The stepper, as the stream left it: its `seq`, a checkpoint of it.
78    pub fn stepper(&self) -> &St {
79        &self.stepper
80    }
81}
82
83impl<S, St> Stream for Workflow<S, St>
84where
85    S: Stream<Item = Chunk<St::Input>> + Unpin,
86    St: Stepper + Unpin,
87    St::Record: Unpin,
88{
89    type Item = Result<St::Record, Fault>;
90
91    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
92        let this = self.get_mut();
93        loop {
94            if let Some(item) = this.ready.pop_front() {
95                return Poll::Ready(Some(item));
96            }
97            if this.ended {
98                return Poll::Ready(None);
99            }
100            match Pin::new(&mut this.source).poll_next(cx) {
101                Poll::Pending => return Poll::Pending,
102                Poll::Ready(None) => this.ended = true,
103                Poll::Ready(Some(chunk)) => {
104                    let mut records = Vec::new();
105                    let result = this.stepper.apply(chunk, &mut records);
106                    this.ready.extend(records.into_iter().map(Ok));
107                    if let Err(fault) = result {
108                        this.ended = !fault.code.is_recoverable();
109                        this.ready.push_back(Err(fault));
110                    }
111                }
112            }
113        }
114    }
115
116    fn size_hint(&self) -> (usize, Option<usize>) {
117        (self.ready.len(), if self.ended { Some(self.ready.len()) } else { None })
118    }
119}