use std::fmt;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures_core::{FusedStream, Stream};
use serde::de::{self, DeserializeOwned, Deserializer};
use serde::{Deserialize, Serialize, Serializer};
use serde_json::Value;
use crate::envelope::{Content, RawItem};
use crate::error::ClientError;
use crate::frame::Frame;
use crate::lift::{Lift, Root};
use crate::transport::{InputItems, MethodRef, RawItemStream, Transport};
pub type Decoder<I> = fn(Content) -> Result<I, serde_json::Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NoProgress {}
impl Serialize for NoProgress {
fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
match *self {}
}
}
impl<'de> Deserialize<'de> for NoProgress {
fn deserialize<D: Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
Err(de::Error::custom(
"a progress frame for a method that declares no progress",
))
}
}
enum State<'a> {
Live(RawItemStream<'a>),
Failed(ClientError),
Finished,
}
struct Core<'a, I> {
state: State<'a>,
item: Decoder<I>,
}
impl<'a, I> Core<'a, I> {
fn new(state: State<'a>, item: Decoder<I>) -> Self {
Self { state, item }
}
fn poll_frame<P>(
&mut self,
cx: &mut Context<'_>,
progress: Option<Decoder<P>>,
) -> Poll<Option<Result<Frame<I, P>, ClientError>>> {
loop {
let next = match &mut self.state {
State::Live(items) => match items.as_mut().poll_next(cx) {
Poll::Pending => return Poll::Pending,
Poll::Ready(next) => next,
},
State::Failed(_) => {
let State::Failed(e) = std::mem::replace(&mut self.state, State::Finished)
else {
unreachable!("matched Failed above")
};
return Poll::Ready(Some(Err(e)));
}
State::Finished => return Poll::Ready(None),
};
let (out, terminal) = match next {
None | Some(Ok(RawItem::Done)) => {
self.state = State::Finished;
return Poll::Ready(None);
}
Some(Err(e)) => (Err(ClientError::Transport(e)), true),
Some(Ok(RawItem::Error { error, .. })) => (Err(ClientError::Remote(*error)), true),
Some(Ok(RawItem::Data { content, content_type })) => match (self.item)(content) {
Ok(item) => (Ok(Frame::Item(item)), false),
Err(e) => (
Err(ClientError::Decode {
content_type: content_type.map(|c| c.to_string()),
message: message_of(&e),
}),
true,
),
},
Some(Ok(RawItem::Progress { content, content_type })) => match progress {
None => continue,
Some(decode) => match decode(content) {
Ok(p) => (Ok(Frame::Progress(p)), false),
Err(e) => (
Err(ClientError::Decode {
content_type: content_type.map(|c| c.to_string()),
message: format!("progress: {}", message_of(&e)),
}),
true,
),
},
},
};
if terminal {
self.state = State::Finished;
}
return Poll::Ready(Some(out));
}
}
fn is_terminated(&self) -> bool {
matches!(self.state, State::Finished)
}
fn state_name(&self) -> &'static str {
match self.state {
State::Live(_) => "live",
State::Failed(_) => "failed",
State::Finished => "finished",
}
}
}
fn identity<T>(t: T) -> T {
t
}
fn message_of(e: &serde_json::Error) -> String {
let message = e.to_string();
if e.line() == 0 {
return message;
}
let at = format!(" at line {} column {}", e.line(), e.column());
match message.strip_suffix(&at) {
Some(bare) => bare.to_owned(),
None => message,
}
}
pub trait EventOf<I> {
type Aggregate;
fn event(&self, item: I) -> Self::Aggregate;
}
impl<I, A> EventOf<I> for fn(I) -> A {
type Aggregate = A;
#[inline]
fn event(&self, item: I) -> A {
self(item)
}
}
pub struct MethodStream<'a, I, P = NoProgress, A = I, L = Root, W = fn(I) -> A> {
core: Core<'a, I>,
event: W,
_aggregate: PhantomData<fn() -> A>,
lift: L,
_progress: PhantomData<fn() -> P>,
}
impl<'a, I, P, A> MethodStream<'a, I, P, A> {
pub fn new(items: RawItemStream<'a>, item: Decoder<I>, event: fn(I) -> A) -> Self {
Self::from_core(Core::new(State::Live(items), item), event)
}
pub fn call<T>(
transport: &'a T,
method: MethodRef,
params: Result<Value, ClientError>,
item: Decoder<I>,
event: fn(I) -> A,
) -> Self
where
T: Transport + ?Sized,
{
let state = match params {
Ok(params) => State::Live(transport.call_raw(method, params)),
Err(e) => State::Failed(e),
};
Self::from_core(Core::new(state, item), event)
}
pub fn call_with_input<T>(
transport: &'a T,
method: MethodRef,
params: Result<Value, ClientError>,
input: InputItems<'a>,
item: Decoder<I>,
event: fn(I) -> A,
) -> Self
where
T: Transport + ?Sized,
{
let state = match params {
Ok(params) => State::Live(transport.call_raw_with_input(method, params, input)),
Err(e) => State::Failed(e),
};
Self::from_core(Core::new(state, item), event)
}
fn from_core(core: Core<'a, I>, event: fn(I) -> A) -> Self {
Self {
core,
event,
_aggregate: PhantomData,
lift: Root,
_progress: PhantomData,
}
}
pub fn call_as<T, W>(
transport: &'a T,
method: MethodRef,
params: Result<Value, ClientError>,
item: Decoder<I>,
event: W,
) -> MethodStream<'a, I, P, A, Root, W>
where
T: Transport + ?Sized,
W: EventOf<I, Aggregate = A>,
{
let state = match params {
Ok(params) => State::Live(transport.call_raw(method, params)),
Err(e) => State::Failed(e),
};
MethodStream {
core: Core::new(state, item),
event,
_aggregate: PhantomData,
lift: Root,
_progress: PhantomData,
}
}
}
impl<'a, I, P, A> MethodStream<'a, I, P, A> {
pub fn call_as_with_input<T, W>(
transport: &'a T,
method: MethodRef,
params: Result<Value, ClientError>,
input: InputItems<'a>,
item: Decoder<I>,
event: W,
) -> MethodStream<'a, I, P, A, Root, W>
where
T: Transport + ?Sized,
W: EventOf<I, Aggregate = A>,
{
let state = match params {
Ok(params) => State::Live(transport.call_raw_with_input(method, params, input)),
Err(e) => State::Failed(e),
};
MethodStream {
core: Core::new(state, item),
event,
_aggregate: PhantomData,
lift: Root,
_progress: PhantomData,
}
}
}
impl<'a, I, P, A, L, W> MethodStream<'a, I, P, A, L, W> {
pub fn lifted<L2: Lift<A>>(self, lift: L2) -> MethodStream<'a, I, P, A, L2, W> {
MethodStream {
core: self.core,
event: self.event,
_aggregate: PhantomData,
lift,
_progress: PhantomData,
}
}
pub fn with_progress(self) -> WithProgress<'a, I, P>
where
P: DeserializeOwned,
{
WithProgress {
core: self.core,
_progress: PhantomData,
}
}
pub fn events(self) -> Events<'a, L::Out>
where
L: Lift<A>,
W: EventOf<I, Aggregate = A> + Clone + MaybeSendSync + 'a,
I: 'a,
P: 'a,
A: 'a,
L::Out: 'a,
{
let event = self.event.clone();
let lift = self.lift.clone();
Events {
inner: Box::pin(futures_util::StreamExt::map(self, move |r| r.map(|i| lift.lift(event.event(i))))),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSendSync: Send + Sync {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + Sync> MaybeSendSync for T {}
#[cfg(target_arch = "wasm32")]
pub trait MaybeSendSync {}
#[cfg(target_arch = "wasm32")]
impl<T> MaybeSendSync for T {}
impl<I, P, A, L, W> Unpin for MethodStream<'_, I, P, A, L, W> {}
impl<I, P, A, L, W> Stream for MethodStream<'_, I, P, A, L, W> {
type Item = Result<I, ClientError>;
#[inline]
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()
.core
.poll_frame::<NoProgress>(cx, None)
.map(|next| {
next.map(|frame| {
frame.map(|frame| match frame {
Frame::Item(item) => item,
Frame::Progress(never) => match never {},
})
})
})
}
}
impl<I, P, A, L, W> FusedStream for MethodStream<'_, I, P, A, L, W> {
fn is_terminated(&self) -> bool {
self.core.is_terminated()
}
}
impl<I, P, A, L, W> fmt::Debug for MethodStream<'_, I, P, A, L, W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MethodStream")
.field("state", &self.core.state_name())
.finish_non_exhaustive()
}
}
pub struct WithProgress<'a, I, P> {
core: Core<'a, I>,
_progress: PhantomData<fn() -> P>,
}
impl<I, P: DeserializeOwned> Stream for WithProgress<'_, I, P> {
type Item = Result<Frame<I, P>, ClientError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut()
.core
.poll_frame(cx, Some(Content::decode::<P> as Decoder<P>))
}
}
impl<I, P: DeserializeOwned> FusedStream for WithProgress<'_, I, P> {
fn is_terminated(&self) -> bool {
self.core.is_terminated()
}
}
impl<I, P> fmt::Debug for WithProgress<'_, I, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WithProgress")
.field("state", &self.core.state_name())
.finish_non_exhaustive()
}
}
#[cfg(not(target_arch = "wasm32"))]
type BoxedEvents<'a, A> = Pin<Box<dyn FusedStream<Item = Result<A, ClientError>> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
type BoxedEvents<'a, A> = Pin<Box<dyn FusedStream<Item = Result<A, ClientError>> + 'a>>;
pub struct Events<'a, A> {
inner: BoxedEvents<'a, A>,
}
impl<A> Stream for Events<'_, A> {
type Item = Result<A, ClientError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.inner.as_mut().poll_next(cx)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<A> FusedStream for Events<'_, A> {
fn is_terminated(&self) -> bool {
self.inner.is_terminated()
}
}
impl<A> fmt::Debug for Events<'_, A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Events")
.field("terminated", &self.inner.is_terminated())
.finish_non_exhaustive()
}
}
pub async fn call_one<T, I>(
transport: &T,
method: MethodRef,
params: Result<Value, ClientError>,
item: Decoder<I>,
) -> Result<I, ClientError>
where
T: Transport + ?Sized,
{
let qualified = method.qualified();
one_of(MethodStream::call(transport, method, params, item, identity::<I>), qualified).await
}
pub async fn call_one_with_input<'a, T, I>(
transport: &'a T,
method: MethodRef,
params: Result<Value, ClientError>,
input: InputItems<'a>,
item: Decoder<I>,
) -> Result<I, ClientError>
where
T: Transport + ?Sized,
{
let qualified = method.qualified();
one_of(MethodStream::call_with_input(transport, method, params, input, item, identity::<I>), qualified).await
}
async fn one_of<I>(mut items: MethodStream<'_, I>, qualified: String) -> Result<I, ClientError> {
use futures_util::StreamExt;
let contract = |message: &str| ClientError::Decode {
content_type: Some(qualified.clone()),
message: message.to_string(),
};
let first = match items.next().await {
Some(first) => first?,
None => return Err(contract("a one-item method ended without its item")),
};
match items.next().await {
None => Ok(first),
Some(Err(e)) => Err(e),
Some(Ok(_)) => Err(contract("a one-item method sent more than one item")),
}
}
pub(crate) fn plain<I: DeserializeOwned>() -> Decoder<I> {
Content::decode::<I>
}
pub(crate) fn untagged<'a, I>(items: RawItemStream<'a>, item: Decoder<I>) -> MethodStream<'a, I> {
MethodStream::new(items, item, identity::<I>)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_progress_never_deserializes() {
let err = serde_json::from_value::<NoProgress>(serde_json::json!({"message": "x"}))
.unwrap_err();
assert!(err.to_string().contains("declares no progress"), "{err}");
}
#[test]
fn method_streams_are_send_and_unpin() {
fn send_unpin<T: Send + Unpin>() {}
send_unpin::<MethodStream<'static, String, NoProgress, u8>>();
send_unpin::<WithProgress<'static, String, crate::Note>>();
send_unpin::<Events<'static, u8>>();
}
}