Skip to main content

plexus_client/
contract.rs

1//! MACRO-13 · what a trait the activation macro emits leans on.
2//!
3//! `#[plexus_macros::activation(trait)]` on `impl FooActivation` emits
4//! `trait Foo`: every wire method as `fn(&self, ..) -> BoxStream<'static, E>`,
5//! implemented by the activation and by `FooClient<T>`. A client call is a
6//! stream of `Result<ClientEvent<E>, ClientError>`; a trait method is a
7//! stream of `E`. This module is the bridge:
8//!
9//! - [`FromClientError`] — how a client failure becomes the event type's own
10//!   in-band error (one line, usually `Error { message }`), so a caller of
11//!   `dyn Foo` sees one shape whether it is talking to a local
12//!   implementation or a remote one;
13//! - [`owned_call`] — a `'static` call from an owned transport, since a trait
14//!   method's stream outlives the `&self` it was called on;
15//! - [`into_events`] / [`error_events`] — the mapping itself: a data event is
16//!   yielded, a progress report is dropped, an error is yielded as
17//!   `E::from_client_error(err)` and ends the stream.
18
19use crate::decode::EventStream;
20use crate::envelope::StreamItem;
21use crate::error::{ClientError, TransportError};
22use crate::event::ClientEvent;
23use crate::transport::{ItemStream, MethodRef, Transport};
24use futures_core::Stream;
25use futures_util::{stream, StreamExt};
26use serde_json::Value;
27use std::future::Future;
28use std::pin::Pin;
29use std::sync::{Arc, Mutex};
30use std::task::{Context, Poll};
31
32/// A boxed stream of `T` — the return type of every method of a trait the
33/// activation macro emits. `Send` off wasm32, as [`ItemStream`] is; on
34/// wasm32 the browser's futures are `!Send`, so the bound is dropped.
35#[cfg(not(target_arch = "wasm32"))]
36pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
37
38/// A boxed stream of `T`. See the non-wasm32 variant.
39#[cfg(target_arch = "wasm32")]
40pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + 'a>>;
41
42/// An event type that can carry a client failure in band.
43///
44/// The client's implementation of an emitted trait yields each data event
45/// as is and, on an `Err(ClientError)`, yields
46/// `E::from_client_error(err)` and ends. Implement it on the activation's
47/// event enum, usually as its in-band error variant:
48///
49/// ```
50/// # #[derive(Debug)] enum EchoEvent { Said { text: String }, Error { message: String } }
51/// impl plexus_client::FromClientError for EchoEvent {
52///     fn from_client_error(error: plexus_client::ClientError) -> Self {
53///         EchoEvent::Error { message: error.to_string() }
54///     }
55/// }
56/// ```
57#[diagnostic::on_unimplemented(
58    message = "`{Self}` does not implement `plexus_client::FromClientError`",
59    label = "the event type of a trait emitted by `#[plexus_macros::activation]` must implement `plexus_client::FromClientError`",
60    note = "the client's implementation of the trait yields a client failure as `{Self}::from_client_error(err)`; implement `plexus_client::FromClientError` for `{Self}` (usually its in-band `Error {{ message }}` variant)"
61)]
62pub trait FromClientError {
63    /// The event that stands for `error`. It is the last item of its stream.
64    fn from_client_error(error: ClientError) -> Self;
65}
66
67/// A stream of strings carries a client failure as its message — so an
68/// activation whose events are plain `String`s (a type no crate but this one
69/// may implement the trait for) still has its trait implemented by its client.
70impl FromClientError for String {
71    fn from_client_error(error: ClientError) -> Self {
72        error.to_string()
73    }
74}
75
76/// A typed client stream as a trait method's stream: data events yielded,
77/// progress dropped, the first error yielded as `E::from_client_error(err)`
78/// and the stream ended there.
79pub fn into_events<'a, E>(events: EventStream<'a, E>) -> BoxStream<'a, E>
80where
81    E: FromClientError + 'a,
82{
83    Box::pin(stream::unfold(Some(events), |state| async move {
84        let mut events = state?;
85        loop {
86            match events.next().await? {
87                Ok(ClientEvent::Data(e)) => return Some((e, Some(events))),
88                Ok(ClientEvent::Progress { .. }) => continue,
89                Err(err) => return Some((E::from_client_error(err), None)),
90            }
91        }
92    }))
93}
94
95/// A trait method's stream that yields `E::from_client_error(error)` and
96/// ends — what an emitted client method returns when a parameter would not
97/// serialize.
98pub fn error_events<'a, E>(error: ClientError) -> BoxStream<'a, E>
99where
100    E: FromClientError + 'a,
101{
102    Box::pin(stream::once(async move { E::from_client_error(error) }))
103}
104
105type Slot = Arc<Mutex<Option<Result<StreamItem, TransportError>>>>;
106
107#[cfg(not(target_arch = "wasm32"))]
108type Driver = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
109#[cfg(target_arch = "wasm32")]
110type Driver = Pin<Box<dyn Future<Output = ()> + 'static>>;
111
112/// `Transport::call` on a transport the stream owns, so the stream is
113/// `'static`: a trait method returns a stream that outlives the `&self` it
114/// was called on, and `Transport::call` borrows its transport.
115///
116/// The transport and the call's stream (which borrows it) live together in
117/// one future, which hands each item out through a slot and pauses until it
118/// is taken — a generator without `unsafe`.
119#[cfg(not(target_arch = "wasm32"))]
120pub fn owned_call<T>(transport: T, method: MethodRef, params: Value) -> ItemStream<'static>
121where
122    T: Transport + Send + Sync + 'static,
123{
124    let slot: Slot = Arc::new(Mutex::new(None));
125    let tx = slot.clone();
126    let driver: Driver = Box::pin(async move {
127        let transport = transport;
128        let mut items = transport.call(method, params);
129        while let Some(item) = items.next().await {
130            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
131            HandOff(false).await;
132        }
133    });
134    Box::pin(Owned { driver: Some(driver), slot })
135}
136
137/// `Transport::call` on an owned transport. See the non-wasm32 variant.
138#[cfg(target_arch = "wasm32")]
139pub fn owned_call<T>(transport: T, method: MethodRef, params: Value) -> ItemStream<'static>
140where
141    T: Transport + 'static,
142{
143    let slot: Slot = Arc::new(Mutex::new(None));
144    let tx = slot.clone();
145    let driver: Driver = Box::pin(async move {
146        let transport = transport;
147        let mut items = transport.call(method, params);
148        while let Some(item) = items.next().await {
149            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
150            HandOff(false).await;
151        }
152    });
153    Box::pin(Owned { driver: Some(driver), slot })
154}
155
156/// Pending once, so the stream can hand out the item just put in the slot;
157/// ready the next time it is polled. It does not wake: the stream returns
158/// the item, and the caller polls again when it wants the next one.
159struct HandOff(bool);
160
161impl Future for HandOff {
162    type Output = ();
163    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
164        if self.0 {
165            Poll::Ready(())
166        } else {
167            self.0 = true;
168            Poll::Pending
169        }
170    }
171}
172
173struct Owned {
174    driver: Option<Driver>,
175    slot: Slot,
176}
177
178impl Owned {
179    fn take_item(&self) -> Option<Result<StreamItem, TransportError>> {
180        self.slot.lock().unwrap_or_else(|p| p.into_inner()).take()
181    }
182}
183
184impl Stream for Owned {
185    type Item = Result<StreamItem, TransportError>;
186
187    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
188        let Some(driver) = self.driver.as_mut() else {
189            return Poll::Ready(None);
190        };
191        match driver.as_mut().poll(cx) {
192            Poll::Ready(()) => {
193                self.driver = None;
194                Poll::Ready(self.take_item())
195            }
196            Poll::Pending => match self.take_item() {
197                Some(item) => Poll::Ready(Some(item)),
198                None => Poll::Pending,
199            },
200        }
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use crate::decode::decode;
208    use crate::memory::MemoryTransport;
209
210    #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
211    enum Ev {
212        N(u8),
213        Error(String),
214    }
215
216    impl FromClientError for Ev {
217        fn from_client_error(error: ClientError) -> Self {
218            Ev::Error(error.to_string())
219        }
220    }
221
222    const COUNT: MethodRef = MethodRef::new("demo", "count");
223
224    #[test]
225    fn an_owned_call_outlives_its_caller_and_ends_on_an_error() {
226        let t = MemoryTransport::new().script(
227            COUNT,
228            vec![
229                StreamItem::Data { metadata: None, content_type: None, content: serde_json::json!({"N": 1}) },
230                StreamItem::Progress { metadata: None, message: "half".into(), percentage: Some(50.0) },
231                StreamItem::Data { metadata: None, content_type: None, content: serde_json::json!({"N": 2}) },
232                StreamItem::Error { metadata: None, message: "no".into(), code: None, recoverable: false },
233                StreamItem::Data { metadata: None, content_type: None, content: serde_json::json!({"N": 3}) },
234            ],
235        );
236        let s = into_events::<Ev>(decode(owned_call(Arc::new(t), COUNT, serde_json::json!({}))));
237        let got: Vec<Ev> = futures::executor::block_on(s.collect());
238        assert_eq!(got, vec![Ev::N(1), Ev::N(2), Ev::Error("remote error: no".into())]);
239    }
240}