Skip to main content

plexus_client/
decode.rs

1//! Turning a wire-item stream into a typed event stream.
2//!
3//! This is the one piece of runtime the generated client calls: everything
4//! above it is the activation's own types, everything below it is a
5//! [`Transport`](crate::Transport).
6
7use crate::envelope::StreamItem;
8use crate::error::ClientError;
9use crate::event::ClientEvent;
10use crate::transport::ItemStream;
11use futures_core::Stream;
12use futures_util::{stream, StreamExt};
13use serde::de::DeserializeOwned;
14use std::pin::Pin;
15
16/// A boxed stream of typed events. Mirrors [`ItemStream`]'s `Send` bound:
17/// required off wasm32, dropped on it.
18#[cfg(not(target_arch = "wasm32"))]
19pub type EventStream<'a, E> =
20    Pin<Box<dyn Stream<Item = Result<ClientEvent<E>, ClientError>> + Send + 'a>>;
21
22/// A boxed stream of typed events. See the non-wasm32 variant.
23#[cfg(target_arch = "wasm32")]
24pub type EventStream<'a, E> = Pin<Box<dyn Stream<Item = Result<ClientEvent<E>, ClientError>> + 'a>>;
25
26/// Decode a transport's wire items into a method's typed events.
27///
28/// The mapping, exhaustively:
29///
30/// | Wire item | Yielded | Stream continues? |
31/// |---|---|---|
32/// | `data` (deserializes) | `Ok(ClientEvent::Data(e))` | yes |
33/// | `data` (does not) | `Err(ClientError::Decode)` | **no** |
34/// | `progress` | `Ok(ClientEvent::Progress)` | yes |
35/// | `error` | `Err(ClientError::Remote)` | **no** |
36/// | `request` | *skipped* | yes |
37/// | `done` | *nothing* | **no** |
38/// | transport failure | `Err(ClientError::Transport)` | **no** |
39///
40/// Both terminal errors end the stream because both mean the server will
41/// send nothing further that is meaningful: an in-band `error` is the hub's
42/// last word on the call (`stream_sse_response` and the buffered REST path
43/// both stop there), and a decode failure means client and server disagree
44/// about the event type, so every subsequent item would fail the same way.
45///
46/// A `done` item is *not* surfaced as an event — normal completion is the
47/// stream ending. `Ok(())`-style sentinels in a `Stream` only invite
48/// consumers to forget to handle them.
49pub fn decode<'a, E>(items: ItemStream<'a>) -> EventStream<'a, E>
50where
51    E: DeserializeOwned + 'a,
52{
53    Box::pin(stream::unfold(Some(items), |state| async move {
54        let mut items = state?;
55        loop {
56            let next = items.next().await?;
57            match next {
58                Err(e) => return Some((Err(ClientError::Transport(e)), None)),
59                Ok(StreamItem::Done { .. }) => return None,
60                Ok(StreamItem::Data {
61                    content,
62                    content_type,
63                    ..
64                }) => {
65                    return Some(match serde_json::from_value::<E>(content) {
66                        Ok(event) => (Ok(ClientEvent::Data(event)), Some(items)),
67                        Err(e) => (
68                            Err(ClientError::Decode {
69                                content_type,
70                                message: e.to_string(),
71                            }),
72                            None,
73                        ),
74                    })
75                }
76                Ok(StreamItem::Progress {
77                    message,
78                    percentage,
79                    ..
80                }) => {
81                    return Some((
82                        Ok(ClientEvent::Progress {
83                            message,
84                            percentage,
85                        }),
86                        Some(items),
87                    ))
88                }
89                Ok(StreamItem::Error {
90                    message,
91                    code,
92                    recoverable,
93                    ..
94                }) => {
95                    return Some((
96                        Err(ClientError::Remote {
97                            message,
98                            code,
99                            recoverable,
100                        }),
101                        None,
102                    ))
103                }
104                // Bidirectional server→client requests need an answer
105                // channel the typed client does not have. Skip rather than
106                // fail: an activation may interleave them with real data.
107                Ok(StreamItem::Request { .. }) => continue,
108            }
109        }
110    }))
111}
112
113/// A typed stream that yields exactly one error and then ends.
114///
115/// What a generated client method returns when it cannot even build the
116/// request — a parameter that would not serialize. Keeping the signature a
117/// stream (rather than `Result<EventStream, _>`) means the call site handles
118/// one error channel, not two.
119pub fn error_stream<'a, E>(error: ClientError) -> EventStream<'a, E>
120where
121    E: 'a,
122{
123    Box::pin(stream::once(async move { Err(error) }))
124}
125
126/// Drive a typed stream to completion, collecting every `data` event.
127///
128/// The shape a unary method wants: menger's finite calls (`list`, `get`,
129/// `blockers`, …) emit N data items then `done`, and the caller wants the
130/// `Vec`. Progress events are discarded; the first error wins.
131pub async fn collect_data<E, S>(mut stream: S) -> Result<Vec<E>, ClientError>
132where
133    S: Stream<Item = Result<ClientEvent<E>, ClientError>> + Unpin,
134{
135    let mut out = Vec::new();
136    while let Some(item) = stream.next().await {
137        match item? {
138            ClientEvent::Data(e) => out.push(e),
139            ClientEvent::Progress { .. } => {}
140        }
141    }
142    Ok(out)
143}