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 plexus_client::{collect_data, decode, MemoryTransport, MethodRef, Transport};
26///
27/// #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
28/// struct Ev { n: u8 }
29///
30/// const COUNT: MethodRef = MethodRef::new("demo", "count");
31///
32/// let t = MemoryTransport::new().script_events(COUNT, &[Ev { n: 1 }, Ev { n: 2 }]);
33/// let events = futures::executor::block_on(async {
34///     collect_data(decode::<Ev>(t.call(COUNT, serde_json::json!({})))).await
35/// })
36/// .unwrap();
37///
38/// assert_eq!(events, vec![Ev { n: 1 }, Ev { n: 2 }]);
39/// assert_eq!(t.params_of(COUNT), Some(serde_json::json!({})));
40/// ```
41#[derive(Debug, Default)]
42pub struct MemoryTransport {
43    scripts: HashMap<String, Script>,
44    /// Every `(method, params)` this transport was called with, in order.
45    calls: Mutex<Vec<(String, Value)>>,
46}
47
48impl MemoryTransport {
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Script the raw wire items a method answers with. Use this to exercise
54    /// the shapes only a real transport produces — `progress`, an in-band
55    /// `error`, a `data` item with the wrong payload.
56    pub fn script(mut self, method: MethodRef, items: Vec<StreamItem>) -> Self {
57        self.scripts
58            .insert(method.qualified(), items.into_iter().map(Ok).collect());
59        self
60    }
61
62    /// Script a transport failure — the connection dying instead of the
63    /// server answering.
64    pub fn script_failure(mut self, method: MethodRef, error: TransportError) -> Self {
65        self.scripts.insert(method.qualified(), vec![Err(error)]);
66        self
67    }
68
69    /// Script the happy path: each event becomes a `data` item stamped with
70    /// the method's `content_type`, followed by `done`.
71    ///
72    /// Serialization uses the event type's own `Serialize`, so a script
73    /// written against the server's event enum cannot drift from what the
74    /// server would actually put on the wire.
75    pub fn script_events<E: Serialize>(self, method: MethodRef, events: &[E]) -> Self {
76        let content_type = method.qualified();
77        let mut items: Vec<StreamItem> = events
78            .iter()
79            .map(|e| StreamItem::Data {
80                metadata: None,
81                content_type: Some(content_type.clone()),
82                content: serde_json::to_value(e).expect("event serializes"),
83            })
84            .collect();
85        items.push(StreamItem::done());
86        self.script(method, items)
87    }
88
89    /// Every call this transport received, in order, as
90    /// `("namespace.method", params)`.
91    pub fn calls(&self) -> Vec<(String, Value)> {
92        self.calls.lock().expect("calls lock").clone()
93    }
94
95    /// The params of the single call to `method`, or `None` if it was not
96    /// called exactly once.
97    pub fn params_of(&self, method: MethodRef) -> Option<Value> {
98        let q = method.qualified();
99        let calls = self.calls.lock().expect("calls lock");
100        let mut hits = calls.iter().filter(|(m, _)| *m == q);
101        let first = hits.next()?;
102        match hits.next() {
103            None => Some(first.1.clone()),
104            Some(_) => None,
105        }
106    }
107}
108
109impl Transport for MemoryTransport {
110    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
111        let qualified = method.qualified();
112        self.calls
113            .lock()
114            .expect("calls lock")
115            .push((qualified.clone(), params));
116
117        let script = self.scripts.get(&qualified).cloned().unwrap_or_else(|| {
118            vec![Err(TransportError::protocol(format!(
119                "MemoryTransport has no script for `{qualified}`"
120            )))]
121        });
122        Box::pin(stream::iter(script))
123    }
124}