use crate::envelope::{RawItem, StreamItem};
use crate::error::TransportError;
use futures_core::Stream;
use futures_util::StreamExt;
use serde_json::Value;
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
#[cfg(not(target_arch = "wasm32"))]
pub type ItemStream<'a> =
Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
pub type ItemStream<'a> = Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + 'a>>;
#[cfg(not(target_arch = "wasm32"))]
pub type RawItemStream<'a> =
Pin<Box<dyn Stream<Item = Result<RawItem, TransportError>> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
pub type RawItemStream<'a> = Pin<Box<dyn Stream<Item = Result<RawItem, TransportError>> + 'a>>;
pub type InputItems<'a> = crate::contract::BoxStream<'a, Result<InputItem, TransportError>>;
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum InputItem {
Json(Value),
#[cfg(feature = "binary")]
Binary(bytes::Bytes),
}
pub fn encode_input<'a, T, S>(input: S) -> InputItems<'a>
where
T: serde::Serialize + 'static,
S: Stream<Item = T> + crate::contract::MaybeSend + 'a,
{
use futures_util::StreamExt;
Box::pin(input.map(|item| {
#[cfg(feature = "binary")]
{
let mut slot = Some(item);
let any: &mut dyn core::any::Any = &mut slot;
if let Some(bytes) = any.downcast_mut::<Option<bytes::Bytes>>() {
return Ok(InputItem::Binary(bytes.take().expect("taken once")));
}
let item = slot.take().expect("not taken");
json_item(&item)
}
#[cfg(not(feature = "binary"))]
json_item(&item)
}))
}
fn json_item<T: serde::Serialize>(item: &T) -> Result<InputItem, TransportError> {
serde_json::to_value(item).map(InputItem::Json).map_err(|e| TransportError::protocol(format!("an input item will not serialize: {e}")))
}
#[derive(Clone)]
pub struct RoutePath(PathRepr);
#[derive(Clone)]
enum PathRepr {
Static(&'static str),
Shared(Arc<str>),
}
impl RoutePath {
pub const EMPTY: RoutePath = RoutePath(PathRepr::Static(""));
pub const fn from_static(path: &'static str) -> Self {
RoutePath(PathRepr::Static(path))
}
pub fn as_str(&self) -> &str {
match &self.0 {
PathRepr::Static(s) => s,
PathRepr::Shared(s) => s,
}
}
pub fn is_empty(&self) -> bool {
self.as_str().is_empty()
}
pub fn join(&self, segment: &str) -> RoutePath {
if self.is_empty() {
return RoutePath::from(segment.to_owned());
}
let mut s = String::with_capacity(self.as_str().len() + 1 + segment.len());
s.push_str(self.as_str());
s.push('.');
s.push_str(segment);
RoutePath::from(s)
}
}
impl From<&'static str> for RoutePath {
fn from(s: &'static str) -> Self {
RoutePath::from_static(s)
}
}
impl From<String> for RoutePath {
fn from(s: String) -> Self {
RoutePath(PathRepr::Shared(Arc::from(s)))
}
}
impl From<Arc<str>> for RoutePath {
fn from(s: Arc<str>) -> Self {
RoutePath(PathRepr::Shared(s))
}
}
impl PartialEq for RoutePath {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl Eq for RoutePath {}
impl std::hash::Hash for RoutePath {
fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
self.as_str().hash(h)
}
}
impl fmt::Debug for RoutePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
impl fmt::Display for RoutePath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MethodRef {
namespace: RoutePath,
method: RoutePath,
path: RoutePath,
}
impl MethodRef {
pub const fn new(namespace: &'static str, method: &'static str) -> Self {
Self {
namespace: RoutePath::from_static(namespace),
method: RoutePath::from_static(method),
path: RoutePath::EMPTY,
}
}
pub fn named(path: impl Into<RoutePath>, method: impl Into<RoutePath>) -> Self {
Self { namespace: path.into(), method: method.into(), path: RoutePath::EMPTY }
}
pub fn at(self, path: impl Into<RoutePath>) -> Self {
let path = path.into();
if path.is_empty() || path.as_str() == self.namespace.as_str() {
Self { path: RoutePath::EMPTY, ..self }
} else {
Self { path, ..self }
}
}
pub fn namespace(&self) -> &str {
self.namespace.as_str()
}
pub fn method(&self) -> &str {
self.method.as_str()
}
pub fn path(&self) -> &str {
if self.path.is_empty() {
self.namespace.as_str()
} else {
self.path.as_str()
}
}
pub fn qualified(&self) -> String {
format!("{}.{}", self.path(), self.method)
}
}
impl fmt::Display for MethodRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}", self.path(), self.method)
}
}
pub trait Transport {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_>;
fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
Box::pin(self.call(method, params).map(|item| item.map(RawItem::from)))
}
fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
let _ = (params, input);
let refused = TransportError::protocol(format!("`{method}` takes an input stream, and this transport carries none"));
Box::pin(futures_util::stream::once(async move { Err(refused) }))
}
fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
Box::pin(self.call_with_input(method, params, input).map(|item| item.map(RawItem::from)))
}
}
impl<T: Transport + ?Sized> Transport for &T {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
(**self).call_raw(method, params)
}
fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
(**self).call_with_input(method, params, input)
}
fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
(**self).call_raw_with_input(method, params, input)
}
}
impl<T: Transport + ?Sized> Transport for Box<T> {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
(**self).call_raw(method, params)
}
fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
(**self).call_with_input(method, params, input)
}
fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
(**self).call_raw_with_input(method, params, input)
}
}
impl<T: Transport + ?Sized> Transport for std::rc::Rc<T> {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
(**self).call_raw(method, params)
}
fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
(**self).call_with_input(method, params, input)
}
fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
(**self).call_raw_with_input(method, params, input)
}
}
impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
(**self).call(method, params)
}
fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
(**self).call_raw(method, params)
}
fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
(**self).call_with_input(method, params, input)
}
fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
(**self).call_raw_with_input(method, params, input)
}
}