Skip to main content

plexus_client/
memory.rs

1//! `MemoryTransport` — a scripted [`Transport`] with no server behind it.
2//!
3//! This is the transport a *client* test uses. It is wasm-safe (it is the
4//! only transport that can be, since it has no I/O), so it is what proves a
5//! generated client compiles and runs for `wasm32-unknown-unknown` without
6//! also standing up a browser.
7//!
8//! It is not the in-process transport: that one drives a real `Activation`
9//! and therefore lives on the `plexus-core` side. This one replays a script.
10
11use crate::envelope::StreamItem;
12use crate::error::TransportError;
13use crate::transport::{ItemStream, MethodRef, Transport};
14use futures_util::stream;
15use serde::Serialize;
16use serde_json::Value;
17use std::collections::HashMap;
18use std::sync::Mutex;
19
20type Script = Vec<Result<StreamItem, TransportError>>;
21
22/// A [`Transport`] that answers from a script and records what it was asked.
23///
24/// ```
25/// use futures::TryStreamExt;
26/// use plexus_client::{decode, MemoryTransport, MethodRef, Transport};
27///
28/// #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
29/// struct Ev { n: u8 }
30///
31/// const COUNT: MethodRef = MethodRef::new("demo", "count");
32///
33/// let t = MemoryTransport::new().script_events(COUNT, &[Ev { n: 1 }, Ev { n: 2 }]);
34/// let events = futures::executor::block_on(async {
35///     decode::<Ev>(t.call(COUNT, serde_json::json!({}))).try_collect::<Vec<_>>().await
36/// })
37/// .unwrap();
38///
39/// assert_eq!(events, vec![Ev { n: 1 }, Ev { n: 2 }]);
40/// assert_eq!(t.params_of(COUNT), Some(serde_json::json!({})));
41/// ```
42#[derive(Debug, Default)]
43pub struct MemoryTransport {
44    scripts: HashMap<String, Script>,
45    /// Every `(method, params)` this transport was called with, in order.
46    calls: Mutex<Vec<(String, Value)>>,
47}
48
49impl MemoryTransport {
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    /// Script the raw wire items a method answers with. Use this to exercise
55    /// the shapes only a real transport produces — `progress`, an in-band
56    /// `error`, a `data` item with the wrong payload.
57    pub fn script(mut self, method: MethodRef, items: Vec<StreamItem>) -> Self {
58        self.scripts
59            .insert(method.qualified(), items.into_iter().map(Ok).collect());
60        self
61    }
62
63    /// Script a transport failure — the connection dying instead of the
64    /// server answering.
65    pub fn script_failure(mut self, method: MethodRef, error: TransportError) -> Self {
66        self.scripts.insert(method.qualified(), vec![Err(error)]);
67        self
68    }
69
70    /// Script the happy path: each event becomes a `data` item stamped with
71    /// the method's `content_type`, followed by `done`.
72    ///
73    /// Serialization uses the event type's own `Serialize`, so a script
74    /// written against the server's event enum cannot drift from what the
75    /// server would actually put on the wire.
76    pub fn script_events<E: Serialize>(self, method: MethodRef, events: &[E]) -> Self {
77        let content_type = method.qualified();
78        let mut items: Vec<StreamItem> = events
79            .iter()
80            .map(|e| StreamItem::Data {
81                metadata: None,
82                content_type: Some(content_type.clone()),
83                content: serde_json::to_value(e).expect("event serializes"),
84            })
85            .collect();
86        items.push(StreamItem::done());
87        self.script(method, items)
88    }
89
90    /// Every call this transport received, in order, as
91    /// `("namespace.method", params)`.
92    pub fn calls(&self) -> Vec<(String, Value)> {
93        self.calls.lock().expect("calls lock").clone()
94    }
95
96    /// The params of the single call to `method`, or `None` if it was not
97    /// called exactly once.
98    pub fn params_of(&self, method: impl std::borrow::Borrow<MethodRef>) -> Option<Value> {
99        let q = method.borrow().qualified();
100        let calls = self.calls.lock().expect("calls lock");
101        let mut hits = calls.iter().filter(|(m, _)| *m == q);
102        let first = hits.next()?;
103        match hits.next() {
104            None => Some(first.1.clone()),
105            Some(_) => None,
106        }
107    }
108}
109
110impl Transport for MemoryTransport {
111    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
112        let qualified = method.qualified();
113        self.calls
114            .lock()
115            .expect("calls lock")
116            .push((qualified.clone(), params));
117
118        let script = self.scripts.get(&qualified).cloned().unwrap_or_else(|| {
119            vec![Err(TransportError::protocol(format!(
120                "MemoryTransport has no script for `{qualified}`"
121            )))]
122        });
123        Box::pin(stream::iter(script))
124    }
125}