Skip to main content

plexus_client/
method_stream.rs

1//! What a many-item method's client call returns: [`MethodStream`].
2//!
3//! A method that yields many items (`-> impl Stream<Item = …>`) is called as
4//! a stream of its items — a plain
5//! `TryStream<Ok = I, Error = ClientError>` — and two per-call opt-ins turn
6//! that same call into something else (RETURNS-1 decisions 6, 11):
7//!
8//! | Call | Yields | Progress frames |
9//! |---|---|---|
10//! | `client.m(..)` | `Result<I, ClientError>` | dropped, undecoded |
11//! | `client.m(..).with_progress()` | `Result<Frame<I, P>, ClientError>`, in arrival order | decoded as `P` |
12//! | `client.m(..).events()` | `Result<{Ns}Event, ClientError>`, `{Ns}Event::M(item)` | dropped |
13//!
14//! `I` is the method's item — a plain `T`, or a `Result<T, E>` decoded from
15//! its `{"ok"}` / `{"err"}` wire form — `P` its progress type ([`NoProgress`]
16//! when it declares none) and `A` the activation's `{Ns}Event` aggregate.
17//!
18//! # Decoding, exhaustively
19//!
20//! | Wire item | Yielded | Stream continues? |
21//! |---|---|---|
22//! | `data` (decodes as `I`) | the item | yes |
23//! | `data` (does not) | `Err(ClientError::Decode)` | **no** |
24//! | `progress` | nothing — unless opted in: `Frame::Progress(p)` | yes |
25//! | `progress` (opted in, does not decode as `P`) | `Err(ClientError::Decode)` | **no** |
26//! | `error` | `Err(ClientError::Remote(RemoteError))` | **no** |
27//! | `request` | *skipped* (the typed client has no answer channel) | yes |
28//! | `done` | nothing | **no** |
29//! | transport failure | `Err(ClientError::Transport)` | **no** |
30//!
31//! A failed call stays an *item* of the stream, so a cut-off stream cannot
32//! pass for a finished one. An `err` item (`Err(e)` of a Result method) is
33//! data, the activation saying no: it is `Ok(Err(e))` here and does not end
34//! the stream — the method decides whether more follows.
35//!
36//! [`NoProgress`] is uninhabited, so `.with_progress()` exists on every
37//! many-item method and still never yields a progress frame where the schema
38//! declares none: such a frame cannot decode, and is a contract break like
39//! any other.
40
41use std::fmt;
42use std::marker::PhantomData;
43use std::pin::Pin;
44use std::task::{Context, Poll};
45
46use futures_core::{FusedStream, Stream};
47use serde::de::{self, DeserializeOwned, Deserializer};
48use serde::{Deserialize, Serialize, Serializer};
49use serde_json::Value;
50
51use crate::envelope::{Content, RawItem};
52use crate::error::ClientError;
53use crate::frame::Frame;
54use crate::lift::{Lift, Root};
55use crate::transport::{InputItems, MethodRef, RawItemStream, Transport};
56
57/// Decodes one data frame's `content` into a method's item `I` — straight
58/// from the wire's text where the transport kept it (PERF.115-36's
59/// [`Content`]), never through a `Value` first.
60///
61/// A plain-`T` method's is `Content::decode::<T>`; a Result method's is
62/// [`wire_result::from_content::<T, E>`](crate::wire_result::from_content),
63/// which reads `{"ok"}` / `{"err"}`. A function pointer, so it is `Send`,
64/// `Sync` and `Copy` whatever `I` is.
65pub type Decoder<I> = fn(Content) -> Result<I, serde_json::Error>;
66
67/// The progress type of a method that reports none. Uninhabited: no value of
68/// it exists, so a stream typed `Frame<I, NoProgress>` can only ever yield
69/// items.
70///
71/// It deserializes from nothing — a progress frame for a method whose schema
72/// declares no progress is a contract break, reported as
73/// [`ClientError::Decode`] under `.with_progress()` (and dropped undecoded
74/// without it, as every progress frame is).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
76pub enum NoProgress {}
77
78impl Serialize for NoProgress {
79    fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
80        match *self {}
81    }
82}
83
84impl<'de> Deserialize<'de> for NoProgress {
85    fn deserialize<D: Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
86        Err(de::Error::custom(
87            "a progress frame for a method that declares no progress",
88        ))
89    }
90}
91
92/// The wire items behind a typed stream, and where they stand.
93enum State<'a> {
94    /// Items still arriving.
95    Live(RawItemStream<'a>),
96    /// The call failed before anything was sent (a parameter that would not
97    /// encode); yielded once, then finished.
98    Failed(ClientError),
99    /// A terminal item was seen (or yielded). The wire stream is dropped the
100    /// moment this is reached, so a transport that cancels on drop (the
101    /// WebSocket one) cancels exactly the calls the client gave up on.
102    Finished,
103}
104
105/// The decoding shared by [`MethodStream`] and [`WithProgress`].
106struct Core<'a, I> {
107    state: State<'a>,
108    item: Decoder<I>,
109}
110
111impl<'a, I> Core<'a, I> {
112    fn new(state: State<'a>, item: Decoder<I>) -> Self {
113        Self { state, item }
114    }
115
116    /// The next frame. `progress` is `None` to drop progress frames
117    /// undecoded, `Some(decoder)` to yield them.
118    fn poll_frame<P>(
119        &mut self,
120        cx: &mut Context<'_>,
121        progress: Option<Decoder<P>>,
122    ) -> Poll<Option<Result<Frame<I, P>, ClientError>>> {
123        loop {
124            let next = match &mut self.state {
125                State::Live(items) => match items.as_mut().poll_next(cx) {
126                    Poll::Pending => return Poll::Pending,
127                    Poll::Ready(next) => next,
128                },
129                State::Failed(_) => {
130                    let State::Failed(e) = std::mem::replace(&mut self.state, State::Finished)
131                    else {
132                        unreachable!("matched Failed above")
133                    };
134                    return Poll::Ready(Some(Err(e)));
135                }
136                State::Finished => return Poll::Ready(None),
137            };
138
139            let (out, terminal) = match next {
140                // Normal completion is the stream ending; a `done` is not an
141                // item. A transport that ends without one has said all it
142                // will say.
143                None | Some(Ok(RawItem::Done)) => {
144                    self.state = State::Finished;
145                    return Poll::Ready(None);
146                }
147                Some(Err(e)) => (Err(ClientError::Transport(e)), true),
148                Some(Ok(RawItem::Error { error, .. })) => (Err(ClientError::Remote(*error)), true),
149                // Bidirectional server→client requests need an answer channel
150                // the typed client does not have. Skip rather than fail: an
151                // activation may interleave them with real data.
152                Some(Ok(RawItem::Request)) => continue,
153                Some(Ok(RawItem::Data { content, content_type })) => match (self.item)(content) {
154                    Ok(item) => (Ok(Frame::Item(item)), false),
155                    Err(e) => (
156                        Err(ClientError::Decode {
157                            content_type: content_type.map(|c| c.to_string()),
158                            message: message_of(&e),
159                        }),
160                        true,
161                    ),
162                },
163                Some(Ok(RawItem::Progress { content, content_type })) => match progress {
164                    None => continue,
165                    Some(decode) => match decode(content) {
166                        Ok(p) => (Ok(Frame::Progress(p)), false),
167                        Err(e) => (
168                            Err(ClientError::Decode {
169                                content_type: content_type.map(|c| c.to_string()),
170                                message: format!("progress: {}", message_of(&e)),
171                            }),
172                            true,
173                        ),
174                    },
175                },
176            };
177            if terminal {
178                self.state = State::Finished;
179            }
180            return Poll::Ready(Some(out));
181        }
182    }
183
184    fn is_terminated(&self) -> bool {
185        matches!(self.state, State::Finished)
186    }
187
188    fn state_name(&self) -> &'static str {
189        match self.state {
190            State::Live(_) => "live",
191            State::Failed(_) => "failed",
192            State::Finished => "finished",
193        }
194    }
195}
196
197fn identity<T>(t: T) -> T {
198    t
199}
200
201/// A decode error as a `Value`'s decode words it: serde_json's message,
202/// without the position a decode from text adds (PERF.115-36).
203fn message_of(e: &serde_json::Error) -> String {
204    let message = e.to_string();
205    if e.line() == 0 {
206        return message;
207    }
208    let at = format!(" at line {} column {}", e.line(), e.column());
209    match message.strip_suffix(&at) {
210        Some(bare) => bare.to_owned(),
211        None => message,
212    }
213}
214
215/// One call of a many-item method: a stream of its items.
216///
217/// `I` is the item, `P` the progress type ([`NoProgress`] when the method
218/// declares none), `A` the activation's `{Ns}Event` aggregate. A generated
219/// client spells all four — `MethodStream<'_, Result<Row, ScanError>,
220/// NoProgress, TicketsEvent>`; the defaults are for the macro-free
221/// [`decode`](crate::decode) path.
222///
223/// It is a plain `Stream<Item = Result<I, ClientError>>` — a `TryStream` —
224/// so `futures`' combinators apply:
225///
226/// ```ignore
227/// use futures::TryStreamExt;
228/// let rows: Vec<Result<Row, ScanError>> = client.scan("a".into()).try_collect().await?;
229/// ```
230///
231/// Progress frames are dropped undecoded unless the caller opts in with
232/// [`with_progress`](Self::with_progress); [`events`](Self::events) turns
233/// the call into the activation's aggregate. See the [module docs](self)
234/// for the decoding table.
235///
236/// `Unpin`, and `Send` wherever the transport's item stream is (everywhere
237/// but wasm32); dropping it mid-stream drops the wire stream, which cancels
238/// the call on a transport that can (the WebSocket one unsubscribes).
239/// How an item becomes its activation's aggregate: the method's variant.
240///
241/// A `fn(I) -> A` is one (`TicketsEvent::List`). The activation macro emits a
242/// zero-sized one per many-item method (RETURNS-46), so the variant and the
243/// lift above it are one inlined step per event — not a call through a
244/// pointer and then the lift, which costs about 10 ns an event.
245pub trait EventOf<I> {
246    /// The activation's aggregate.
247    type Aggregate;
248    /// `item` as its aggregate.
249    fn event(&self, item: I) -> Self::Aggregate;
250}
251
252impl<I, A> EventOf<I> for fn(I) -> A {
253    type Aggregate = A;
254    #[inline]
255    fn event(&self, item: I) -> A {
256        self(item)
257    }
258}
259
260pub struct MethodStream<'a, I, P = NoProgress, A = I, L = Root, W = fn(I) -> A> {
261    core: Core<'a, I>,
262    /// An item as the activation's aggregate: the method's variant.
263    event: W,
264    _aggregate: PhantomData<fn() -> A>,
265    /// RETURNS-46: the aggregate as the client's — [`Root`] for a client
266    /// reached through nothing, a parent's wrapping for one an accessor made.
267    lift: L,
268    _progress: PhantomData<fn() -> P>,
269}
270
271impl<'a, I, P, A> MethodStream<'a, I, P, A> {
272    /// Type a transport's wire items as one method's stream: `item` decodes
273    /// each data frame's `content`, `event` wraps an item in the
274    /// aggregate (`TicketsEvent::List`) for [`events`](Self::events).
275    pub fn new(items: RawItemStream<'a>, item: Decoder<I>, event: fn(I) -> A) -> Self {
276        Self::from_core(Core::new(State::Live(items), item), event)
277    }
278
279    /// Call `method` on `transport` with `params` and type the answer — what
280    /// a generated client's many-item method is. When `params` is an `Err`
281    /// (an argument that would not encode) nothing is sent and the stream
282    /// yields that error once.
283    pub fn call<T>(
284        transport: &'a T,
285        method: MethodRef,
286        params: Result<Value, ClientError>,
287        item: Decoder<I>,
288        event: fn(I) -> A,
289    ) -> Self
290    where
291        T: Transport + ?Sized,
292    {
293        let state = match params {
294            // PERF.115-36: the items with their content still the wire's
295            // text, decoded straight into the item.
296            Ok(params) => State::Live(transport.call_raw(method, params)),
297            Err(e) => State::Failed(e),
298        };
299        Self::from_core(Core::new(state, item), event)
300    }
301
302    /// BIDIR-6: [`call`](Self::call), for a method with an input half:
303    /// `input` is sent under the callee's credit as the stream is read.
304    pub fn call_with_input<T>(
305        transport: &'a T,
306        method: MethodRef,
307        params: Result<Value, ClientError>,
308        input: InputItems<'a>,
309        item: Decoder<I>,
310        event: fn(I) -> A,
311    ) -> Self
312    where
313        T: Transport + ?Sized,
314    {
315        let state = match params {
316            Ok(params) => State::Live(transport.call_raw_with_input(method, params, input)),
317            Err(e) => State::Failed(e),
318        };
319        Self::from_core(Core::new(state, item), event)
320    }
321
322    fn from_core(core: Core<'a, I>, event: fn(I) -> A) -> Self {
323        Self {
324            core,
325            event,
326            _aggregate: PhantomData,
327            lift: Root,
328            _progress: PhantomData,
329        }
330    }
331
332    /// [`call`](Self::call) with the method's variant as an [`EventOf`] —
333    /// what a generated client passes (RETURNS-46): a zero-sized type, so
334    /// the variant inlines into [`events`](Self::events).
335    pub fn call_as<T, W>(
336        transport: &'a T,
337        method: MethodRef,
338        params: Result<Value, ClientError>,
339        item: Decoder<I>,
340        event: W,
341    ) -> MethodStream<'a, I, P, A, Root, W>
342    where
343        T: Transport + ?Sized,
344        W: EventOf<I, Aggregate = A>,
345    {
346        let state = match params {
347            Ok(params) => State::Live(transport.call_raw(method, params)),
348            Err(e) => State::Failed(e),
349        };
350        MethodStream {
351            core: Core::new(state, item),
352            event,
353            _aggregate: PhantomData,
354            lift: Root,
355            _progress: PhantomData,
356        }
357    }
358}
359
360impl<'a, I, P, A> MethodStream<'a, I, P, A> {
361    /// [`call_as`](Self::call_as) for a method with an input half
362    /// (BIDIR-6, RETURNS-46): `input` is sent under the callee's credit as
363    /// the stream is read.
364    pub fn call_as_with_input<T, W>(
365        transport: &'a T,
366        method: MethodRef,
367        params: Result<Value, ClientError>,
368        input: InputItems<'a>,
369        item: Decoder<I>,
370        event: W,
371    ) -> MethodStream<'a, I, P, A, Root, W>
372    where
373        T: Transport + ?Sized,
374        W: EventOf<I, Aggregate = A>,
375    {
376        let state = match params {
377            Ok(params) => State::Live(transport.call_raw_with_input(method, params, input)),
378            Err(e) => State::Failed(e),
379        };
380        MethodStream {
381            core: Core::new(state, item),
382            event,
383            _aggregate: PhantomData,
384            lift: Root,
385            _progress: PhantomData,
386        }
387    }
388}
389
390impl<'a, I, P, A, L, W> MethodStream<'a, I, P, A, L, W> {
391    /// RETURNS-46: the same call, its [`events`](Self::events) lifted by
392    /// `lift` into an enclosing aggregate — what a client reached through a
393    /// parent's accessor does with every many-item call, so the call's
394    /// events are the parent's (`TreeEvent::Branch(BranchEvent::Grow(..))`).
395    pub fn lifted<L2: Lift<A>>(self, lift: L2) -> MethodStream<'a, I, P, A, L2, W> {
396        MethodStream {
397            core: self.core,
398            event: self.event,
399            _aggregate: PhantomData,
400            lift,
401            _progress: PhantomData,
402        }
403    }
404
405    /// Opt in to progress: the same call, yielding each item as
406    /// [`Frame::Item`] and each progress frame, decoded as `P`, as
407    /// [`Frame::Progress`] — in arrival order.
408    ///
409    /// For a method that declares no progress `P` is [`NoProgress`], and the
410    /// stream yields only items.
411    pub fn with_progress(self) -> WithProgress<'a, I, P>
412    where
413        P: DeserializeOwned,
414    {
415        WithProgress {
416            core: self.core,
417            _progress: PhantomData,
418        }
419    }
420
421    /// The same call as the activation's aggregate: each item `i` becomes
422    /// `{Ns}Event::M(i)`; progress is dropped (the aggregate carries items
423    /// only). Every method's `events()` has the same type, so several calls
424    /// merge into one listener with ordinary stream plumbing:
425    ///
426    /// ```ignore
427    /// let mut all = futures::stream::select_all([
428    ///     client.watch(None).events(),
429    ///     client.list(None, None).events(),
430    /// ]);
431    /// while let Some(ev) = all.next().await { state.reduce(ev?) }   // ev: TicketsEvent
432    /// ```
433    pub fn events(self) -> Events<'a, L::Out>
434    where
435        L: Lift<A>,
436        W: EventOf<I, Aggregate = A> + Clone + MaybeSendSync + 'a,
437        I: 'a,
438        P: 'a,
439        A: 'a,
440        L::Out: 'a,
441    {
442        let event = self.event.clone();
443        let lift = self.lift.clone();
444        Events {
445            inner: Box::pin(futures_util::StreamExt::map(self, move |r| r.map(|i| lift.lift(event.event(i))))),
446        }
447    }
448}
449
450/// `Send + Sync` off wasm32, nothing on it — what an event constructor
451/// moved into a boxed [`Events`] must be.
452#[cfg(not(target_arch = "wasm32"))]
453pub trait MaybeSendSync: Send + Sync {}
454#[cfg(not(target_arch = "wasm32"))]
455impl<T: Send + Sync> MaybeSendSync for T {}
456/// See the non-wasm32 variant.
457#[cfg(target_arch = "wasm32")]
458pub trait MaybeSendSync {}
459#[cfg(target_arch = "wasm32")]
460impl<T> MaybeSendSync for T {}
461
462// No field is pinned: the wire stream is boxed, the lift a plain value.
463impl<I, P, A, L, W> Unpin for MethodStream<'_, I, P, A, L, W> {}
464
465impl<I, P, A, L, W> Stream for MethodStream<'_, I, P, A, L, W> {
466    type Item = Result<I, ClientError>;
467
468    #[inline]
469    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
470        self.get_mut()
471            .core
472            .poll_frame::<NoProgress>(cx, None)
473            .map(|next| {
474                next.map(|frame| {
475                    frame.map(|frame| match frame {
476                        Frame::Item(item) => item,
477                        Frame::Progress(never) => match never {},
478                    })
479                })
480            })
481    }
482}
483
484impl<I, P, A, L, W> FusedStream for MethodStream<'_, I, P, A, L, W> {
485    fn is_terminated(&self) -> bool {
486        self.core.is_terminated()
487    }
488}
489
490impl<I, P, A, L, W> fmt::Debug for MethodStream<'_, I, P, A, L, W> {
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        f.debug_struct("MethodStream")
493            .field("state", &self.core.state_name())
494            .finish_non_exhaustive()
495    }
496}
497
498/// A [`MethodStream`] whose caller opted in to progress
499/// ([`MethodStream::with_progress`]): `Result<Frame<I, P>, ClientError>`,
500/// in arrival order.
501pub struct WithProgress<'a, I, P> {
502    core: Core<'a, I>,
503    _progress: PhantomData<fn() -> P>,
504}
505
506impl<I, P: DeserializeOwned> Stream for WithProgress<'_, I, P> {
507    type Item = Result<Frame<I, P>, ClientError>;
508
509    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
510        self.get_mut()
511            .core
512            .poll_frame(cx, Some(Content::decode::<P> as Decoder<P>))
513    }
514}
515
516impl<I, P: DeserializeOwned> FusedStream for WithProgress<'_, I, P> {
517    fn is_terminated(&self) -> bool {
518        self.core.is_terminated()
519    }
520}
521
522impl<I, P> fmt::Debug for WithProgress<'_, I, P> {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        f.debug_struct("WithProgress")
525            .field("state", &self.core.state_name())
526            .finish_non_exhaustive()
527    }
528}
529
530#[cfg(not(target_arch = "wasm32"))]
531type BoxedEvents<'a, A> = Pin<Box<dyn FusedStream<Item = Result<A, ClientError>> + Send + 'a>>;
532
533#[cfg(target_arch = "wasm32")]
534type BoxedEvents<'a, A> = Pin<Box<dyn FusedStream<Item = Result<A, ClientError>> + 'a>>;
535
536/// A call as the activation's aggregate ([`MethodStream::events`]):
537/// `Result<A, ClientError>`, where `A` is `{Ns}Event`.
538///
539/// Its type names only the aggregate, not the method, so every method's
540/// `events()` is the same type and several calls merge with
541/// `futures::stream::select_all` (or `select`). Mirrors the transport's
542/// `Send` bound: `Send` off wasm32, not on it.
543pub struct Events<'a, A> {
544    inner: BoxedEvents<'a, A>,
545}
546
547impl<A> Stream for Events<'_, A> {
548    type Item = Result<A, ClientError>;
549
550    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
551        self.inner.as_mut().poll_next(cx)
552    }
553
554    fn size_hint(&self) -> (usize, Option<usize>) {
555        self.inner.size_hint()
556    }
557}
558
559impl<A> FusedStream for Events<'_, A> {
560    fn is_terminated(&self) -> bool {
561        self.inner.is_terminated()
562    }
563}
564
565impl<A> fmt::Debug for Events<'_, A> {
566    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567        f.debug_struct("Events")
568            .field("terminated", &self.inner.is_terminated())
569            .finish_non_exhaustive()
570    }
571}
572
573/// Call a one-item method (`-> T`, `-> Result<T, E>`) and return its item —
574/// what a generated client's one-item `async fn` is.
575///
576/// Reads the call to its terminal frame: one data item, then `done`. So a
577/// transport that cancels a dropped call (the WebSocket one) never cancels a
578/// call that finished, and a server that breaks the contract is caught:
579///
580/// | Wire | Result |
581/// |---|---|
582/// | one `data` (decodes), `done` | `Ok(item)` |
583/// | `error` (before or after the item) | `Err(ClientError::Remote)` |
584/// | `done` with no item, or a second item | `Err(ClientError::Decode)` naming the method |
585/// | transport failure | `Err(ClientError::Transport)` |
586///
587/// Progress frames are dropped (a one-item method never reports progress:
588/// RETURNS-1 decision 10); `request` frames are skipped. When `params` is an
589/// `Err` nothing is sent and that is the result.
590pub async fn call_one<T, I>(
591    transport: &T,
592    method: MethodRef,
593    params: Result<Value, ClientError>,
594    item: Decoder<I>,
595) -> Result<I, ClientError>
596where
597    T: Transport + ?Sized,
598{
599    let qualified = method.qualified();
600    one_of(MethodStream::call(transport, method, params, item, identity::<I>), qualified).await
601}
602
603/// BIDIR-6: [`call_one`], for a method with an input half: `input` is sent
604/// under the callee's credit while the call is read to its end.
605pub async fn call_one_with_input<'a, T, I>(
606    transport: &'a T,
607    method: MethodRef,
608    params: Result<Value, ClientError>,
609    input: InputItems<'a>,
610    item: Decoder<I>,
611) -> Result<I, ClientError>
612where
613    T: Transport + ?Sized,
614{
615    let qualified = method.qualified();
616    one_of(MethodStream::call_with_input(transport, method, params, input, item, identity::<I>), qualified).await
617}
618
619/// A one-item call's item, read to its terminal frame. `qualified` names
620/// the method in a contract break (RETURNS-46: a `MethodRef` is `Clone`, not
621/// `Copy`, so the name is taken before the call has it).
622async fn one_of<I>(mut items: MethodStream<'_, I>, qualified: String) -> Result<I, ClientError> {
623    use futures_util::StreamExt;
624
625    let contract = |message: &str| ClientError::Decode {
626        content_type: Some(qualified.clone()),
627        message: message.to_string(),
628    };
629    let first = match items.next().await {
630        Some(first) => first?,
631        None => return Err(contract("a one-item method ended without its item")),
632    };
633    match items.next().await {
634        None => Ok(first),
635        Some(Err(e)) => Err(e),
636        Some(Ok(_)) => Err(contract("a one-item method sent more than one item")),
637    }
638}
639
640/// The `Decoder` for a plain item, as a function pointer.
641pub(crate) fn plain<I: DeserializeOwned>() -> Decoder<I> {
642    Content::decode::<I>
643}
644
645/// `MethodStream::new` with the identity aggregate, for the macro-free path.
646pub(crate) fn untagged<'a, I>(items: RawItemStream<'a>, item: Decoder<I>) -> MethodStream<'a, I> {
647    MethodStream::new(items, item, identity::<I>)
648}
649
650#[cfg(test)]
651mod tests {
652    use super::*;
653
654    #[test]
655    fn no_progress_never_deserializes() {
656        let err = serde_json::from_value::<NoProgress>(serde_json::json!({"message": "x"}))
657            .unwrap_err();
658        assert!(err.to_string().contains("declares no progress"), "{err}");
659    }
660
661    #[test]
662    fn method_streams_are_send_and_unpin() {
663        fn send_unpin<T: Send + Unpin>() {}
664        send_unpin::<MethodStream<'static, String, NoProgress, u8>>();
665        send_unpin::<WithProgress<'static, String, crate::Note>>();
666        send_unpin::<Events<'static, u8>>();
667    }
668}