Skip to main content

plexus_client/
transport.rs

1//! The transport seam: one small trait every wire implementation satisfies,
2//! and the strongly-typed method reference the generated client hands it.
3
4use crate::envelope::{RawItem, StreamItem};
5use crate::error::TransportError;
6use futures_core::Stream;
7use futures_util::StreamExt;
8use serde_json::Value;
9use std::fmt;
10use std::pin::Pin;
11use std::sync::Arc;
12
13/// A boxed stream of wire items.
14///
15/// `Send` is required off wasm32 (so native callers can `tokio::spawn` a
16/// client stream) and **not** required on wasm32, where the browser futures a
17/// transport must build on (`JsFuture`, `ReadableStreamDefaultReader`) are
18/// `!Send` by construction.
19#[cfg(not(target_arch = "wasm32"))]
20pub type ItemStream<'a> =
21    Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + Send + 'a>>;
22
23/// A boxed stream of wire items. See the non-wasm32 variant for the
24/// `Send`-bound rationale.
25#[cfg(target_arch = "wasm32")]
26pub type ItemStream<'a> = Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + 'a>>;
27
28/// A boxed stream of a typed client's items ([`RawItem`], PERF.115-36). The
29/// same `Send` bound as [`ItemStream`].
30#[cfg(not(target_arch = "wasm32"))]
31pub type RawItemStream<'a> =
32    Pin<Box<dyn Stream<Item = Result<RawItem, TransportError>> + Send + 'a>>;
33
34/// A boxed stream of a typed client's items. See the non-wasm32 variant.
35#[cfg(target_arch = "wasm32")]
36pub type RawItemStream<'a> = Pin<Box<dyn Stream<Item = Result<RawItem, TransportError>> + 'a>>;
37
38/// BIDIR-6: what a transport sends for a call's input half: each item, or
39/// why an item would not serialize (which ends the call).
40pub type InputItems<'a> = crate::contract::BoxStream<'a, Result<InputItem, TransportError>>;
41
42/// One item of a call's input half.
43#[derive(Debug, Clone, PartialEq)]
44#[non_exhaustive]
45pub enum InputItem {
46    /// An item as JSON, in a `{ns}.input` frame.
47    Json(Value),
48    /// BIDIR-17: an `Input<Bytes>` item, which a WebSocket sends as one binary
49    /// frame, `[0x01][subscription: u64 BE][seq: u64 BE][payload]`.
50    #[cfg(feature = "binary")]
51    Binary(bytes::Bytes),
52}
53
54/// A stream of items as [`InputItems`]: what a generated client method
55/// hands [`Transport::call_with_input`]. `Bytes` items are
56/// [`InputItem::Binary`] (with a WebSocket backend); anything else is JSON.
57pub fn encode_input<'a, T, S>(input: S) -> InputItems<'a>
58where
59    T: serde::Serialize + 'static,
60    S: Stream<Item = T> + crate::contract::MaybeSend + 'a,
61{
62    use futures_util::StreamExt;
63    Box::pin(input.map(|item| {
64        #[cfg(feature = "binary")]
65        {
66            let mut slot = Some(item);
67            let any: &mut dyn core::any::Any = &mut slot;
68            if let Some(bytes) = any.downcast_mut::<Option<bytes::Bytes>>() {
69                return Ok(InputItem::Binary(bytes.take().expect("taken once")));
70            }
71            let item = slot.take().expect("not taken");
72            json_item(&item)
73        }
74        #[cfg(not(feature = "binary"))]
75        json_item(&item)
76    }))
77}
78
79fn json_item<T: serde::Serialize>(item: &T) -> Result<InputItem, TransportError> {
80    serde_json::to_value(item).map(InputItem::Json).map_err(|e| TransportError::protocol(format!("an input item will not serialize: {e}")))
81}
82
83/// The dotted route a service reaches an activation at: `"tickets"`,
84/// `"tickets.inputs"`, `"tickets.acme"` (a dynamic instance).
85///
86/// RETURNS-46: a path built at run time — a child's, a dynamic instance's —
87/// is the client's own, shared by `Arc` and freed with the last client that
88/// holds it: no process-wide set, nothing leaked, no lock. A path known when
89/// the program is written (a namespace, a `MethodRef` constant) is a
90/// `&'static str` and costs nothing; `""` means "the namespace". So it is
91/// `Cow<'static, str>` with an `Arc` arm: a constant stays `const`, and a
92/// clone of a run-time path is a reference count, not a copy.
93#[derive(Clone)]
94pub struct RoutePath(PathRepr);
95
96#[derive(Clone)]
97enum PathRepr {
98    Static(&'static str),
99    Shared(Arc<str>),
100}
101
102impl RoutePath {
103    /// The empty path: the activation's own namespace.
104    pub const EMPTY: RoutePath = RoutePath(PathRepr::Static(""));
105
106    /// A path known when the program is written.
107    pub const fn from_static(path: &'static str) -> Self {
108        RoutePath(PathRepr::Static(path))
109    }
110
111    /// The path as text.
112    pub fn as_str(&self) -> &str {
113        match &self.0 {
114            PathRepr::Static(s) => s,
115            PathRepr::Shared(s) => s,
116        }
117    }
118
119    /// `true` for the empty path.
120    pub fn is_empty(&self) -> bool {
121        self.as_str().is_empty()
122    }
123
124    /// `"{self}.{segment}"`, or `segment` when `self` is empty — one
125    /// allocation, the new path's own.
126    pub fn join(&self, segment: &str) -> RoutePath {
127        if self.is_empty() {
128            return RoutePath::from(segment.to_owned());
129        }
130        let mut s = String::with_capacity(self.as_str().len() + 1 + segment.len());
131        s.push_str(self.as_str());
132        s.push('.');
133        s.push_str(segment);
134        RoutePath::from(s)
135    }
136}
137
138impl From<&'static str> for RoutePath {
139    fn from(s: &'static str) -> Self {
140        RoutePath::from_static(s)
141    }
142}
143
144impl From<String> for RoutePath {
145    fn from(s: String) -> Self {
146        RoutePath(PathRepr::Shared(Arc::from(s)))
147    }
148}
149
150impl From<Arc<str>> for RoutePath {
151    fn from(s: Arc<str>) -> Self {
152        RoutePath(PathRepr::Shared(s))
153    }
154}
155
156impl PartialEq for RoutePath {
157    fn eq(&self, other: &Self) -> bool {
158        self.as_str() == other.as_str()
159    }
160}
161
162impl Eq for RoutePath {}
163
164impl std::hash::Hash for RoutePath {
165    fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
166        self.as_str().hash(h)
167    }
168}
169
170impl fmt::Debug for RoutePath {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        fmt::Debug::fmt(self.as_str(), f)
173    }
174}
175
176impl fmt::Display for RoutePath {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        f.write_str(self.as_str())
179    }
180}
181
182/// A fully qualified Plexus method — the activation namespace and the method
183/// name, kept as separate fields because the transports need them
184/// differently:
185///
186/// | Transport | Uses |
187/// |---|---|
188/// | WebSocket JSON-RPC | `"{path}.{method}"` as the `params.method` of a `{service}.call` subscription |
189/// | REST + SSE | `POST /rest/{namespace}/{method}` |
190/// | in-process | `namespace` selects the activation, `method` is passed to `Activation::call` |
191///
192/// A pre-joined `&str` would force every transport to re-split it, and a
193/// mis-split is silent. The generated client emits `MethodRef::new(..)` as a
194/// const, so this costs nothing at the call site.
195///
196/// MACRO-16: a method of a `#[child]` activation is reached through its
197/// parent — `tickets.inputs.answer`, not `inputs.answer`. [`MethodRef::at`]
198/// gives the reference the dotted *path* the activation is mounted at
199/// (`"tickets.inputs"`); [`MethodRef::qualified`] then answers
200/// `"{path}.{method}"`. Without a path (every [`MethodRef::new`]) the path is
201/// the namespace, exactly as before.
202///
203/// RETURNS-46: the path is a [`RoutePath`] — a dynamic instance's path is a
204/// run-time value — so a `MethodRef` is `Clone`, not `Copy`.
205#[derive(Debug, Clone, PartialEq, Eq, Hash)]
206pub struct MethodRef {
207    namespace: &'static str,
208    method: &'static str,
209    /// The dotted path the activation is reached at; empty means its own
210    /// namespace (a service's top-level activation).
211    path: RoutePath,
212}
213
214impl MethodRef {
215    pub const fn new(namespace: &'static str, method: &'static str) -> Self {
216        Self { namespace, method, path: RoutePath::EMPTY }
217    }
218
219    /// The same method on the activation mounted at `path` — the dotted
220    /// route from the service to it, e.g. `"tickets.inputs"` for the
221    /// `inputs` child of `tickets`. A path equal to the namespace, or empty,
222    /// is the top-level reference itself (so `at` never makes two equal
223    /// methods compare unequal).
224    pub fn at(self, path: impl Into<RoutePath>) -> Self {
225        let path = path.into();
226        if path.is_empty() || path.as_str() == self.namespace {
227            Self { path: RoutePath::EMPTY, ..self }
228        } else {
229            Self { path, ..self }
230        }
231    }
232
233    /// The activation namespace, e.g. `"tickets"` (a child's own, e.g.
234    /// `"inputs"`).
235    pub const fn namespace(&self) -> &'static str {
236        self.namespace
237    }
238
239    /// The bare method name, e.g. `"watch"`.
240    pub const fn method(&self) -> &'static str {
241        self.method
242    }
243
244    /// The dotted path the activation is reached at: the namespace for a
245    /// top-level activation, `"tickets.inputs"` for a child.
246    pub fn path(&self) -> &str {
247        if self.path.is_empty() {
248            self.namespace
249        } else {
250            self.path.as_str()
251        }
252    }
253
254    /// The dotted form the service's `call` method expects, e.g.
255    /// `"tickets.watch"`, or `"tickets.inputs.answer"` for a child's method.
256    pub fn qualified(&self) -> String {
257        format!("{}.{}", self.path(), self.method)
258    }
259}
260
261impl fmt::Display for MethodRef {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        write!(f, "{}.{}", self.path(), self.method)
264    }
265}
266
267/// One Plexus wire implementation.
268///
269/// Every method call on a generated client turns into exactly one
270/// `Transport::call`. The returned stream yields the response items in order
271/// and ends after the terminal one (`done` or `error`); a transport that
272/// loses the connection mid-stream reports it as a
273/// [`TransportError`](crate::TransportError) item rather than by ending
274/// silently.
275///
276/// Implementations must **not** interpret `params` — the generated client
277/// has already built the by-name object the schema expects.
278pub trait Transport {
279    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_>;
280
281    /// [`call`](Self::call) for a typed client (PERF.115-36): the same items,
282    /// each data item's content still the wire's JSON, which
283    /// [`decode_raw`](crate::decode_raw) decodes straight into the method's
284    /// event. The default is `call`'s items, each content the `Value` it
285    /// carries; a transport that has the wire's text (`WsTransport`) hands it
286    /// over unread.
287    fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
288        Box::pin(self.call(method, params).map(|item| item.map(RawItem::from)))
289    }
290
291    /// BIDIR-6: [`call`](Self::call), for a method with an input half:
292    /// `input` is sent as the call runs, under the callee's credit, and ended
293    /// when it ends. A transport that carries no input half (the default)
294    /// says so in the one item it yields: the call does not hang.
295    fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
296        let _ = (params, input);
297        let refused = TransportError::protocol(format!("`{method}` takes an input stream, and this transport carries none"));
298        Box::pin(futures_util::stream::once(async move { Err(refused) }))
299    }
300
301    /// BIDIR-6: [`call_raw`](Self::call_raw), for a method with an input
302    /// half: what a typed client's method with an `Input` calls. The default
303    /// is [`call_with_input`](Self::call_with_input)'s items, each content
304    /// the `Value` it carries.
305    fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
306        Box::pin(self.call_with_input(method, params, input).map(|item| item.map(RawItem::from)))
307    }
308}
309
310/// So a client can be handed `&T`, `Arc<T>`, `Box<T>`, … interchangeably.
311impl<T: Transport + ?Sized> Transport for &T {
312    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
313        (**self).call(method, params)
314    }
315
316    fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
317        (**self).call_raw(method, params)
318    }
319
320    fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
321        (**self).call_with_input(method, params, input)
322    }
323
324    fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
325        (**self).call_raw_with_input(method, params, input)
326    }
327}
328
329impl<T: Transport + ?Sized> Transport for Box<T> {
330    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
331        (**self).call(method, params)
332    }
333
334    fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
335        (**self).call_raw(method, params)
336    }
337
338    fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
339        (**self).call_with_input(method, params, input)
340    }
341
342    fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
343        (**self).call_raw_with_input(method, params, input)
344    }
345}
346
347impl<T: Transport + ?Sized> Transport for std::rc::Rc<T> {
348    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
349        (**self).call(method, params)
350    }
351
352    fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
353        (**self).call_raw(method, params)
354    }
355
356    fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
357        (**self).call_with_input(method, params, input)
358    }
359
360    fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
361        (**self).call_raw_with_input(method, params, input)
362    }
363}
364
365impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
366    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
367        (**self).call(method, params)
368    }
369
370    fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
371        (**self).call_raw(method, params)
372    }
373
374    fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
375        (**self).call_with_input(method, params, input)
376    }
377
378    fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
379        (**self).call_raw_with_input(method, params, input)
380    }
381}