Skip to main content

isothrum_client/client/
events.rs

1//! A subscription's events, and one operation's read off it to its end.
2
3use super::{
4    Accepted, ClientError, Context, ErrorCode, ErrorReport, Event, EventCursor, EventKind, OperationId, OperationPhase, Pin, Poll, Result, is_outcome, mpsc,
5    phase_of,
6};
7
8/// A subscription: the events of the stream, each with its cursor. It ends when the service
9/// closes the connection (an error item says so); dropping it unsubscribes.
10pub struct Subscription {
11    pub(super) rx: mpsc::Receiver<Result<(EventCursor, Event)>>,
12    pub(super) task: tokio::task::JoinHandle<()>,
13}
14
15impl Subscription {
16    /// The next event; `None` once the subscription ended.
17    pub async fn next(&mut self) -> Option<Result<(EventCursor, Event)>> {
18        self.rx.recv().await
19    }
20}
21
22impl futures_core::Stream for Subscription {
23    type Item = Result<(EventCursor, Event)>;
24
25    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
26        self.rx.poll_recv(cx)
27    }
28}
29
30impl Drop for Subscription {
31    fn drop(&mut self) {
32        self.task.abort();
33    }
34}
35
36impl std::fmt::Debug for Subscription {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("Subscription").finish_non_exhaustive()
39    }
40}
41
42/// An operation queued and followed ([`Client::follow`](crate::Client::follow)).
43#[derive(Debug)]
44pub struct Followed {
45    /// The service's acceptance.
46    pub accepted: Accepted,
47    pub(super) events: OperationEvents,
48}
49
50impl Followed {
51    /// The operation's next event; `None` after its `ended`.
52    pub async fn next(&mut self) -> Option<Result<Event>> {
53        self.events.next().await
54    }
55
56    /// Reads the operation to its end, and returns its `result`, else its `error` as
57    /// [`ClientError::Operation`].
58    ///
59    /// # Errors
60    ///
61    /// It failed, was cancelled, or the connection ended.
62    pub async fn outcome(&mut self) -> Result<Event> {
63        self.events.outcome().await
64    }
65}
66
67/// One operation's events, read off a subscription.
68#[derive(Debug)]
69pub(super) struct OperationEvents {
70    operation: OperationId,
71    events: Subscription,
72    ended: bool,
73}
74
75impl OperationEvents {
76    pub(super) fn new(operation: OperationId, events: Subscription) -> OperationEvents {
77        OperationEvents {
78            operation,
79            events,
80            ended: false,
81        }
82    }
83
84    pub(super) async fn next(&mut self) -> Option<Result<Event>> {
85        if self.ended {
86            return None;
87        }
88        loop {
89            let event = match self.events.next().await? {
90                Ok((_, event)) => event,
91                Err(e) => {
92                    self.ended = true;
93                    return Some(Err(e));
94                }
95            };
96            if event.operation != Some(self.operation) {
97                continue;
98            }
99            if phase_of(&event) == Some(OperationPhase::Ended) {
100                self.ended = true;
101            }
102            return Some(Ok(event));
103        }
104    }
105
106    pub(super) async fn outcome(&mut self) -> Result<Event> {
107        let mut outcome = None;
108        while let Some(event) = self.next().await {
109            let event = event?;
110            if is_outcome(&event) {
111                outcome = Some(event);
112            }
113        }
114        outcome_of(outcome)
115    }
116}
117
118/// An operation's outcome from its last `result` or `error` event (none: it was cancelled before
119/// it began).
120pub(super) fn outcome_of(event: Option<Event>) -> Result<Event> {
121    let Some(event) = event else {
122        return Err(ClientError::Operation(Box::new(ErrorReport::new(
123            ErrorCode::Cancelled,
124            "the operation was cancelled before it began",
125        ))));
126    };
127    match &event.kind {
128        EventKind::Error(report) => Err(ClientError::Operation(Box::new(report.clone()))),
129        _ => Ok(event),
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use isothrum_runner::store::EventCursor;
136    use isothrum_runner::{ErrorCode, ErrorReport, EventKind, Op, ResultData, RunState, Stream};
137
138    use super::*;
139    use crate::v1::Event;
140
141    /// Operation `id`'s event of `kind`.
142    fn of(id: i64, kind: EventKind) -> Event {
143        let mut event = Event::new(1, Some("stack".to_owned()), Some(Op::Up), kind);
144        event.operation = Some(OperationId(id));
145        event
146    }
147
148    fn ended(id: i64) -> Event {
149        of(
150            id,
151            EventKind::Operation {
152                phase: OperationPhase::Ended,
153                outcome: None,
154                position: None,
155            },
156        )
157    }
158
159    /// Operation 7's events read off a subscription that gives `items`, then ends.
160    fn following(items: Vec<Result<Event>>) -> OperationEvents {
161        let (tx, rx) = tokio::sync::mpsc::channel(16);
162        for item in items {
163            tx.try_send(item.map(|e| (EventCursor(1), e))).expect("room");
164        }
165        drop(tx);
166        let task = tokio::spawn(async {});
167        OperationEvents::new(OperationId(7), Subscription { rx, task })
168    }
169
170    #[tokio::test]
171    async fn an_operations_events_are_its_own_up_to_its_end_and_none_after() {
172        let result = of(
173            7,
174            EventKind::Result {
175                ok: true,
176                data: ResultData::Moved { state: RunState::Ready },
177            },
178        );
179        let mut events = following(vec![
180            Ok(of(
181                8,
182                EventKind::Log {
183                    step: "up".into(),
184                    stream: Stream::Stdout,
185                    line: "another's".into(),
186                },
187            )),
188            Ok(result.clone()),
189            Ok(ended(7)),
190            Ok(of(
191                7,
192                EventKind::Log {
193                    step: "up".into(),
194                    stream: Stream::Stdout,
195                    line: "after its end".into(),
196                },
197            )),
198        ]);
199        let first = events.next().await.expect("an event").expect("its own");
200        assert_eq!(first.kind, result.kind, "another operation's event is passed over");
201        let last = events.next().await.expect("an event").expect("its own");
202        assert_eq!(phase_of(&last), Some(OperationPhase::Ended));
203        assert!(events.next().await.is_none(), "nothing after its end, though the stream goes on");
204    }
205
206    #[tokio::test]
207    async fn an_error_event_is_the_operations_failure_with_its_code_and_step() {
208        let failed = of(7, EventKind::Error(ErrorReport::new(ErrorCode::ToolFailed, "compose said no").with_step("up")));
209        let e = following(vec![Ok(failed), Ok(ended(7))]).outcome().await.expect_err("failed");
210        assert!(
211            matches!(&e, ClientError::Operation(r) if r.code == ErrorCode::ToolFailed && r.step.as_deref() == Some("up")),
212            "{e:?}"
213        );
214    }
215
216    #[tokio::test]
217    async fn an_operation_that_ended_with_no_outcome_was_cancelled_and_a_broken_stream_is_its_error() {
218        let cancelled = following(vec![Ok(ended(7))]).outcome().await.expect_err("no outcome");
219        assert_eq!(cancelled.code(), ErrorCode::Cancelled);
220        let mut broken = following(vec![Err(ClientError::closed())]);
221        let e = broken.next().await.expect("an item").expect_err("the stream's error");
222        assert_eq!(e.code(), ErrorCode::Io);
223        assert!(broken.next().await.is_none(), "it ended with its error");
224    }
225
226    #[tokio::test]
227    async fn a_subscription_is_a_stream_of_its_events() {
228        use std::pin::Pin;
229        let (tx, rx) = tokio::sync::mpsc::channel(1);
230        tx.try_send(Ok((EventCursor(4), ended(7)))).expect("room");
231        drop(tx);
232        let mut sub = Subscription {
233            rx,
234            task: tokio::spawn(async {}),
235        };
236        let first = std::future::poll_fn(|cx| futures_core::Stream::poll_next(Pin::new(&mut sub), cx)).await;
237        assert!(matches!(first, Some(Ok((EventCursor(4), _)))), "{first:?}");
238        assert!(sub.next().await.is_none());
239    }
240}