plexus-client 0.8.0

wasm-safe client runtime for Plexus RPC: the wire envelope, the Transport trait, and typed event decoding
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
//! What a many-item method's client call returns: [`MethodStream`].
//!
//! A method that yields many items (`-> impl Stream<Item = …>`) is called as
//! a stream of its items — a plain
//! `TryStream<Ok = I, Error = ClientError>` — and two per-call opt-ins turn
//! that same call into something else (RETURNS-1 decisions 6, 11):
//!
//! | Call | Yields | Progress frames |
//! |---|---|---|
//! | `client.m(..)` | `Result<I, ClientError>` | dropped, undecoded |
//! | `client.m(..).with_progress()` | `Result<Frame<I, P>, ClientError>`, in arrival order | decoded as `P` |
//! | `client.m(..).events()` | `Result<{Ns}Event, ClientError>`, `{Ns}Event::M(item)` | dropped |
//!
//! `I` is the method's item — a plain `T`, or a `Result<T, E>` decoded from
//! its `{"ok"}` / `{"err"}` wire form — `P` its progress type ([`NoProgress`]
//! when it declares none) and `A` the activation's `{Ns}Event` aggregate.
//!
//! # Decoding, exhaustively
//!
//! | Wire item | Yielded | Stream continues? |
//! |---|---|---|
//! | `data` (decodes as `I`) | the item | yes |
//! | `data` (does not) | `Err(ClientError::Decode)` | **no** |
//! | `progress` | nothing — unless opted in: `Frame::Progress(p)` | yes |
//! | `progress` (opted in, does not decode as `P`) | `Err(ClientError::Decode)` | **no** |
//! | `error` | `Err(ClientError::Remote(RemoteError))` | **no** |
//! | `request` | *skipped* (the typed client has no answer channel) | yes |
//! | `done` | nothing | **no** |
//! | transport failure | `Err(ClientError::Transport)` | **no** |
//!
//! A failed call stays an *item* of the stream, so a cut-off stream cannot
//! pass for a finished one. An `err` item (`Err(e)` of a Result method) is
//! data, the activation saying no: it is `Ok(Err(e))` here and does not end
//! the stream — the method decides whether more follows.
//!
//! [`NoProgress`] is uninhabited, so `.with_progress()` exists on every
//! many-item method and still never yields a progress frame where the schema
//! declares none: such a frame cannot decode, and is a contract break like
//! any other.

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};

/// Decodes one data frame's `content` into a method's item `I` — straight
/// from the wire's text where the transport kept it (PERF.115-36's
/// [`Content`]), never through a `Value` first.
///
/// A plain-`T` method's is `Content::decode::<T>`; a Result method's is
/// [`wire_result::from_content::<T, E>`](crate::wire_result::from_content),
/// which reads `{"ok"}` / `{"err"}`. A function pointer, so it is `Send`,
/// `Sync` and `Copy` whatever `I` is.
pub type Decoder<I> = fn(Content) -> Result<I, serde_json::Error>;

/// The progress type of a method that reports none. Uninhabited: no value of
/// it exists, so a stream typed `Frame<I, NoProgress>` can only ever yield
/// items.
///
/// It deserializes from nothing — a progress frame for a method whose schema
/// declares no progress is a contract break, reported as
/// [`ClientError::Decode`] under `.with_progress()` (and dropped undecoded
/// without it, as every progress frame is).
#[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",
        ))
    }
}

/// The wire items behind a typed stream, and where they stand.
enum State<'a> {
    /// Items still arriving.
    Live(RawItemStream<'a>),
    /// The call failed before anything was sent (a parameter that would not
    /// encode); yielded once, then finished.
    Failed(ClientError),
    /// A terminal item was seen (or yielded). The wire stream is dropped the
    /// moment this is reached, so a transport that cancels on drop (the
    /// WebSocket one) cancels exactly the calls the client gave up on.
    Finished,
}

/// The decoding shared by [`MethodStream`] and [`WithProgress`].
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 }
    }

    /// The next frame. `progress` is `None` to drop progress frames
    /// undecoded, `Some(decoder)` to yield them.
    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 {
                // Normal completion is the stream ending; a `done` is not an
                // item. A transport that ends without one has said all it
                // will say.
                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),
                // Bidirectional server→client requests need an answer channel
                // the typed client does not have. Skip rather than fail: an
                // activation may interleave them with real data.
                Some(Ok(RawItem::Request)) => continue,
                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
}

/// A decode error as a `Value`'s decode words it: serde_json's message,
/// without the position a decode from text adds (PERF.115-36).
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,
    }
}

/// One call of a many-item method: a stream of its items.
///
/// `I` is the item, `P` the progress type ([`NoProgress`] when the method
/// declares none), `A` the activation's `{Ns}Event` aggregate. A generated
/// client spells all four — `MethodStream<'_, Result<Row, ScanError>,
/// NoProgress, TicketsEvent>`; the defaults are for the macro-free
/// [`decode`](crate::decode) path.
///
/// It is a plain `Stream<Item = Result<I, ClientError>>` — a `TryStream` —
/// so `futures`' combinators apply:
///
/// ```ignore
/// use futures::TryStreamExt;
/// let rows: Vec<Result<Row, ScanError>> = client.scan("a".into()).try_collect().await?;
/// ```
///
/// Progress frames are dropped undecoded unless the caller opts in with
/// [`with_progress`](Self::with_progress); [`events`](Self::events) turns
/// the call into the activation's aggregate. See the [module docs](self)
/// for the decoding table.
///
/// `Unpin`, and `Send` wherever the transport's item stream is (everywhere
/// but wasm32); dropping it mid-stream drops the wire stream, which cancels
/// the call on a transport that can (the WebSocket one unsubscribes).
/// How an item becomes its activation's aggregate: the method's variant.
///
/// A `fn(I) -> A` is one (`TicketsEvent::List`). The activation macro emits a
/// zero-sized one per many-item method (RETURNS-46), so the variant and the
/// lift above it are one inlined step per event — not a call through a
/// pointer and then the lift, which costs about 10 ns an event.
pub trait EventOf<I> {
    /// The activation's aggregate.
    type Aggregate;
    /// `item` as its 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>,
    /// An item as the activation's aggregate: the method's variant.
    event: W,
    _aggregate: PhantomData<fn() -> A>,
    /// RETURNS-46: the aggregate as the client's — [`Root`] for a client
    /// reached through nothing, a parent's wrapping for one an accessor made.
    lift: L,
    _progress: PhantomData<fn() -> P>,
}

impl<'a, I, P, A> MethodStream<'a, I, P, A> {
    /// Type a transport's wire items as one method's stream: `item` decodes
    /// each data frame's `content`, `event` wraps an item in the
    /// aggregate (`TicketsEvent::List`) for [`events`](Self::events).
    pub fn new(items: RawItemStream<'a>, item: Decoder<I>, event: fn(I) -> A) -> Self {
        Self::from_core(Core::new(State::Live(items), item), event)
    }

    /// Call `method` on `transport` with `params` and type the answer — what
    /// a generated client's many-item method is. When `params` is an `Err`
    /// (an argument that would not encode) nothing is sent and the stream
    /// yields that error once.
    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 {
            // PERF.115-36: the items with their content still the wire's
            // text, decoded straight into the item.
            Ok(params) => State::Live(transport.call_raw(method, params)),
            Err(e) => State::Failed(e),
        };
        Self::from_core(Core::new(state, item), event)
    }

    /// BIDIR-6: [`call`](Self::call), for a method with an input half:
    /// `input` is sent under the callee's credit as the stream is read.
    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,
        }
    }

    /// [`call`](Self::call) with the method's variant as an [`EventOf`] —
    /// what a generated client passes (RETURNS-46): a zero-sized type, so
    /// the variant inlines into [`events`](Self::events).
    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> {
    /// [`call_as`](Self::call_as) for a method with an input half
    /// (BIDIR-6, RETURNS-46): `input` is sent under the callee's credit as
    /// the stream is read.
    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> {
    /// RETURNS-46: the same call, its [`events`](Self::events) lifted by
    /// `lift` into an enclosing aggregate — what a client reached through a
    /// parent's accessor does with every many-item call, so the call's
    /// events are the parent's (`TreeEvent::Branch(BranchEvent::Grow(..))`).
    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,
        }
    }

    /// Opt in to progress: the same call, yielding each item as
    /// [`Frame::Item`] and each progress frame, decoded as `P`, as
    /// [`Frame::Progress`] — in arrival order.
    ///
    /// For a method that declares no progress `P` is [`NoProgress`], and the
    /// stream yields only items.
    pub fn with_progress(self) -> WithProgress<'a, I, P>
    where
        P: DeserializeOwned,
    {
        WithProgress {
            core: self.core,
            _progress: PhantomData,
        }
    }

    /// The same call as the activation's aggregate: each item `i` becomes
    /// `{Ns}Event::M(i)`; progress is dropped (the aggregate carries items
    /// only). Every method's `events()` has the same type, so several calls
    /// merge into one listener with ordinary stream plumbing:
    ///
    /// ```ignore
    /// let mut all = futures::stream::select_all([
    ///     client.watch(None).events(),
    ///     client.list(None, None).events(),
    /// ]);
    /// while let Some(ev) = all.next().await { state.reduce(ev?) }   // ev: TicketsEvent
    /// ```
    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))))),
        }
    }
}

/// `Send + Sync` off wasm32, nothing on it — what an event constructor
/// moved into a boxed [`Events`] must be.
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSendSync: Send + Sync {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + Sync> MaybeSendSync for T {}
/// See the non-wasm32 variant.
#[cfg(target_arch = "wasm32")]
pub trait MaybeSendSync {}
#[cfg(target_arch = "wasm32")]
impl<T> MaybeSendSync for T {}

// No field is pinned: the wire stream is boxed, the lift a plain value.
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()
    }
}

/// A [`MethodStream`] whose caller opted in to progress
/// ([`MethodStream::with_progress`]): `Result<Frame<I, P>, ClientError>`,
/// in arrival order.
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>>;

/// A call as the activation's aggregate ([`MethodStream::events`]):
/// `Result<A, ClientError>`, where `A` is `{Ns}Event`.
///
/// Its type names only the aggregate, not the method, so every method's
/// `events()` is the same type and several calls merge with
/// `futures::stream::select_all` (or `select`). Mirrors the transport's
/// `Send` bound: `Send` off wasm32, not on it.
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()
    }
}

/// Call a one-item method (`-> T`, `-> Result<T, E>`) and return its item —
/// what a generated client's one-item `async fn` is.
///
/// Reads the call to its terminal frame: one data item, then `done`. So a
/// transport that cancels a dropped call (the WebSocket one) never cancels a
/// call that finished, and a server that breaks the contract is caught:
///
/// | Wire | Result |
/// |---|---|
/// | one `data` (decodes), `done` | `Ok(item)` |
/// | `error` (before or after the item) | `Err(ClientError::Remote)` |
/// | `done` with no item, or a second item | `Err(ClientError::Decode)` naming the method |
/// | transport failure | `Err(ClientError::Transport)` |
///
/// Progress frames are dropped (a one-item method never reports progress:
/// RETURNS-1 decision 10); `request` frames are skipped. When `params` is an
/// `Err` nothing is sent and that is the result.
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
}

/// BIDIR-6: [`call_one`], for a method with an input half: `input` is sent
/// under the callee's credit while the call is read to its end.
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
}

/// A one-item call's item, read to its terminal frame. `qualified` names
/// the method in a contract break (RETURNS-46: a `MethodRef` is `Clone`, not
/// `Copy`, so the name is taken before the call has it).
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")),
    }
}

/// The `Decoder` for a plain item, as a function pointer.
pub(crate) fn plain<I: DeserializeOwned>() -> Decoder<I> {
    Content::decode::<I>
}

/// `MethodStream::new` with the identity aggregate, for the macro-free path.
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>>();
    }
}