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::StreamItem;
5use crate::error::TransportError;
6use futures_core::Stream;
7use serde_json::Value;
8use std::fmt;
9use std::pin::Pin;
10
11/// A boxed stream of wire items.
12///
13/// `Send` is required off wasm32 (so native callers can `tokio::spawn` a
14/// client stream) and **not** required on wasm32, where the browser futures a
15/// transport must build on (`JsFuture`, `ReadableStreamDefaultReader`) are
16/// `!Send` by construction.
17#[cfg(not(target_arch = "wasm32"))]
18pub type ItemStream<'a> =
19    Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + Send + 'a>>;
20
21/// A boxed stream of wire items. See the non-wasm32 variant for the
22/// `Send`-bound rationale.
23#[cfg(target_arch = "wasm32")]
24pub type ItemStream<'a> = Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + 'a>>;
25
26/// A fully qualified Plexus method — the activation namespace and the method
27/// name, kept as separate fields because the transports need them
28/// differently:
29///
30/// | Transport | Uses |
31/// |---|---|
32/// | WebSocket JSON-RPC | `"{path}.{method}"` as the `params.method` of a `{hub}.call` subscription |
33/// | REST + SSE | `POST /rest/{namespace}/{method}` |
34/// | in-process | `namespace` selects the activation, `method` is passed to `Activation::call` |
35///
36/// A pre-joined `&str` would force every transport to re-split it, and a
37/// mis-split is silent. The generated client emits `MethodRef::new(..)` as a
38/// const, so this costs nothing at the call site.
39///
40/// MACRO-16: a method of a `#[child]` activation is reached through its
41/// parent — `tickets.inputs.answer`, not `inputs.answer`. [`MethodRef::at`]
42/// gives the reference the dotted *path* the activation is mounted at
43/// (`"tickets.inputs"`); [`MethodRef::qualified`] then answers
44/// `"{path}.{method}"`. Without a path (every [`MethodRef::new`]) the path is
45/// the namespace, exactly as before.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47pub struct MethodRef {
48    namespace: &'static str,
49    method: &'static str,
50    /// The dotted path the activation is reached at; `""` means its own
51    /// namespace (a hub's top-level activation).
52    path: &'static str,
53}
54
55impl MethodRef {
56    pub const fn new(namespace: &'static str, method: &'static str) -> Self {
57        Self { namespace, method, path: "" }
58    }
59
60    /// The same method on the activation mounted at `path` — the dotted
61    /// route from the hub to it, e.g. `"tickets.inputs"` for the `inputs`
62    /// child of `tickets`. A path equal to the namespace, or empty, is the
63    /// top-level reference itself (so `at` never makes two equal methods
64    /// compare unequal).
65    pub fn at(self, path: &'static str) -> Self {
66        if path.is_empty() || path == self.namespace {
67            Self { path: "", ..self }
68        } else {
69            Self { path, ..self }
70        }
71    }
72
73    /// The activation namespace, e.g. `"tickets"` (a child's own, e.g.
74    /// `"inputs"`).
75    pub const fn namespace(&self) -> &'static str {
76        self.namespace
77    }
78
79    /// The bare method name, e.g. `"watch"`.
80    pub const fn method(&self) -> &'static str {
81        self.method
82    }
83
84    /// The dotted path the activation is reached at: the namespace for a
85    /// top-level activation, `"tickets.inputs"` for a child.
86    pub const fn path(&self) -> &'static str {
87        if self.path.is_empty() {
88            self.namespace
89        } else {
90            self.path
91        }
92    }
93
94    /// The dotted form the hub's `call` method expects, e.g.
95    /// `"tickets.watch"`, or `"tickets.inputs.answer"` for a child's method.
96    pub fn qualified(&self) -> String {
97        format!("{}.{}", self.path(), self.method)
98    }
99}
100
101impl fmt::Display for MethodRef {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "{}.{}", self.path(), self.method)
104    }
105}
106
107/// MACRO-16: `"{parent}.{child}"` as a `&'static str`, for a generated
108/// client's child accessor. A top-level parent (`""`) needs no join: the
109/// path is `segment` itself. A deeper one is joined once per distinct pair
110/// and kept for the life of the process — the set is the static tree of
111/// `#[child]` accessors, so it is bounded by the program, not by its input.
112#[doc(hidden)]
113pub fn join_path(parent: &'static str, segment: &'static str) -> &'static str {
114    use std::collections::HashMap;
115    use std::sync::{Mutex, OnceLock};
116    if parent.is_empty() {
117        return segment;
118    }
119    static PATHS: OnceLock<Mutex<HashMap<(&'static str, &'static str), &'static str>>> = OnceLock::new();
120    let mut paths = PATHS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
121    paths
122        .entry((parent, segment))
123        .or_insert_with(|| Box::leak(format!("{parent}.{segment}").into_boxed_str()))
124}
125
126/// One Plexus wire implementation.
127///
128/// Every method call on a generated client turns into exactly one
129/// `Transport::call`. The returned stream yields the response items in order
130/// and ends after the terminal one (`done` or `error`); a transport that
131/// loses the connection mid-stream reports it as a
132/// [`TransportError`](crate::TransportError) item rather than by ending
133/// silently.
134///
135/// Implementations must **not** interpret `params` — the generated client
136/// has already built the by-name object the schema expects.
137pub trait Transport {
138    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_>;
139}
140
141/// So a client can be handed `&T`, `Arc<T>`, `Box<T>`, … interchangeably.
142impl<T: Transport + ?Sized> Transport for &T {
143    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
144        (**self).call(method, params)
145    }
146}
147
148impl<T: Transport + ?Sized> Transport for Box<T> {
149    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
150        (**self).call(method, params)
151    }
152}
153
154impl<T: Transport + ?Sized> Transport for std::rc::Rc<T> {
155    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
156        (**self).call(method, params)
157    }
158}
159
160impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
161    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
162        (**self).call(method, params)
163    }
164}