1use 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
32pub trait FromRoute<T>: Sized {
36 fn from_route(transport: T, route: Route) -> Self;
38}
39
40pub trait ShapeCheck {
46 fn shape_check(path: &str, schema: &Value) -> Result<(), ClientError>;
50}
51
52pub struct Untyped<T> {
54 transport: T,
55 route: Route,
56}
57
58impl<T> Untyped<T> {
59 pub fn new(transport: T, path: impl Into<RoutePath>) -> Self {
62 Self { transport, route: Route::at(path, "") }
63 }
64
65 pub fn from_route(transport: T, route: Route) -> Self {
68 Self { transport, route }
69 }
70
71 pub fn path(&self) -> &str {
73 self.route.path("")
74 }
75
76 pub fn route(&self) -> &Route {
78 &self.route
79 }
80
81 pub fn transport(&self) -> &T {
83 &self.transport
84 }
85
86 pub fn into_transport(self) -> T {
88 self.transport
89 }
90
91 pub fn child(&self, name: &str) -> Untyped<&T> {
96 Untyped { transport: &self.transport, route: self.route.segment(name) }
97 }
98
99 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 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 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 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 pub async fn schema(&self) -> Result<Value, ClientError> {
140 self.call_one("schema", Value::Object(Default::default())).await
141 }
142
143 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}