1use crate::envelope::{RawItem, StreamItem};
5use crate::error::TransportError;
6use futures_core::Stream;
7use futures_util::StreamExt;
8use serde_json::Value;
9use std::fmt;
10use std::pin::Pin;
11use std::sync::Arc;
12
13#[cfg(not(target_arch = "wasm32"))]
20pub type ItemStream<'a> =
21 Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + Send + 'a>>;
22
23#[cfg(target_arch = "wasm32")]
26pub type ItemStream<'a> = Pin<Box<dyn Stream<Item = Result<StreamItem, TransportError>> + 'a>>;
27
28#[cfg(not(target_arch = "wasm32"))]
31pub type RawItemStream<'a> =
32 Pin<Box<dyn Stream<Item = Result<RawItem, TransportError>> + Send + 'a>>;
33
34#[cfg(target_arch = "wasm32")]
36pub type RawItemStream<'a> = Pin<Box<dyn Stream<Item = Result<RawItem, TransportError>> + 'a>>;
37
38pub type InputItems<'a> = crate::contract::BoxStream<'a, Result<InputItem, TransportError>>;
41
42#[derive(Debug, Clone, PartialEq)]
44#[non_exhaustive]
45pub enum InputItem {
46 Json(Value),
48 #[cfg(feature = "binary")]
51 Binary(bytes::Bytes),
52}
53
54pub fn encode_input<'a, T, S>(input: S) -> InputItems<'a>
58where
59 T: serde::Serialize + 'static,
60 S: Stream<Item = T> + crate::contract::MaybeSend + 'a,
61{
62 use futures_util::StreamExt;
63 Box::pin(input.map(|item| {
64 #[cfg(feature = "binary")]
65 {
66 let mut slot = Some(item);
67 let any: &mut dyn core::any::Any = &mut slot;
68 if let Some(bytes) = any.downcast_mut::<Option<bytes::Bytes>>() {
69 return Ok(InputItem::Binary(bytes.take().expect("taken once")));
70 }
71 let item = slot.take().expect("not taken");
72 json_item(&item)
73 }
74 #[cfg(not(feature = "binary"))]
75 json_item(&item)
76 }))
77}
78
79fn json_item<T: serde::Serialize>(item: &T) -> Result<InputItem, TransportError> {
80 serde_json::to_value(item).map(InputItem::Json).map_err(|e| TransportError::protocol(format!("an input item will not serialize: {e}")))
81}
82
83#[derive(Clone)]
94pub struct RoutePath(PathRepr);
95
96#[derive(Clone)]
97enum PathRepr {
98 Static(&'static str),
99 Shared(Arc<str>),
100}
101
102impl RoutePath {
103 pub const EMPTY: RoutePath = RoutePath(PathRepr::Static(""));
105
106 pub const fn from_static(path: &'static str) -> Self {
108 RoutePath(PathRepr::Static(path))
109 }
110
111 pub fn as_str(&self) -> &str {
113 match &self.0 {
114 PathRepr::Static(s) => s,
115 PathRepr::Shared(s) => s,
116 }
117 }
118
119 pub fn is_empty(&self) -> bool {
121 self.as_str().is_empty()
122 }
123
124 pub fn join(&self, segment: &str) -> RoutePath {
127 if self.is_empty() {
128 return RoutePath::from(segment.to_owned());
129 }
130 let mut s = String::with_capacity(self.as_str().len() + 1 + segment.len());
131 s.push_str(self.as_str());
132 s.push('.');
133 s.push_str(segment);
134 RoutePath::from(s)
135 }
136}
137
138impl From<&'static str> for RoutePath {
139 fn from(s: &'static str) -> Self {
140 RoutePath::from_static(s)
141 }
142}
143
144impl From<String> for RoutePath {
145 fn from(s: String) -> Self {
146 RoutePath(PathRepr::Shared(Arc::from(s)))
147 }
148}
149
150impl From<Arc<str>> for RoutePath {
151 fn from(s: Arc<str>) -> Self {
152 RoutePath(PathRepr::Shared(s))
153 }
154}
155
156impl PartialEq for RoutePath {
157 fn eq(&self, other: &Self) -> bool {
158 self.as_str() == other.as_str()
159 }
160}
161
162impl Eq for RoutePath {}
163
164impl std::hash::Hash for RoutePath {
165 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
166 self.as_str().hash(h)
167 }
168}
169
170impl fmt::Debug for RoutePath {
171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 fmt::Debug::fmt(self.as_str(), f)
173 }
174}
175
176impl fmt::Display for RoutePath {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 f.write_str(self.as_str())
179 }
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Hash)]
206pub struct MethodRef {
207 namespace: &'static str,
208 method: &'static str,
209 path: RoutePath,
212}
213
214impl MethodRef {
215 pub const fn new(namespace: &'static str, method: &'static str) -> Self {
216 Self { namespace, method, path: RoutePath::EMPTY }
217 }
218
219 pub fn at(self, path: impl Into<RoutePath>) -> Self {
225 let path = path.into();
226 if path.is_empty() || path.as_str() == self.namespace {
227 Self { path: RoutePath::EMPTY, ..self }
228 } else {
229 Self { path, ..self }
230 }
231 }
232
233 pub const fn namespace(&self) -> &'static str {
236 self.namespace
237 }
238
239 pub const fn method(&self) -> &'static str {
241 self.method
242 }
243
244 pub fn path(&self) -> &str {
247 if self.path.is_empty() {
248 self.namespace
249 } else {
250 self.path.as_str()
251 }
252 }
253
254 pub fn qualified(&self) -> String {
257 format!("{}.{}", self.path(), self.method)
258 }
259}
260
261impl fmt::Display for MethodRef {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 write!(f, "{}.{}", self.path(), self.method)
264 }
265}
266
267pub trait Transport {
279 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_>;
280
281 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
288 Box::pin(self.call(method, params).map(|item| item.map(RawItem::from)))
289 }
290
291 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
296 let _ = (params, input);
297 let refused = TransportError::protocol(format!("`{method}` takes an input stream, and this transport carries none"));
298 Box::pin(futures_util::stream::once(async move { Err(refused) }))
299 }
300
301 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
306 Box::pin(self.call_with_input(method, params, input).map(|item| item.map(RawItem::from)))
307 }
308}
309
310impl<T: Transport + ?Sized> Transport for &T {
312 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
313 (**self).call(method, params)
314 }
315
316 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
317 (**self).call_raw(method, params)
318 }
319
320 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
321 (**self).call_with_input(method, params, input)
322 }
323
324 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
325 (**self).call_raw_with_input(method, params, input)
326 }
327}
328
329impl<T: Transport + ?Sized> Transport for Box<T> {
330 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
331 (**self).call(method, params)
332 }
333
334 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
335 (**self).call_raw(method, params)
336 }
337
338 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
339 (**self).call_with_input(method, params, input)
340 }
341
342 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
343 (**self).call_raw_with_input(method, params, input)
344 }
345}
346
347impl<T: Transport + ?Sized> Transport for std::rc::Rc<T> {
348 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
349 (**self).call(method, params)
350 }
351
352 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
353 (**self).call_raw(method, params)
354 }
355
356 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
357 (**self).call_with_input(method, params, input)
358 }
359
360 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
361 (**self).call_raw_with_input(method, params, input)
362 }
363}
364
365impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
366 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
367 (**self).call(method, params)
368 }
369
370 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
371 (**self).call_raw(method, params)
372 }
373
374 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
375 (**self).call_with_input(method, params, input)
376 }
377
378 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
379 (**self).call_raw_with_input(method, params, input)
380 }
381}