Skip to main content

plexus_client/
untyped.rs

1//! NEST-14 · a client for a node whose interface is not known when the
2//! program is written: an untyped peer slot, a `#[child(opaque)]`, a tree
3//! mounted at run time.
4//!
5//! [`Untyped`] is a transport and a dotted path. It calls a method by name
6//! ([`Untyped::call`], [`Untyped::call_one`]), reaches a node below by name
7//! ([`Untyped::child`]), asks the node's schema ([`Untyped::schema`]), and —
8//! once the caller knows the interface — becomes that interface's generated
9//! client, checked against the node's schema first ([`Untyped::typed`]):
10//!
11//! ```ignore
12//! let shop = dyn_client.peer("shop");                 // Untyped<&T>
13//! let shop: ShopClient<_> = shop.typed().await?;      // ShapeMismatch if it is not a shop
14//! let items = shop.items().list().await?;
15//! ```
16//!
17//! Its items are `serde_json::Value`s; nothing lifts them into a parent's
18//! aggregate (a typed parent has no variant for a node it cannot type).
19//! Works over every [`Transport`]: a socket, a service in process, a
20//! host's transport handed to a child.
21
22use std::fmt;
23
24use serde_json::Value;
25
26use crate::error::ClientError;
27use crate::method_stream::{call_one, MethodStream};
28use crate::route::Route;
29use crate::transport::{MethodRef, RoutePath, Transport};
30use crate::Content;
31
32/// A generated client made at a route: what [`Untyped::typed`] turns an
33/// untyped client into. The activation macro implements it for every client
34/// it emits (`XClient<T>`, its events its own).
35pub trait FromRoute<T>: Sized {
36    /// The client of the node at `route`, over `transport`.
37    fn from_route(transport: T, route: Route) -> Self;
38}
39
40/// What a generated client was built against, checked against a node's
41/// schema: the methods it calls, each by its shape's hash. The activation
42/// macro implements it beside the server half (where the method schemas
43/// are), so a client-only build (wasm32) has [`Untyped::typed_unchecked`]
44/// alone.
45pub trait ShapeCheck {
46    /// `Ok` when `schema` — the node at `path`'s answer to `schema` — serves
47    /// every method this client calls under the same shape; else
48    /// [`ClientError::ShapeMismatch`] naming those it does not.
49    fn shape_check(path: &str, schema: &Value) -> Result<(), ClientError>;
50}
51
52/// An untyped client: a transport and the dotted path of a node.
53pub struct Untyped<T> {
54    transport: T,
55    route: Route,
56}
57
58impl<T> Untyped<T> {
59    /// The node at the dotted `path` (`"host.dendrite.digest"`); empty is
60    /// the service itself.
61    pub fn new(transport: T, path: impl Into<RoutePath>) -> Self {
62        Self { transport, route: Route::at(path, "") }
63    }
64
65    /// The node at `route` — what a generated accessor builds; a refused
66    /// route makes a client every call of which fails at once.
67    pub fn from_route(transport: T, route: Route) -> Self {
68        Self { transport, route }
69    }
70
71    /// The node's dotted path.
72    pub fn path(&self) -> &str {
73        self.route.path("")
74    }
75
76    /// The node's route.
77    pub fn route(&self) -> &Route {
78        &self.route
79    }
80
81    /// Borrow the transport.
82    pub fn transport(&self) -> &T {
83        &self.transport
84    }
85
86    /// Unwrap the transport.
87    pub fn into_transport(self) -> T {
88        self.transport
89    }
90
91    /// The node `name` below this one (`<path>.<name>`): a static child, an
92    /// instance of a dynamic one, a peer slot's name. A name that is not a
93    /// route segment makes a client every call of which fails at once with
94    /// [`ClientError::InvalidName`].
95    pub fn child(&self, name: &str) -> Untyped<&T> {
96        Untyped { transport: &self.transport, route: self.route.segment(name) }
97    }
98
99    /// [`Self::child`], keeping the transport.
100    pub fn into_child(self, name: &str) -> Untyped<T> {
101        let route = self.route.segment(name);
102        Untyped { transport: self.transport, route }
103    }
104
105    /// The generated client `C` of this node, unchecked — for a caller that
106    /// knows the interface by other means, or a build with no
107    /// [`ShapeCheck`] (a client-only one).
108    pub fn typed_unchecked<C: FromRoute<T>>(self) -> C {
109        C::from_route(self.transport, self.route)
110    }
111
112    fn method(&self, method: &str) -> MethodRef {
113        MethodRef::named(RoutePath::from(self.path().to_owned()), RoutePath::from(method.to_owned()))
114    }
115}
116
117impl<T: Transport> Untyped<T> {
118    /// Call `method` on this node with `params` (an object, by name): its
119    /// items as JSON, `Err` for the call failing, progress dropped
120    /// (`.with_progress()` keeps it).
121    pub fn call(&self, method: &str, params: Value) -> MethodStream<'_, Value> {
122        let params = match self.route.refusal() {
123            None => Ok(params),
124            Some(e) => Err(e),
125        };
126        MethodStream::call(&self.transport, self.method(method), params, Content::decode::<Value>, |v| v)
127    }
128
129    /// Call a one-item `method`: its item, or why there is none.
130    pub async fn call_one(&self, method: &str, params: Value) -> Result<Value, ClientError> {
131        let params = match self.route.refusal() {
132            None => Ok(params),
133            Some(e) => Err(e),
134        };
135        call_one(&self.transport, self.method(method), params, Content::decode::<Value>).await
136    }
137
138    /// The node's schema, as it answers `<path>.schema`.
139    pub async fn schema(&self) -> Result<Value, ClientError> {
140        self.call_one("schema", Value::Object(Default::default())).await
141    }
142
143    /// This node as the generated client `C`, once its schema says it
144    /// serves `C`'s interface: every method `C` calls under the same shape
145    /// (a node that serves more is fine). Else
146    /// [`ClientError::ShapeMismatch`], and nothing else is called.
147    pub async fn typed<C: FromRoute<T> + ShapeCheck>(self) -> Result<C, ClientError> {
148        let schema = self.schema().await?;
149        C::shape_check(self.path(), &schema)?;
150        Ok(C::from_route(self.transport, self.route))
151    }
152}
153
154impl<T: Clone> Clone for Untyped<T> {
155    fn clone(&self) -> Self {
156        Self { transport: self.transport.clone(), route: self.route.clone() }
157    }
158}
159
160impl<T: fmt::Debug> fmt::Debug for Untyped<T> {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        f.debug_struct("Untyped").field("transport", &self.transport).field("path", &self.path()).finish()
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::{MemoryTransport, StreamItem};
170    use futures_util::StreamExt;
171    use serde_json::json;
172
173    fn data(ct: &str, v: Value) -> StreamItem {
174        StreamItem::Data { metadata: None, content_type: Some(ct.into()), content: v }
175    }
176
177    #[test]
178    fn calls_go_to_the_path_by_name() {
179        let t = MemoryTransport::new()
180            .script(MethodRef::named("host.dendrite.digest", "summarize"), vec![data("x", json!("a")), data("x", json!("b")), StreamItem::done()])
181            .script(MethodRef::named("host.dendrite.digest.inner", "ping"), vec![data("x", json!(1)), StreamItem::done()]);
182        let root = Untyped::new(&t, "host");
183        let u = root.child("dendrite").into_child("digest");
184        assert_eq!(u.path(), "host.dendrite.digest");
185        let items: Vec<_> = futures_executor_block(u.call("summarize", json!({"n": 2})).collect::<Vec<_>>());
186        assert_eq!(items, vec![Ok(json!("a")), Ok(json!("b"))]);
187        assert_eq!(t.params_of(MethodRef::named("host.dendrite.digest", "summarize")), Some(json!({"n": 2})));
188        let one = futures_executor_block(u.child("inner").call_one("ping", json!({})));
189        assert_eq!(one, Ok(json!(1)));
190    }
191
192    #[test]
193    fn a_bad_name_sends_nothing() {
194        let t = MemoryTransport::new();
195        let u = Untyped::new(&t, "host");
196        let bad = u.child("Not A Segment");
197        let r = futures_executor_block(bad.call_one("ping", json!({})));
198        assert!(matches!(r, Err(ClientError::InvalidName { .. })), "{r:?}");
199        assert!(t.calls().is_empty());
200    }
201
202    fn futures_executor_block<F: std::future::Future>(f: F) -> F::Output {
203        futures::executor::block_on(f)
204    }
205}