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<E, ClientError>` (RETURNS-9's `MethodStream`, progress
7//! already dropped); a trait method is a stream of `E`. This module is the
8//! bridge:
9//!
10//! - [`FromClientError`] — how a client failure becomes the event type's own
11//!   in-band error (one line, usually `Error { message }`), so a caller of
12//!   `dyn Foo` sees one shape whether it is talking to a local
13//!   implementation or a remote one;
14//! - [`owned_call`] — a `'static` call from an owned transport, since a trait
15//!   method's stream outlives the `&self` it was called on;
16//! - [`into_events`] / [`error_events`] — the mapping itself: an item is
17//!   yielded, an error is yielded as `E::from_client_error(err)` and ends the
18//!   stream.
19//!
20//! RETURNS-36: the trait is always emitted, each method under its own return
21//! type: a one-item method's is a [`BoxFuture`] of its item, a stream form's a
22//! [`BoxStream`] of its items. [`trait_one`], [`trait_many`],
23//! [`trait_progress`] and [`trait_result_progress`] are the client half's.
24
25use crate::envelope::{RawItem, StreamItem};
26use crate::error::{ClientError, TransportError};
27use crate::transport::{ItemStream, MethodRef, RawItemStream, Transport};
28use futures_core::Stream;
29use futures_util::{stream, StreamExt};
30use serde_json::Value;
31use std::future::Future;
32use std::pin::Pin;
33use std::sync::{Arc, Mutex};
34use std::task::{Context, Poll};
35
36/// A boxed stream of `T` — the return type of every method of a trait the
37/// activation macro emits. `Send` off wasm32, as [`ItemStream`] is; on
38/// wasm32 the browser's futures are `!Send`, so the bound is dropped.
39#[cfg(not(target_arch = "wasm32"))]
40pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
41
42/// A boxed stream of `T`. See the non-wasm32 variant.
43#[cfg(target_arch = "wasm32")]
44pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + 'a>>;
45
46/// A boxed future of `T` — what a one-item method of an emitted trait
47/// returns (RETURNS-36). `Send` off wasm32, as [`BoxStream`] is.
48#[cfg(not(target_arch = "wasm32"))]
49pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
50
51/// A boxed future of `T`. See the non-wasm32 variant.
52#[cfg(target_arch = "wasm32")]
53pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
54
55/// `Send` off wasm32, nothing on it: the bound a trait's client half puts
56/// on what it moves into a boxed future or stream.
57#[cfg(not(target_arch = "wasm32"))]
58pub trait MaybeSend: Send {}
59#[cfg(not(target_arch = "wasm32"))]
60impl<T: Send> MaybeSend for T {}
61/// See the non-wasm32 variant.
62#[cfg(target_arch = "wasm32")]
63pub trait MaybeSend {}
64#[cfg(target_arch = "wasm32")]
65impl<T> MaybeSend for T {}
66
67/// An event type that can carry a client failure in band.
68///
69/// The client's implementation of an emitted trait yields each data event
70/// as is and, on an `Err(ClientError)`, yields
71/// `E::from_client_error(err)` and ends. Implement it on the activation's
72/// event enum, usually as its in-band error variant:
73///
74/// ```
75/// # #[derive(Debug)] enum EchoEvent { Said { text: String }, Error { message: String } }
76/// impl plexus_client::FromClientError for EchoEvent {
77///     fn from_client_error(error: plexus_client::ClientError) -> Self {
78///         EchoEvent::Error { message: error.to_string() }
79///     }
80/// }
81/// ```
82#[diagnostic::on_unimplemented(
83    message = "`{Self}` does not implement `plexus_client::FromClientError`",
84    label = "the event type of a trait emitted by `#[plexus_macros::activation]` must implement `plexus_client::FromClientError`",
85    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)"
86)]
87pub trait FromClientError {
88    /// The event that stands for `error`. It is the last item of its stream.
89    fn from_client_error(error: ClientError) -> Self;
90}
91
92/// A stream of strings carries a client failure as its message — so an
93/// activation whose events are plain `String`s (a type no crate but this one
94/// may implement the trait for) still has its trait implemented by its client.
95/// A Result item carries a client failure as its error (RETURNS-36): what
96/// the trait's client half yields for a fallible method.
97impl<T, E: FromClientError> FromClientError for Result<T, E> {
98    fn from_client_error(error: ClientError) -> Self {
99        Err(E::from_client_error(error))
100    }
101}
102
103/// A progress item carries a client failure as its item (RETURNS-36).
104impl<T: FromClientError, P> FromClientError for crate::progress::Progress<T, P> {
105    fn from_client_error(error: ClientError) -> Self {
106        crate::progress::Progress::Item(T::from_client_error(error))
107    }
108}
109
110impl FromClientError for String {
111    fn from_client_error(error: ClientError) -> Self {
112        error.to_string()
113    }
114}
115
116/// A typed client stream as a trait method's stream: data events yielded,
117/// progress dropped, the first error yielded as `E::from_client_error(err)`
118/// and the stream ended there.
119#[cfg(not(target_arch = "wasm32"))]
120pub fn into_events<'a, E, S>(events: S) -> BoxStream<'a, E>
121where
122    E: FromClientError + Send + 'a,
123    S: Stream<Item = Result<E, ClientError>> + Unpin + Send + 'a,
124{
125    Box::pin(stream::unfold(Some(events), |state| async move {
126        let mut events = state?;
127        match events.next().await? {
128            Ok(e) => Some((e, Some(events))),
129            Err(err) => Some((E::from_client_error(err), None)),
130        }
131    }))
132}
133
134/// [`into_events`] on wasm32, where a stream need not be `Send`.
135#[cfg(target_arch = "wasm32")]
136pub fn into_events<'a, E, S>(events: S) -> BoxStream<'a, E>
137where
138    E: FromClientError + 'a,
139    S: Stream<Item = Result<E, ClientError>> + Unpin + 'a,
140{
141    Box::pin(stream::unfold(Some(events), |state| async move {
142        let mut events = state?;
143        match events.next().await? {
144            Ok(e) => Some((e, Some(events))),
145            Err(err) => Some((E::from_client_error(err), None)),
146        }
147    }))
148}
149
150/// A trait method's stream that yields `E::from_client_error(error)` and
151/// ends — what an emitted client method returns when a parameter would not
152/// serialize.
153pub fn error_events<'a, E>(error: ClientError) -> BoxStream<'a, E>
154where
155    E: FromClientError + 'a,
156{
157    Box::pin(stream::once(async move { E::from_client_error(error) }))
158}
159
160// ---------------------------------------------------------------------------
161// RETURNS-36: the trait's client half, one helper per signature form. Each
162// takes its call already made (`owned_call`, or a params error) and yields
163// the method's own return type, a client failure folded in by
164// `FromClientError`.
165// ---------------------------------------------------------------------------
166
167/// `-> T` / `-> Result<T, E>`: one item.
168pub fn trait_one<T, I>(
169    transport: T,
170    method: MethodRef,
171    params: Result<Value, ClientError>,
172    item: crate::method_stream::Decoder<I>,
173) -> BoxFuture<'static, I>
174where
175    T: Transport + MaybeSend + Sync + 'static,
176    I: FromClientError + MaybeSend + 'static,
177{
178    Box::pin(async move {
179        match crate::method_stream::call_one(&transport, method, params, item).await {
180            Ok(i) => i,
181            Err(e) => I::from_client_error(e),
182        }
183    })
184}
185
186/// BIDIR-6: [`trait_one`], for a method with an input half.
187pub fn trait_one_with_input<T, I>(
188    transport: T,
189    method: MethodRef,
190    params: Result<Value, ClientError>,
191    input: crate::transport::InputItems<'static>,
192    item: crate::method_stream::Decoder<I>,
193) -> BoxFuture<'static, I>
194where
195    T: Transport + MaybeSend + Sync + 'static,
196    I: FromClientError + MaybeSend + 'static,
197{
198    Box::pin(async move {
199        match crate::method_stream::call_one_with_input(&transport, method, params, input, item).await {
200            Ok(i) => i,
201            Err(e) => I::from_client_error(e),
202        }
203    })
204}
205
206/// `-> impl Stream<Item = T>` / `Item = Result<T, E>`: many items.
207pub fn trait_many<I>(
208    items: Result<RawItemStream<'static>, ClientError>,
209    item: crate::method_stream::Decoder<I>,
210) -> BoxStream<'static, I>
211where
212    I: FromClientError + MaybeSend + 'static,
213{
214    match items {
215        Ok(items) => fold(crate::method_stream::MethodStream::<'static, I>::new(items, item, std::convert::identity)),
216        Err(e) => Box::pin(stream::once(async move { I::from_client_error(e) })),
217    }
218}
219
220/// `-> impl Stream<Item = Progress<T, P>>`: items and progress updates.
221pub fn trait_progress<T, P>(
222    items: Result<RawItemStream<'static>, ClientError>,
223    item: crate::method_stream::Decoder<T>,
224) -> BoxStream<'static, crate::progress::Progress<T, P>>
225where
226    T: FromClientError + MaybeSend + 'static,
227    P: serde::de::DeserializeOwned + MaybeSend + 'static,
228{
229    use crate::frame::Frame;
230    use crate::progress::Progress;
231    match items {
232        Ok(items) => fold(
233            crate::method_stream::MethodStream::<'static, T, P, T>::new(items, item, std::convert::identity)
234                .with_progress()
235                .map(|r| {
236                    r.map(|f| match f {
237                        Frame::Item(t) => Progress::Item(t),
238                        Frame::Progress(p) => Progress::Update(p),
239                    })
240                }),
241        ),
242        Err(e) => Box::pin(stream::once(async move { Progress::Item(T::from_client_error(e)) })),
243    }
244}
245
246/// `-> impl Stream<Item = Result<Progress<T, P>, E>>`.
247pub fn trait_result_progress<T, P, E>(
248    items: Result<RawItemStream<'static>, ClientError>,
249    item: crate::method_stream::Decoder<Result<T, E>>,
250) -> BoxStream<'static, Result<crate::progress::Progress<T, P>, E>>
251where
252    T: MaybeSend + 'static,
253    E: FromClientError + MaybeSend + 'static,
254    P: serde::de::DeserializeOwned + MaybeSend + 'static,
255{
256    use crate::frame::Frame;
257    use crate::progress::Progress;
258    match items {
259        Ok(items) => fold(
260            crate::method_stream::MethodStream::<'static, Result<T, E>, P, Result<T, E>>::new(
261                items,
262                item,
263                std::convert::identity,
264            )
265            .with_progress()
266            .map(|r| {
267                r.map(|f| match f {
268                    Frame::Item(Ok(t)) => Ok(Progress::Item(t)),
269                    Frame::Item(Err(e)) => Err(e),
270                    Frame::Progress(p) => Ok(Progress::Update(p)),
271                })
272            }),
273        ),
274        Err(e) => Box::pin(stream::once(async move { Err(E::from_client_error(e)) })),
275    }
276}
277
278/// A client stream as a trait method's: each item as is, the first failure
279/// folded into the item type and the end.
280fn fold<I, S>(events: S) -> BoxStream<'static, I>
281where
282    I: FromClientError + MaybeSend + 'static,
283    S: Stream<Item = Result<I, ClientError>> + Unpin + MaybeSend + 'static,
284{
285    Box::pin(stream::unfold(Some(events), |state| async move {
286        let mut events = state?;
287        match events.next().await? {
288            Ok(e) => Some((e, Some(events))),
289            Err(err) => Some((I::from_client_error(err), None)),
290        }
291    }))
292}
293
294type Slot<I> = Arc<Mutex<Option<Result<I, TransportError>>>>;
295
296#[cfg(not(target_arch = "wasm32"))]
297type Driver = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
298#[cfg(target_arch = "wasm32")]
299type Driver = Pin<Box<dyn Future<Output = ()> + 'static>>;
300
301/// `Transport::call` on a transport the stream owns, so the stream is
302/// `'static`: a trait method returns a stream that outlives the `&self` it
303/// was called on, and `Transport::call` borrows its transport.
304///
305/// The transport and the call's stream (which borrows it) live together in
306/// one future, which hands each item out through a slot and pauses until it
307/// is taken — a generator without `unsafe`.
308#[cfg(not(target_arch = "wasm32"))]
309pub fn owned_call<T>(transport: T, method: MethodRef, params: Value) -> ItemStream<'static>
310where
311    T: Transport + Send + Sync + 'static,
312{
313    let slot: Slot<StreamItem> = Arc::new(Mutex::new(None));
314    let tx = slot.clone();
315    let driver: Driver = Box::pin(async move {
316        let transport = transport;
317        let mut items = transport.call(method, params);
318        while let Some(item) = items.next().await {
319            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
320            HandOff(false).await;
321        }
322    });
323    Box::pin(Owned { driver: Some(driver), slot })
324}
325
326/// [`owned_call`] for a typed client: `Transport::call_raw` on a transport
327/// the stream owns (PERF.115-36).
328#[cfg(not(target_arch = "wasm32"))]
329pub fn owned_call_raw<T>(transport: T, method: MethodRef, params: Value) -> RawItemStream<'static>
330where
331    T: Transport + Send + Sync + 'static,
332{
333    let slot: Slot<RawItem> = Arc::new(Mutex::new(None));
334    let tx = slot.clone();
335    let driver: Driver = Box::pin(async move {
336        let transport = transport;
337        let mut items = transport.call_raw(method, params);
338        while let Some(item) = items.next().await {
339            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
340            HandOff(false).await;
341        }
342    });
343    Box::pin(Owned { driver: Some(driver), slot })
344}
345
346/// `Transport::call` on an owned transport. See the non-wasm32 variant.
347#[cfg(target_arch = "wasm32")]
348pub fn owned_call<T>(transport: T, method: MethodRef, params: Value) -> ItemStream<'static>
349where
350    T: Transport + 'static,
351{
352    let slot: Slot<StreamItem> = Arc::new(Mutex::new(None));
353    let tx = slot.clone();
354    let driver: Driver = Box::pin(async move {
355        let transport = transport;
356        let mut items = transport.call(method, params);
357        while let Some(item) = items.next().await {
358            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
359            HandOff(false).await;
360        }
361    });
362    Box::pin(Owned { driver: Some(driver), slot })
363}
364
365/// `owned_call_raw` on an owned transport. See the non-wasm32 variant.
366#[cfg(target_arch = "wasm32")]
367pub fn owned_call_raw<T>(transport: T, method: MethodRef, params: Value) -> RawItemStream<'static>
368where
369    T: Transport + 'static,
370{
371    let slot: Slot<RawItem> = Arc::new(Mutex::new(None));
372    let tx = slot.clone();
373    let driver: Driver = Box::pin(async move {
374        let transport = transport;
375        let mut items = transport.call_raw(method, params);
376        while let Some(item) = items.next().await {
377            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
378            HandOff(false).await;
379        }
380    });
381    Box::pin(Owned { driver: Some(driver), slot })
382}
383
384/// BIDIR-6: [`owned_call_raw`], for a method with an input half.
385#[cfg(not(target_arch = "wasm32"))]
386pub fn owned_call_raw_with_input<T>(transport: T, method: MethodRef, params: Value, input: crate::transport::InputItems<'static>) -> RawItemStream<'static>
387where
388    T: Transport + Send + Sync + 'static,
389{
390    let slot: Slot<RawItem> = Arc::new(Mutex::new(None));
391    let tx = slot.clone();
392    let driver: Driver = Box::pin(async move {
393        let transport = transport;
394        let mut items = transport.call_raw_with_input(method, params, input);
395        while let Some(item) = items.next().await {
396            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
397            HandOff(false).await;
398        }
399    });
400    Box::pin(Owned { driver: Some(driver), slot })
401}
402
403/// BIDIR-6: [`owned_call_raw`], for a method with an input half. See the
404/// non-wasm32 variant.
405#[cfg(target_arch = "wasm32")]
406pub fn owned_call_raw_with_input<T>(transport: T, method: MethodRef, params: Value, input: crate::transport::InputItems<'static>) -> RawItemStream<'static>
407where
408    T: Transport + 'static,
409{
410    let slot: Slot<RawItem> = Arc::new(Mutex::new(None));
411    let tx = slot.clone();
412    let driver: Driver = Box::pin(async move {
413        let transport = transport;
414        let mut items = transport.call_raw_with_input(method, params, input);
415        while let Some(item) = items.next().await {
416            *tx.lock().unwrap_or_else(|p| p.into_inner()) = Some(item);
417            HandOff(false).await;
418        }
419    });
420    Box::pin(Owned { driver: Some(driver), slot })
421}
422
423/// Pending once, so the stream can hand out the item just put in the slot;
424/// ready the next time it is polled. It does not wake: the stream returns
425/// the item, and the caller polls again when it wants the next one.
426struct HandOff(bool);
427
428impl Future for HandOff {
429    type Output = ();
430    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
431        if self.0 {
432            Poll::Ready(())
433        } else {
434            self.0 = true;
435            Poll::Pending
436        }
437    }
438}
439
440struct Owned<I> {
441    driver: Option<Driver>,
442    slot: Slot<I>,
443}
444
445impl<I> Owned<I> {
446    fn take_item(&self) -> Option<Result<I, TransportError>> {
447        self.slot.lock().unwrap_or_else(|p| p.into_inner()).take()
448    }
449}
450
451impl<I> Stream for Owned<I> {
452    type Item = Result<I, TransportError>;
453
454    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
455        let Some(driver) = self.driver.as_mut() else {
456            return Poll::Ready(None);
457        };
458        match driver.as_mut().poll(cx) {
459            Poll::Ready(()) => {
460                self.driver = None;
461                Poll::Ready(self.take_item())
462            }
463            Poll::Pending => match self.take_item() {
464                Some(item) => Poll::Ready(Some(item)),
465                None => Poll::Pending,
466            },
467        }
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use crate::decode::decode;
475    use crate::memory::MemoryTransport;
476
477    #[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
478    enum Ev {
479        N(u8),
480        Error(String),
481    }
482
483    impl FromClientError for Ev {
484        fn from_client_error(error: ClientError) -> Self {
485            Ev::Error(error.to_string())
486        }
487    }
488
489    const COUNT: MethodRef = MethodRef::new("demo", "count");
490
491    #[test]
492    fn an_owned_call_outlives_its_caller_and_ends_on_an_error() {
493        let t = MemoryTransport::new().script(
494            COUNT,
495            vec![
496                StreamItem::Data { metadata: None, content_type: None, content: serde_json::json!({"N": 1}) },
497                StreamItem::Progress { metadata: None, content_type: None, content: serde_json::json!({"message": "half", "percentage": 50.0}) },
498                StreamItem::Data { metadata: None, content_type: None, content: serde_json::json!({"N": 2}) },
499                StreamItem::Error {
500                    metadata: None,
501                    recoverable: false,
502                    message: Some("no".into()),
503                    code: None,
504                    error: crate::RemoteError::Execution { message: "no".into() },
505                    fields: Default::default(),
506                },
507                StreamItem::Data { metadata: None, content_type: None, content: serde_json::json!({"N": 3}) },
508            ],
509        );
510        let s = into_events::<Ev, _>(decode::<Ev>(owned_call(Arc::new(t), COUNT, serde_json::json!({}))));
511        let got: Vec<Ev> = futures::executor::block_on(s.collect());
512        assert_eq!(got, vec![Ev::N(1), Ev::N(2), Ev::Error("remote error: no".into())]);
513    }
514}