use std::fmt;
use serde_json::Value;
use crate::error::ClientError;
use crate::method_stream::{call_one, MethodStream};
use crate::route::Route;
use crate::transport::{MethodRef, RoutePath, Transport};
use crate::Content;
pub trait FromRoute<T>: Sized {
fn from_route(transport: T, route: Route) -> Self;
}
pub trait ShapeCheck {
fn shape_check(path: &str, schema: &Value) -> Result<(), ClientError>;
}
pub struct Untyped<T> {
transport: T,
route: Route,
}
impl<T> Untyped<T> {
pub fn new(transport: T, path: impl Into<RoutePath>) -> Self {
Self { transport, route: Route::at(path, "") }
}
pub fn from_route(transport: T, route: Route) -> Self {
Self { transport, route }
}
pub fn path(&self) -> &str {
self.route.path("")
}
pub fn route(&self) -> &Route {
&self.route
}
pub fn transport(&self) -> &T {
&self.transport
}
pub fn into_transport(self) -> T {
self.transport
}
pub fn child(&self, name: &str) -> Untyped<&T> {
Untyped { transport: &self.transport, route: self.route.segment(name) }
}
pub fn into_child(self, name: &str) -> Untyped<T> {
let route = self.route.segment(name);
Untyped { transport: self.transport, route }
}
pub fn typed_unchecked<C: FromRoute<T>>(self) -> C {
C::from_route(self.transport, self.route)
}
fn method(&self, method: &str) -> MethodRef {
MethodRef::named(RoutePath::from(self.path().to_owned()), RoutePath::from(method.to_owned()))
}
}
impl<T: Transport> Untyped<T> {
pub fn call(&self, method: &str, params: Value) -> MethodStream<'_, Value> {
let params = match self.route.refusal() {
None => Ok(params),
Some(e) => Err(e),
};
MethodStream::call(&self.transport, self.method(method), params, Content::decode::<Value>, |v| v)
}
pub async fn call_one(&self, method: &str, params: Value) -> Result<Value, ClientError> {
let params = match self.route.refusal() {
None => Ok(params),
Some(e) => Err(e),
};
call_one(&self.transport, self.method(method), params, Content::decode::<Value>).await
}
pub async fn schema(&self) -> Result<Value, ClientError> {
self.call_one("schema", Value::Object(Default::default())).await
}
pub async fn typed<C: FromRoute<T> + ShapeCheck>(self) -> Result<C, ClientError> {
let schema = self.schema().await?;
C::shape_check(self.path(), &schema)?;
Ok(C::from_route(self.transport, self.route))
}
}
impl<T: Clone> Clone for Untyped<T> {
fn clone(&self) -> Self {
Self { transport: self.transport.clone(), route: self.route.clone() }
}
}
impl<T: fmt::Debug> fmt::Debug for Untyped<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Untyped").field("transport", &self.transport).field("path", &self.path()).finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{MemoryTransport, StreamItem};
use futures_util::StreamExt;
use serde_json::json;
fn data(ct: &str, v: Value) -> StreamItem {
StreamItem::Data { metadata: None, content_type: Some(ct.into()), content: v }
}
#[test]
fn calls_go_to_the_path_by_name() {
let t = MemoryTransport::new()
.script(MethodRef::named("host.dendrite.digest", "summarize"), vec![data("x", json!("a")), data("x", json!("b")), StreamItem::done()])
.script(MethodRef::named("host.dendrite.digest.inner", "ping"), vec![data("x", json!(1)), StreamItem::done()]);
let root = Untyped::new(&t, "host");
let u = root.child("dendrite").into_child("digest");
assert_eq!(u.path(), "host.dendrite.digest");
let items: Vec<_> = futures_executor_block(u.call("summarize", json!({"n": 2})).collect::<Vec<_>>());
assert_eq!(items, vec![Ok(json!("a")), Ok(json!("b"))]);
assert_eq!(t.params_of(MethodRef::named("host.dendrite.digest", "summarize")), Some(json!({"n": 2})));
let one = futures_executor_block(u.child("inner").call_one("ping", json!({})));
assert_eq!(one, Ok(json!(1)));
}
#[test]
fn a_bad_name_sends_nothing() {
let t = MemoryTransport::new();
let u = Untyped::new(&t, "host");
let bad = u.child("Not A Segment");
let r = futures_executor_block(bad.call_one("ping", json!({})));
assert!(matches!(r, Err(ClientError::InvalidName { .. })), "{r:?}");
assert!(t.calls().is_empty());
}
fn futures_executor_block<F: std::future::Future>(f: F) -> F::Output {
futures::executor::block_on(f)
}
}