plexus-core 0.11.0

Core infrastructure for Plexus RPC: Activation trait, DynamicHub, schemas
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! Streaming helpers for the caller-wraps architecture
//!
//! These functions are used by the DynamicHub routing layer to wrap activation
//! responses with metadata. Activations return typed domain events, and
//! the caller uses these helpers to create PlexusStreamItems.

use futures::stream::{self, Stream, StreamExt};
use plexus_client::{Progress, RemoteError};
use serde::{Serialize, Serializer};
use std::pin::Pin;
use std::sync::Arc;

use super::context::PlexusContext;
use super::credential_envelope::{
    assemble_envelope_content, serialize_with_credential_capture, CookieProjector,
};
use super::types::{PlexusStreamItem, StreamMetadata};

/// Type alias for boxed stream of PlexusStreamItem
pub type PlexusStream = Pin<Box<dyn Stream<Item = PlexusStreamItem> + Send>>;

/// Wrap a typed stream into PlexusStream with automatic Done event
///
/// This is the core helper for the caller-wraps architecture.
/// Activations return typed domain events (e.g., HealthEvent),
/// and the caller wraps them with metadata. A Done event is
/// automatically appended when the stream completes.
///
/// # Dispatch-time credential interception (AUTHZ-CRED-CORE-2)
///
/// For every emitted item, this function routes the serialization through
/// the dispatch-time credential capture machinery: a fresh sidecar is
/// installed (per the RAII guard documented in
/// `plexus_auth_core::DispatchCaptureGuard`), serialization runs (and
/// each `Credential<T>` field emits its sentinel inline while the inner
/// value is captured into the sidecar), and the resulting `(payload,
/// captured)` pair is assembled into a wire envelope with an optional
/// `_credentials` field. Payloads with zero `Credential<T>` fields are
/// wire-format-identical to today (additive only).
///
/// See `crate::plexus::credential_envelope` for the envelope assembly
/// rules and `plans/AUTHZ/AUTHZ-CRED-CORE-2.md` for the contract.
///
/// # Example
///
/// ```ignore
/// let stream = health.check();  // Returns Stream<Item = HealthEvent>
/// let wrapped = wrap_stream(stream, "health.status", vec!["health".into()]);
/// // Stream will emit: Data, Data, ..., Done
/// ```
pub fn wrap_stream<T: Serialize + Send + 'static>(
    stream: impl Stream<Item = T> + Send + 'static,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream {
    let plexus_hash = PlexusContext::hash();
    let metadata = Arc::new(StreamMetadata::new(provenance.clone(), plexus_hash.clone()));
    let done = StreamMetadata::new(provenance, plexus_hash);
    Box::pin(Wrapped::<_, DataForm> {
        inner: stream,
        metadata,
        content_type,
        done: Some(done),
        ended: false,
        form: std::marker::PhantomData,
    })
}

// ============================================================================
// RETURNS-8: one wrapper per signature form
// ============================================================================
//
// `#[plexus_macros::method]` reads a method's return type and calls the one
// wrapper that matches it (RETURNS-1 decisions 2, 3, 4, 10):
//
// | signature | wrapper | frames per item |
// |---|---|---|
// | `-> T` | [`wrap_one`] | data `T`, then done |
// | `-> Result<T, E>` | [`wrap_one_result`] | data `{"ok": t}` / `{"err": e}`, then done |
// | `-> impl Stream<Item = T>` | [`wrap_stream`] | data `T` … done |
// | `-> impl Stream<Item = Result<T, E>>` | [`wrap_result_stream`] | data `{ok}` / `{err}` … done |
// | `-> impl Stream<Item = Progress<T, P>>` | [`wrap_progress_stream`] | `Update(p)` → progress `P`; `Item(t)` → data `T` |
// | `-> impl Stream<Item = Result<Progress<T, P>, E>>` | [`wrap_result_progress_stream`] | `Ok(Update(p))` → progress; `Ok(Item(t))` → data `{ok}`; `Err(e)` → data `{err}` |
//
// An `Err` item is data: it does not end the stream — the method ends it by
// returning. Every wrapper appends exactly one `done`.

/// One frame of a method's output before metadata: an item (a data frame) or
/// a progress update (a progress frame).
enum Out<D, P> {
    Data(D),
    Progress(P),
}

/// A Result item as the wire carries it: `Ok(t)` → `{"ok": t}`, `Err(e)` →
/// `{"err": e}` (`plexus_client::wire_result`).
struct WireResult<T, E>(Result<T, E>);

impl<T: Serialize, E: Serialize> Serialize for WireResult<T, E> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        plexus_client::wire_result::serialize(&self.0, serializer)
    }
}

/// `-> T`: one data frame carrying `item`, then `done`.
pub fn wrap_one<T: Serialize + Send + 'static>(
    item: T,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream {
    wrap_frames(
        stream::once(futures::future::ready(Out::<T, ()>::Data(item))),
        content_type,
        provenance,
    )
}

/// `-> Result<T, E>`: one data frame, `{"ok": t}` or `{"err": e}`, then `done`.
pub fn wrap_one_result<T, E>(
    item: Result<T, E>,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream
where
    T: Serialize + Send + 'static,
    E: Serialize + Send + 'static,
{
    wrap_frames(
        stream::once(futures::future::ready(Out::<_, ()>::Data(WireResult(item)))),
        content_type,
        provenance,
    )
}

/// `-> impl Stream<Item = Result<T, E>>`: one data frame per item, `{"ok": t}`
/// or `{"err": e}`; an `Err` does not end the stream. Then `done`.
pub fn wrap_result_stream<T, E>(
    stream: impl Stream<Item = Result<T, E>> + Send + 'static,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream
where
    T: Serialize + Send + 'static,
    E: Serialize + Send + 'static,
{
    wrap_frames(
        stream.map(|r| Out::<_, ()>::Data(WireResult(r))),
        content_type,
        provenance,
    )
}

/// `-> impl Stream<Item = Progress<T, P>>`: `Update(p)` → a progress frame
/// carrying `p`; `Item(t)` → a data frame carrying `t`. Then `done`.
pub fn wrap_progress_stream<T, P>(
    stream: impl Stream<Item = Progress<T, P>> + Send + 'static,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream
where
    T: Serialize + Send + 'static,
    P: Serialize + Send + 'static,
{
    wrap_frames(
        stream.map(|step| match step {
            Progress::Update(p) => Out::Progress(p),
            Progress::Item(t) => Out::Data(t),
        }),
        content_type,
        provenance,
    )
}

/// `-> impl Stream<Item = Result<Progress<T, P>, E>>`: `Ok(Update(p))` → a
/// progress frame; `Ok(Item(t))` → a data frame `{"ok": t}`; `Err(e)` → a data
/// frame `{"err": e}`. Then `done`.
pub fn wrap_result_progress_stream<T, P, E>(
    stream: impl Stream<Item = Result<Progress<T, P>, E>> + Send + 'static,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream
where
    T: Serialize + Send + 'static,
    P: Serialize + Send + 'static,
    E: Serialize + Send + 'static,
{
    wrap_frames(
        stream.map(|r| match r {
            Ok(Progress::Update(p)) => Out::Progress(p),
            Ok(Progress::Item(t)) => Out::Data(WireResult(Ok(t))),
            Err(e) => Out::Data(WireResult(Err(e))),
        }),
        content_type,
        provenance,
    )
}

/// The one place frames get their metadata: every data item goes through the
/// credential capture `wrap_stream` has always applied, every progress value
/// is serialized as-is, and exactly one `done` follows the last item.
fn wrap_frames<D, P>(
    stream: impl Stream<Item = Out<D, P>> + Send + 'static,
    content_type: &'static str,
    provenance: Vec<String>,
) -> PlexusStream
where
    D: Serialize + Send + 'static,
    P: Serialize + Send + 'static,
{
    let plexus_hash = PlexusContext::hash();
    let metadata = Arc::new(StreamMetadata::new(provenance.clone(), plexus_hash.clone()));
    let done = StreamMetadata::new(provenance, plexus_hash);
    Box::pin(Wrapped::<_, OutForm> {
        inner: stream,
        metadata,
        content_type,
        done: Some(done),
        ended: false,
        form: std::marker::PhantomData,
    })
}

pin_project_lite::pin_project! {
    /// Every wrapper's stream. PERF-7: each event is a `Data` item whose
    /// metadata is the stream's (shared, not cloned), whose content type is
    /// the method's, and whose content is the event encoded once — straight
    /// into the WebSocket pipe's buffer when the pipe polls this stream
    /// ([`super::wire::pipe`]), as a `Value` anywhere else. RETURNS-8: `K`
    /// is the signature form's [`Form`] — what one item of the method's
    /// stream becomes (a data frame, or a progress frame).
    struct Wrapped<S, K> {
        #[pin]
        inner: S,
        metadata: Arc<StreamMetadata>,
        content_type: &'static str,
        done: Option<StreamMetadata>,
        ended: bool,
        form: std::marker::PhantomData<fn() -> K>,
    }
}

/// RETURNS-8: what one item of a wrapped stream becomes.
trait Form<I> {
    fn frame(item: I, metadata: &Arc<StreamMetadata>, content_type: &'static str) -> PlexusStreamItem;
}

/// `wrap_stream`'s form: every item is data.
struct DataForm;

impl<T: Serialize> Form<T> for DataForm {
    fn frame(event: T, metadata: &Arc<StreamMetadata>, content_type: &'static str) -> PlexusStreamItem {
        PlexusStreamItem::Data {
            metadata: metadata.clone(),
            content_type: std::borrow::Cow::Borrowed(content_type),
            content: content_of(&event),
        }
    }
}

/// The other forms': an [`Out`] — data, or a progress value (RETURNS-6's
/// progress frame, the method's `P` serialized as-is: progress reports carry
/// no credentials).
struct OutForm;

impl<D: Serialize, P: Serialize> Form<Out<D, P>> for OutForm {
    fn frame(out: Out<D, P>, metadata: &Arc<StreamMetadata>, content_type: &'static str) -> PlexusStreamItem {
        match out {
            Out::Data(item) => DataForm::frame(item, metadata, content_type),
            Out::Progress(p) => PlexusStreamItem::progress(
                (**metadata).clone(),
                content_type.to_string(),
                serde_json::to_value(&p).unwrap_or(serde_json::Value::Null),
            ),
        }
    }
}

impl<S, K> Stream for Wrapped<S, K>
where
    S: Stream,
    K: Form<S::Item>,
{
    type Item = PlexusStreamItem;

    fn poll_next(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<PlexusStreamItem>> {
        use std::task::Poll;
        let this = self.project();
        if !*this.ended {
            // A stream the method polls inside its own (a call it routes and
            // reads in process) is not the pipe's: one level deeper.
            match super::wire::nested(|| this.inner.poll_next(cx)) {
                Poll::Ready(Some(event)) => return Poll::Ready(Some(K::frame(event, this.metadata, this.content_type))),
                Poll::Ready(None) => *this.ended = true,
                Poll::Pending => return Poll::Pending,
            }
        }
        Poll::Ready(this.done.take().map(|metadata| PlexusStreamItem::Done { metadata }))
    }
}

/// An event's content: encoded once into the pipe's buffer when the pipe
/// polls this stream (PERF-7), else — and for an event carrying a
/// credential, whose envelope is assembled as before — a `Value`.
///
/// # Dispatch-time credential interception (AUTHZ-CRED-CORE-2)
///
/// Either way the serialization runs under the credential capture: a
/// `Credential<T>` writes its sentinel inline and its value is captured.
/// An event that captured none is today's payload exactly (encoded, the
/// same JSON); one that captured any takes the `Value` path, where
/// [`assemble_envelope_content`] adds its `_credentials` envelope.
///
/// The cookie projector is `None` because plexus-core does not know what
/// transport is attached to this stream; the transport may project later.
fn content_of<T: Serialize>(event: &T) -> super::wire::Content {
    if let Some(content) = super::wire::encode(event) {
        return content;
    }
    let (payload, captured) = serialize_with_credential_capture(event);
    let (content, _hints) = assemble_envelope_content(payload, captured, &CookieProjector::None);
    super::wire::Content::from(content)
}

/// Create an error stream
///
/// Returns a single-item stream containing an error frame carrying `error`.
/// From a `PlexusError`: `error_stream(RemoteError::from(&e), provenance, false)`.
pub fn error_stream(
    error: RemoteError,
    provenance: Vec<String>,
    recoverable: bool,
) -> PlexusStream {
    let metadata = StreamMetadata::new(provenance, PlexusContext::hash());

    Box::pin(stream::once(async move {
        PlexusStreamItem::error(metadata, error, recoverable)
    }))
}

/// Create a done stream
///
/// Returns a single-item stream containing a done event.
pub fn done_stream(provenance: Vec<String>) -> PlexusStream {
    let metadata = StreamMetadata::new(provenance, PlexusContext::hash());

    Box::pin(stream::once(async move {
        PlexusStreamItem::Done { metadata }
    }))
}

/// Create a progress stream
///
/// Returns a single-item stream containing a progress frame for the call
/// `content_type` (e.g. "tickets.import"), carrying the method's progress
/// value `content` — `serde_json::to_value(&p)` of its declared `P`.
pub fn progress_stream(
    content_type: String,
    content: serde_json::Value,
    provenance: Vec<String>,
) -> PlexusStream {
    let metadata = StreamMetadata::new(provenance, PlexusContext::hash());

    Box::pin(stream::once(async move {
        PlexusStreamItem::progress(metadata, content_type, content)
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::StreamExt;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct TestEvent {
        value: i32,
    }

    #[tokio::test]
    async fn test_wrap_stream() {
        let events = vec![TestEvent { value: 1 }, TestEvent { value: 2 }];
        let input_stream = stream::iter(events);

        let wrapped = wrap_stream(input_stream, "test.event", vec!["test".into()]);
        let items: Vec<_> = wrapped.collect().await;

        // 2 data items + 1 done
        assert_eq!(items.len(), 3);

        // Check first item
        match &items[0] {
            PlexusStreamItem::Data {
                content_type,
                content,
                metadata,
            } => {
                assert_eq!(content_type, "test.event");
                assert_eq!(content["value"], 1);
                assert_eq!(metadata.provenance, vec!["test"]);
            }
            _ => panic!("Expected Data item"),
        }

        // Check done at end
        assert!(matches!(items[2], PlexusStreamItem::Done { .. }));
    }

    /// AUTHZ-CRED-CORE-2 AC #10 regression: a stream item whose payload
    /// has no `Credential<T>` fields produces wire content that's
    /// byte-identical to today (no `_credentials` key added). The path
    /// goes through the new envelope-assembly machinery — this asserts
    /// the additive-only property holds.
    #[tokio::test]
    async fn wrap_stream_credential_free_payload_is_wire_identical() {
        let events = vec![TestEvent { value: 7 }];
        let input_stream = stream::iter(events);

        let wrapped = wrap_stream(input_stream, "test.event", vec!["t".into()]);
        let items: Vec<_> = wrapped.collect().await;

        assert_eq!(items.len(), 2); // 1 data + 1 done
        match &items[0] {
            PlexusStreamItem::Data { content, .. } => {
                // Same shape as before AUTHZ-CRED-CORE-2: just the
                // serialized payload as an object.
                let obj = content.as_object().expect("object");
                assert_eq!(obj.get("value").unwrap(), &serde_json::json!(7));
                assert!(
                    !obj.contains_key("_credentials"),
                    "_credentials key MUST NOT appear on non-credential payloads"
                );
                assert_eq!(obj.len(), 1, "no extra fields");
            }
            _ => panic!("Expected Data item"),
        }
    }

    /// AUTHZ-CRED-CORE-2 sentinel-emission: a payload containing a
    /// `Credential<T>` field produces a Data item whose body has the
    /// sentinel inline. Today the `_credentials` sidecar is absent
    /// because plexus-auth-core's `DispatchCaptureGuard::install` is
    /// `pub(crate)` and unreachable from this crate (see
    /// `plans/AUTHZ/AUTHZ-CRED-CORE-2-RUN-NOTES.md` §Blocker). Once
    /// the public exposure lands, the sidecar will populate
    /// automatically — this test will continue passing AND the
    /// `_credentials` assertion can flip from "absent" to "present
    /// with the captured value".
    #[tokio::test]
    async fn wrap_stream_credential_bearing_payload_emits_sentinel_in_body() {
        use plexus_auth_core::{
            AttachmentSite, Credential, CredentialIssuer, CredentialKind, CredentialMetadata,
            CredentialMinter, CredentialScheme, HeaderName, MethodPath, Origin, Scope,
        };

        // Construct a credential and embed it in a payload. The minter
        // is `pub(crate)` to plexus-auth-core; we can't reach its
        // constructor from here, but we CAN derive a credential indirectly
        // by using the `Serialize` impl through a stream — which is
        // exactly what dispatch does in production. For this test we
        // construct via a workaround: serialize a struct containing a
        // sentinel-typed value directly to confirm the wrap_stream path
        // routes it.
        //
        // (Once AUTHZ-CRED-CORE-2-a lands and exposes a public minter or
        // capture API, this test can be tightened to assert the captured
        // sidecar entry too.)

        // Mint via the test-internal API path. We need a CredentialMinter
        // for this test; the constructor lives behind the seal so we
        // cannot construct one. Instead we drive the test through a
        // typed payload that already contains a sentinel-shaped value
        // by Serializing a `Credential<T>` via the public API — which
        // works because plexus-auth-core's Serialize impl emits the
        // sentinel unconditionally.
        //
        // We need access to a Credential<T>. Since
        // `CredentialMinter::new_sealed` is pub(crate), this test
        // exercises the wrap_stream serialization path through the
        // already-public `Credential<T>` Serialize impl by going via a
        // domain wrapper that serde renders identically:
        let _ = (
            CredentialMinter::issuer, // satisfy unused-import for diagnostic
            Credential::<String>::metadata,
            CredentialIssuer::new(
                Origin::new("ws://test"),
                MethodPath::try_new("auth.login").unwrap(),
            ),
            CredentialMetadata::new(
                CredentialKind::Bearer,
                AttachmentSite::Header {
                    name: HeaderName::try_new("authorization").unwrap(),
                },
                Some(CredentialScheme::new("Bearer ")),
                Vec::<Scope>::new(),
                None,
                None,
                None,
                CredentialIssuer::new(
                    Origin::new("ws://test"),
                    MethodPath::try_new("auth.login").unwrap(),
                ),
            ),
        );

        // For this regression test, we send a payload that contains the
        // raw sentinel shape directly, mimicking what
        // `Credential<T>::Serialize` would emit. This confirms the
        // wrap_stream path forwards the sentinel intact and does NOT
        // strip or transform it.
        #[derive(Serialize)]
        struct LoginPayload {
            user_id: String,
            // In production this would be `Credential<String>`; here we
            // hand-write the sentinel JSON the Serialize impl emits so
            // we can run this test without minter access.
            session: serde_json::Value,
        }
        let payload = LoginPayload {
            user_id: "alice".into(),
            session: serde_json::json!({ "$credential": "cred_0" }),
        };
        let input_stream = stream::iter(vec![payload]);

        let wrapped = wrap_stream(input_stream, "auth.login.result", vec!["auth".into()]);
        let items: Vec<_> = wrapped.collect().await;

        let content = match &items[0] {
            PlexusStreamItem::Data { content, .. } => content,
            _ => panic!("Expected Data item"),
        };

        // Sentinel survives intact in the body.
        assert_eq!(
            content.get("session").unwrap(),
            &serde_json::json!({ "$credential": "cred_0" })
        );
        // No _credentials sidecar today (see RUN-NOTES §Blocker). When
        // plexus-auth-core exposes the guard publicly this assertion
        // flips to checking sidecar presence.
        let obj = content.as_object().unwrap();
        assert!(!obj.contains_key("_credentials"),
            "sidecar absent until plexus-auth-core exposes DispatchCaptureGuard::install");
    }


    #[tokio::test]
    async fn test_error_stream() {
        let stream = error_stream(
            RemoteError::Execution {
                message: "Something failed".into(),
            },
            vec!["test".into()],
            false,
        );
        let items: Vec<_> = stream.collect().await;

        assert_eq!(items.len(), 1);
        match &items[0] {
            PlexusStreamItem::Error {
                error,
                recoverable,
                metadata,
                ..
            } => {
                assert_eq!(
                    error,
                    &RemoteError::Execution {
                        message: "Something failed".into()
                    }
                );
                assert!(!recoverable);
                assert_eq!(metadata.provenance, vec!["test"]);
            }
            _ => panic!("Expected Error item"),
        }
    }

    #[tokio::test]
    async fn test_error_stream_carries_recoverable() {
        let stream = error_stream(RemoteError::Unauthenticated, vec!["test".into()], true);
        let items: Vec<_> = stream.collect().await;

        assert_eq!(items.len(), 1);
        assert!(matches!(
            &items[0],
            PlexusStreamItem::Error {
                error: RemoteError::Unauthenticated,
                recoverable: true,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn test_progress_stream() {
        let stream = progress_stream(
            "test.import".into(),
            serde_json::json!({"message": "indexing", "percentage": 50.0}),
            vec!["test".into()],
        );
        let items: Vec<_> = stream.collect().await;

        assert_eq!(items.len(), 1);
        match &items[0] {
            PlexusStreamItem::Progress {
                content_type,
                content,
                ..
            } => {
                assert_eq!(content_type, "test.import");
                let note: plexus_client::Note =
                    serde_json::from_value(content.clone()).expect("a Note");
                assert_eq!(note, plexus_client::Note::new("indexing").with_percentage(50.0));
            }
            _ => panic!("Expected Progress item"),
        }
    }

    // ------------------------------------------------------------------
    // RETURNS-8: the per-form wrappers
    // ------------------------------------------------------------------

    /// `(type, content)` of every frame but the last, and asserts the last
    /// is the stream's one `done`.
    async fn frames(stream: PlexusStream) -> Vec<(&'static str, serde_json::Value)> {
        let items: Vec<_> = stream.collect().await;
        let (last, body) = items.split_last().expect("at least a done");
        assert!(matches!(last, PlexusStreamItem::Done { .. }), "ends in done");
        body.iter()
            .map(|item| match item {
                PlexusStreamItem::Data { content_type, content, .. } => {
                    assert_eq!(content_type, "t.m");
                    ("data", content.clone().into_value())
                }
                PlexusStreamItem::Progress { content_type, content, .. } => {
                    assert_eq!(content_type, "t.m");
                    ("progress", content.clone())
                }
                PlexusStreamItem::Done { .. } => panic!("a second done"),
                other => panic!("unexpected frame {other:?}"),
            })
            .collect()
    }

    #[tokio::test]
    async fn wrap_one_is_one_data_frame_then_done() {
        let got = frames(wrap_one(TestEvent { value: 1 }, "t.m", vec!["t".into()])).await;
        assert_eq!(got, vec![("data", serde_json::json!({"value": 1}))]);
    }

    #[tokio::test]
    async fn wrap_one_result_carries_ok_or_err() {
        let ok: Result<u32, String> = Ok(7);
        let err: Result<u32, String> = Err("no".into());
        assert_eq!(
            frames(wrap_one_result(ok, "t.m", vec!["t".into()])).await,
            vec![("data", serde_json::json!({"ok": 7}))]
        );
        assert_eq!(
            frames(wrap_one_result(err, "t.m", vec!["t".into()])).await,
            vec![("data", serde_json::json!({"err": "no"}))]
        );
    }

    #[tokio::test]
    async fn wrap_result_stream_carries_on_past_an_err() {
        let items: Vec<Result<u32, String>> = vec![Ok(1), Err("bad".into()), Ok(3)];
        let got = frames(wrap_result_stream(stream::iter(items), "t.m", vec!["t".into()])).await;
        assert_eq!(
            got,
            vec![
                ("data", serde_json::json!({"ok": 1})),
                ("data", serde_json::json!({"err": "bad"})),
                ("data", serde_json::json!({"ok": 3})),
            ]
        );
    }

    #[tokio::test]
    async fn wrap_progress_stream_splits_updates_from_items() {
        let steps: Vec<Progress<u32>> = vec![
            Progress::Update(plexus_client::Note::new("half").with_percentage(50.0)),
            Progress::Item(9),
        ];
        let got = frames(wrap_progress_stream(stream::iter(steps), "t.m", vec!["t".into()])).await;
        assert_eq!(
            got,
            vec![
                ("progress", serde_json::json!({"message": "half", "percentage": 50.0})),
                ("data", serde_json::json!(9)),
            ]
        );
    }

    #[tokio::test]
    async fn wrap_result_progress_stream_maps_all_three_cases() {
        let steps: Vec<Result<Progress<u32, String>, String>> = vec![
            Ok(Progress::Update("step".into())),
            Ok(Progress::Item(1)),
            Err("refused".into()),
        ];
        let got = frames(wrap_result_progress_stream(
            stream::iter(steps),
            "t.m",
            vec!["t".into()],
        ))
        .await;
        assert_eq!(
            got,
            vec![
                ("progress", serde_json::json!("step")),
                ("data", serde_json::json!({"ok": 1})),
                ("data", serde_json::json!({"err": "refused"})),
            ]
        );
    }
}