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: RoutePath,
211 method: RoutePath,
212 path: RoutePath,
215}
216
217impl MethodRef {
218 pub const fn new(namespace: &'static str, method: &'static str) -> Self {
219 Self {
220 namespace: RoutePath::from_static(namespace),
221 method: RoutePath::from_static(method),
222 path: RoutePath::EMPTY,
223 }
224 }
225
226 pub fn named(path: impl Into<RoutePath>, method: impl Into<RoutePath>) -> Self {
230 Self { namespace: path.into(), method: method.into(), path: RoutePath::EMPTY }
231 }
232
233 pub fn at(self, path: impl Into<RoutePath>) -> Self {
239 let path = path.into();
240 if path.is_empty() || path.as_str() == self.namespace.as_str() {
241 Self { path: RoutePath::EMPTY, ..self }
242 } else {
243 Self { path, ..self }
244 }
245 }
246
247 pub fn namespace(&self) -> &str {
253 self.namespace.as_str()
254 }
255
256 pub fn method(&self) -> &str {
258 self.method.as_str()
259 }
260
261 pub fn path(&self) -> &str {
264 if self.path.is_empty() {
265 self.namespace.as_str()
266 } else {
267 self.path.as_str()
268 }
269 }
270
271 pub fn qualified(&self) -> String {
274 format!("{}.{}", self.path(), self.method)
275 }
276}
277
278impl fmt::Display for MethodRef {
279 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280 write!(f, "{}.{}", self.path(), self.method)
281 }
282}
283
284pub trait Transport {
296 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_>;
297
298 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
305 Box::pin(self.call(method, params).map(|item| item.map(RawItem::from)))
306 }
307
308 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
313 let _ = (params, input);
314 let refused = TransportError::protocol(format!("`{method}` takes an input stream, and this transport carries none"));
315 Box::pin(futures_util::stream::once(async move { Err(refused) }))
316 }
317
318 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
323 Box::pin(self.call_with_input(method, params, input).map(|item| item.map(RawItem::from)))
324 }
325}
326
327impl<T: Transport + ?Sized> Transport for &T {
329 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
330 (**self).call(method, params)
331 }
332
333 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
334 (**self).call_raw(method, params)
335 }
336
337 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
338 (**self).call_with_input(method, params, input)
339 }
340
341 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
342 (**self).call_raw_with_input(method, params, input)
343 }
344}
345
346impl<T: Transport + ?Sized> Transport for Box<T> {
347 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
348 (**self).call(method, params)
349 }
350
351 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
352 (**self).call_raw(method, params)
353 }
354
355 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
356 (**self).call_with_input(method, params, input)
357 }
358
359 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
360 (**self).call_raw_with_input(method, params, input)
361 }
362}
363
364impl<T: Transport + ?Sized> Transport for std::rc::Rc<T> {
365 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
366 (**self).call(method, params)
367 }
368
369 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
370 (**self).call_raw(method, params)
371 }
372
373 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
374 (**self).call_with_input(method, params, input)
375 }
376
377 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
378 (**self).call_raw_with_input(method, params, input)
379 }
380}
381
382impl<T: Transport + ?Sized> Transport for std::sync::Arc<T> {
383 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
384 (**self).call(method, params)
385 }
386
387 fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
388 (**self).call_raw(method, params)
389 }
390
391 fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
392 (**self).call_with_input(method, params, input)
393 }
394
395 fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
396 (**self).call_raw_with_input(method, params, input)
397 }
398}