Skip to main content

plexus_core/plexus/
streaming.rs

1//! Streaming helpers for the caller-wraps architecture
2//!
3//! These functions are used by the DynamicHub routing layer to wrap activation
4//! responses with metadata. Activations return typed domain events, and
5//! the caller uses these helpers to create PlexusStreamItems.
6
7use futures::stream::{self, Stream, StreamExt};
8use plexus_client::{Progress, RemoteError};
9use serde::{Serialize, Serializer};
10use std::pin::Pin;
11use std::sync::Arc;
12
13use super::context::PlexusContext;
14use super::credential_envelope::{
15    assemble_envelope_content, serialize_with_credential_capture, CookieProjector,
16};
17use super::types::{PlexusStreamItem, StreamMetadata};
18
19/// Type alias for boxed stream of PlexusStreamItem
20pub type PlexusStream = Pin<Box<dyn Stream<Item = PlexusStreamItem> + Send>>;
21
22/// Wrap a typed stream into PlexusStream with automatic Done event
23///
24/// This is the core helper for the caller-wraps architecture.
25/// Activations return typed domain events (e.g., HealthEvent),
26/// and the caller wraps them with metadata. A Done event is
27/// automatically appended when the stream completes.
28///
29/// # Dispatch-time credential interception (AUTHZ-CRED-CORE-2)
30///
31/// For every emitted item, this function routes the serialization through
32/// the dispatch-time credential capture machinery: a fresh sidecar is
33/// installed (per the RAII guard documented in
34/// `plexus_auth_core::DispatchCaptureGuard`), serialization runs (and
35/// each `Credential<T>` field emits its sentinel inline while the inner
36/// value is captured into the sidecar), and the resulting `(payload,
37/// captured)` pair is assembled into a wire envelope with an optional
38/// `_credentials` field. Payloads with zero `Credential<T>` fields are
39/// wire-format-identical to today (additive only).
40///
41/// See `crate::plexus::credential_envelope` for the envelope assembly
42/// rules and `plans/AUTHZ/AUTHZ-CRED-CORE-2.md` for the contract.
43///
44/// # Example
45///
46/// ```ignore
47/// let stream = health.check();  // Returns Stream<Item = HealthEvent>
48/// let wrapped = wrap_stream(stream, "health.status", vec!["health".into()]);
49/// // Stream will emit: Data, Data, ..., Done
50/// ```
51pub fn wrap_stream<T: Serialize + Send + 'static>(
52    stream: impl Stream<Item = T> + Send + 'static,
53    content_type: &'static str,
54    provenance: Vec<String>,
55) -> PlexusStream {
56    let plexus_hash = PlexusContext::hash();
57    let metadata = Arc::new(StreamMetadata::new(provenance.clone(), plexus_hash.clone()));
58    let done = StreamMetadata::new(provenance, plexus_hash);
59    Box::pin(Wrapped::<_, DataForm> {
60        inner: stream,
61        metadata,
62        content_type,
63        done: Some(done),
64        ended: false,
65        form: std::marker::PhantomData,
66    })
67}
68
69// ============================================================================
70// RETURNS-8: one wrapper per signature form
71// ============================================================================
72//
73// `#[plexus_macros::method]` reads a method's return type and calls the one
74// wrapper that matches it (RETURNS-1 decisions 2, 3, 4, 10):
75//
76// | signature | wrapper | frames per item |
77// |---|---|---|
78// | `-> T` | [`wrap_one`] | data `T`, then done |
79// | `-> Result<T, E>` | [`wrap_one_result`] | data `{"ok": t}` / `{"err": e}`, then done |
80// | `-> impl Stream<Item = T>` | [`wrap_stream`] | data `T` … done |
81// | `-> impl Stream<Item = Result<T, E>>` | [`wrap_result_stream`] | data `{ok}` / `{err}` … done |
82// | `-> impl Stream<Item = Progress<T, P>>` | [`wrap_progress_stream`] | `Update(p)` → progress `P`; `Item(t)` → data `T` |
83// | `-> 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}` |
84//
85// An `Err` item is data: it does not end the stream — the method ends it by
86// returning. Every wrapper appends exactly one `done`.
87
88/// One frame of a method's output before metadata: an item (a data frame) or
89/// a progress update (a progress frame).
90enum Out<D, P> {
91    Data(D),
92    Progress(P),
93}
94
95/// A Result item as the wire carries it: `Ok(t)` → `{"ok": t}`, `Err(e)` →
96/// `{"err": e}` (`plexus_client::wire_result`).
97struct WireResult<T, E>(Result<T, E>);
98
99impl<T: Serialize, E: Serialize> Serialize for WireResult<T, E> {
100    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
101        plexus_client::wire_result::serialize(&self.0, serializer)
102    }
103}
104
105/// `-> T`: one data frame carrying `item`, then `done`.
106pub fn wrap_one<T: Serialize + Send + 'static>(
107    item: T,
108    content_type: &'static str,
109    provenance: Vec<String>,
110) -> PlexusStream {
111    wrap_frames(
112        stream::once(futures::future::ready(Out::<T, ()>::Data(item))),
113        content_type,
114        provenance,
115    )
116}
117
118/// `-> Result<T, E>`: one data frame, `{"ok": t}` or `{"err": e}`, then `done`.
119pub fn wrap_one_result<T, E>(
120    item: Result<T, E>,
121    content_type: &'static str,
122    provenance: Vec<String>,
123) -> PlexusStream
124where
125    T: Serialize + Send + 'static,
126    E: Serialize + Send + 'static,
127{
128    wrap_frames(
129        stream::once(futures::future::ready(Out::<_, ()>::Data(WireResult(item)))),
130        content_type,
131        provenance,
132    )
133}
134
135/// `-> impl Stream<Item = Result<T, E>>`: one data frame per item, `{"ok": t}`
136/// or `{"err": e}`; an `Err` does not end the stream. Then `done`.
137pub fn wrap_result_stream<T, E>(
138    stream: impl Stream<Item = Result<T, E>> + Send + 'static,
139    content_type: &'static str,
140    provenance: Vec<String>,
141) -> PlexusStream
142where
143    T: Serialize + Send + 'static,
144    E: Serialize + Send + 'static,
145{
146    wrap_frames(
147        stream.map(|r| Out::<_, ()>::Data(WireResult(r))),
148        content_type,
149        provenance,
150    )
151}
152
153/// `-> impl Stream<Item = Progress<T, P>>`: `Update(p)` → a progress frame
154/// carrying `p`; `Item(t)` → a data frame carrying `t`. Then `done`.
155pub fn wrap_progress_stream<T, P>(
156    stream: impl Stream<Item = Progress<T, P>> + Send + 'static,
157    content_type: &'static str,
158    provenance: Vec<String>,
159) -> PlexusStream
160where
161    T: Serialize + Send + 'static,
162    P: Serialize + Send + 'static,
163{
164    wrap_frames(
165        stream.map(|step| match step {
166            Progress::Update(p) => Out::Progress(p),
167            Progress::Item(t) => Out::Data(t),
168        }),
169        content_type,
170        provenance,
171    )
172}
173
174/// `-> impl Stream<Item = Result<Progress<T, P>, E>>`: `Ok(Update(p))` → a
175/// progress frame; `Ok(Item(t))` → a data frame `{"ok": t}`; `Err(e)` → a data
176/// frame `{"err": e}`. Then `done`.
177pub fn wrap_result_progress_stream<T, P, E>(
178    stream: impl Stream<Item = Result<Progress<T, P>, E>> + Send + 'static,
179    content_type: &'static str,
180    provenance: Vec<String>,
181) -> PlexusStream
182where
183    T: Serialize + Send + 'static,
184    P: Serialize + Send + 'static,
185    E: Serialize + Send + 'static,
186{
187    wrap_frames(
188        stream.map(|r| match r {
189            Ok(Progress::Update(p)) => Out::Progress(p),
190            Ok(Progress::Item(t)) => Out::Data(WireResult(Ok(t))),
191            Err(e) => Out::Data(WireResult(Err(e))),
192        }),
193        content_type,
194        provenance,
195    )
196}
197
198/// The one place frames get their metadata: every data item goes through the
199/// credential capture `wrap_stream` has always applied, every progress value
200/// is serialized as-is, and exactly one `done` follows the last item.
201fn wrap_frames<D, P>(
202    stream: impl Stream<Item = Out<D, P>> + Send + 'static,
203    content_type: &'static str,
204    provenance: Vec<String>,
205) -> PlexusStream
206where
207    D: Serialize + Send + 'static,
208    P: Serialize + Send + 'static,
209{
210    let plexus_hash = PlexusContext::hash();
211    let metadata = Arc::new(StreamMetadata::new(provenance.clone(), plexus_hash.clone()));
212    let done = StreamMetadata::new(provenance, plexus_hash);
213    Box::pin(Wrapped::<_, OutForm> {
214        inner: stream,
215        metadata,
216        content_type,
217        done: Some(done),
218        ended: false,
219        form: std::marker::PhantomData,
220    })
221}
222
223pin_project_lite::pin_project! {
224    /// Every wrapper's stream. PERF-7: each event is a `Data` item whose
225    /// metadata is the stream's (shared, not cloned), whose content type is
226    /// the method's, and whose content is the event encoded once — straight
227    /// into the WebSocket pipe's buffer when the pipe polls this stream
228    /// ([`super::wire::pipe`]), as a `Value` anywhere else. RETURNS-8: `K`
229    /// is the signature form's [`Form`] — what one item of the method's
230    /// stream becomes (a data frame, or a progress frame).
231    struct Wrapped<S, K> {
232        #[pin]
233        inner: S,
234        metadata: Arc<StreamMetadata>,
235        content_type: &'static str,
236        done: Option<StreamMetadata>,
237        ended: bool,
238        form: std::marker::PhantomData<fn() -> K>,
239    }
240}
241
242/// RETURNS-8: what one item of a wrapped stream becomes.
243trait Form<I> {
244    fn frame(item: I, metadata: &Arc<StreamMetadata>, content_type: &'static str) -> PlexusStreamItem;
245}
246
247/// `wrap_stream`'s form: every item is data.
248struct DataForm;
249
250impl<T: Serialize> Form<T> for DataForm {
251    fn frame(event: T, metadata: &Arc<StreamMetadata>, content_type: &'static str) -> PlexusStreamItem {
252        PlexusStreamItem::Data {
253            metadata: metadata.clone(),
254            content_type: std::borrow::Cow::Borrowed(content_type),
255            content: content_of(&event),
256        }
257    }
258}
259
260/// The other forms': an [`Out`] — data, or a progress value (RETURNS-6's
261/// progress frame, the method's `P` serialized as-is: progress reports carry
262/// no credentials).
263struct OutForm;
264
265impl<D: Serialize, P: Serialize> Form<Out<D, P>> for OutForm {
266    fn frame(out: Out<D, P>, metadata: &Arc<StreamMetadata>, content_type: &'static str) -> PlexusStreamItem {
267        match out {
268            Out::Data(item) => DataForm::frame(item, metadata, content_type),
269            Out::Progress(p) => PlexusStreamItem::progress(
270                (**metadata).clone(),
271                content_type.to_string(),
272                serde_json::to_value(&p).unwrap_or(serde_json::Value::Null),
273            ),
274        }
275    }
276}
277
278impl<S, K> Stream for Wrapped<S, K>
279where
280    S: Stream,
281    K: Form<S::Item>,
282{
283    type Item = PlexusStreamItem;
284
285    fn poll_next(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<PlexusStreamItem>> {
286        use std::task::Poll;
287        let this = self.project();
288        if !*this.ended {
289            // A stream the method polls inside its own (a call it routes and
290            // reads in process) is not the pipe's: one level deeper.
291            match super::wire::nested(|| this.inner.poll_next(cx)) {
292                Poll::Ready(Some(event)) => return Poll::Ready(Some(K::frame(event, this.metadata, this.content_type))),
293                Poll::Ready(None) => *this.ended = true,
294                Poll::Pending => return Poll::Pending,
295            }
296        }
297        Poll::Ready(this.done.take().map(|metadata| PlexusStreamItem::Done { metadata }))
298    }
299}
300
301/// An event's content: encoded once into the pipe's buffer when the pipe
302/// polls this stream (PERF-7), else — and for an event carrying a
303/// credential, whose envelope is assembled as before — a `Value`.
304///
305/// # Dispatch-time credential interception (AUTHZ-CRED-CORE-2)
306///
307/// Either way the serialization runs under the credential capture: a
308/// `Credential<T>` writes its sentinel inline and its value is captured.
309/// An event that captured none is today's payload exactly (encoded, the
310/// same JSON); one that captured any takes the `Value` path, where
311/// [`assemble_envelope_content`] adds its `_credentials` envelope.
312///
313/// The cookie projector is `None` because plexus-core does not know what
314/// transport is attached to this stream; the transport may project later.
315fn content_of<T: Serialize>(event: &T) -> super::wire::Content {
316    if let Some(content) = super::wire::encode(event) {
317        return content;
318    }
319    let (payload, captured) = serialize_with_credential_capture(event);
320    let (content, _hints) = assemble_envelope_content(payload, captured, &CookieProjector::None);
321    super::wire::Content::from(content)
322}
323
324/// Create an error stream
325///
326/// Returns a single-item stream containing an error frame carrying `error`.
327/// From a `PlexusError`: `error_stream(RemoteError::from(&e), provenance, false)`.
328pub fn error_stream(
329    error: RemoteError,
330    provenance: Vec<String>,
331    recoverable: bool,
332) -> PlexusStream {
333    let metadata = StreamMetadata::new(provenance, PlexusContext::hash());
334
335    Box::pin(stream::once(async move {
336        PlexusStreamItem::error(metadata, error, recoverable)
337    }))
338}
339
340/// Create a done stream
341///
342/// Returns a single-item stream containing a done event.
343pub fn done_stream(provenance: Vec<String>) -> PlexusStream {
344    let metadata = StreamMetadata::new(provenance, PlexusContext::hash());
345
346    Box::pin(stream::once(async move {
347        PlexusStreamItem::Done { metadata }
348    }))
349}
350
351/// Create a progress stream
352///
353/// Returns a single-item stream containing a progress frame for the call
354/// `content_type` (e.g. "tickets.import"), carrying the method's progress
355/// value `content` — `serde_json::to_value(&p)` of its declared `P`.
356pub fn progress_stream(
357    content_type: String,
358    content: serde_json::Value,
359    provenance: Vec<String>,
360) -> PlexusStream {
361    let metadata = StreamMetadata::new(provenance, PlexusContext::hash());
362
363    Box::pin(stream::once(async move {
364        PlexusStreamItem::progress(metadata, content_type, content)
365    }))
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use futures::StreamExt;
372    use serde::{Deserialize, Serialize};
373
374    #[derive(Debug, Clone, Serialize, Deserialize)]
375    struct TestEvent {
376        value: i32,
377    }
378
379    #[tokio::test]
380    async fn test_wrap_stream() {
381        let events = vec![TestEvent { value: 1 }, TestEvent { value: 2 }];
382        let input_stream = stream::iter(events);
383
384        let wrapped = wrap_stream(input_stream, "test.event", vec!["test".into()]);
385        let items: Vec<_> = wrapped.collect().await;
386
387        // 2 data items + 1 done
388        assert_eq!(items.len(), 3);
389
390        // Check first item
391        match &items[0] {
392            PlexusStreamItem::Data {
393                content_type,
394                content,
395                metadata,
396            } => {
397                assert_eq!(content_type, "test.event");
398                assert_eq!(content["value"], 1);
399                assert_eq!(metadata.provenance, vec!["test"]);
400            }
401            _ => panic!("Expected Data item"),
402        }
403
404        // Check done at end
405        assert!(matches!(items[2], PlexusStreamItem::Done { .. }));
406    }
407
408    /// AUTHZ-CRED-CORE-2 AC #10 regression: a stream item whose payload
409    /// has no `Credential<T>` fields produces wire content that's
410    /// byte-identical to today (no `_credentials` key added). The path
411    /// goes through the new envelope-assembly machinery — this asserts
412    /// the additive-only property holds.
413    #[tokio::test]
414    async fn wrap_stream_credential_free_payload_is_wire_identical() {
415        let events = vec![TestEvent { value: 7 }];
416        let input_stream = stream::iter(events);
417
418        let wrapped = wrap_stream(input_stream, "test.event", vec!["t".into()]);
419        let items: Vec<_> = wrapped.collect().await;
420
421        assert_eq!(items.len(), 2); // 1 data + 1 done
422        match &items[0] {
423            PlexusStreamItem::Data { content, .. } => {
424                // Same shape as before AUTHZ-CRED-CORE-2: just the
425                // serialized payload as an object.
426                let obj = content.as_object().expect("object");
427                assert_eq!(obj.get("value").unwrap(), &serde_json::json!(7));
428                assert!(
429                    !obj.contains_key("_credentials"),
430                    "_credentials key MUST NOT appear on non-credential payloads"
431                );
432                assert_eq!(obj.len(), 1, "no extra fields");
433            }
434            _ => panic!("Expected Data item"),
435        }
436    }
437
438    /// AUTHZ-CRED-CORE-2 sentinel-emission: a payload containing a
439    /// `Credential<T>` field produces a Data item whose body has the
440    /// sentinel inline. Today the `_credentials` sidecar is absent
441    /// because plexus-auth-core's `DispatchCaptureGuard::install` is
442    /// `pub(crate)` and unreachable from this crate (see
443    /// `plans/AUTHZ/AUTHZ-CRED-CORE-2-RUN-NOTES.md` §Blocker). Once
444    /// the public exposure lands, the sidecar will populate
445    /// automatically — this test will continue passing AND the
446    /// `_credentials` assertion can flip from "absent" to "present
447    /// with the captured value".
448    #[tokio::test]
449    async fn wrap_stream_credential_bearing_payload_emits_sentinel_in_body() {
450        use plexus_auth_core::{
451            AttachmentSite, Credential, CredentialIssuer, CredentialKind, CredentialMetadata,
452            CredentialMinter, CredentialScheme, HeaderName, MethodPath, Origin, Scope,
453        };
454
455        // Construct a credential and embed it in a payload. The minter
456        // is `pub(crate)` to plexus-auth-core; we can't reach its
457        // constructor from here, but we CAN derive a credential indirectly
458        // by using the `Serialize` impl through a stream — which is
459        // exactly what dispatch does in production. For this test we
460        // construct via a workaround: serialize a struct containing a
461        // sentinel-typed value directly to confirm the wrap_stream path
462        // routes it.
463        //
464        // (Once AUTHZ-CRED-CORE-2-a lands and exposes a public minter or
465        // capture API, this test can be tightened to assert the captured
466        // sidecar entry too.)
467
468        // Mint via the test-internal API path. We need a CredentialMinter
469        // for this test; the constructor lives behind the seal so we
470        // cannot construct one. Instead we drive the test through a
471        // typed payload that already contains a sentinel-shaped value
472        // by Serializing a `Credential<T>` via the public API — which
473        // works because plexus-auth-core's Serialize impl emits the
474        // sentinel unconditionally.
475        //
476        // We need access to a Credential<T>. Since
477        // `CredentialMinter::new_sealed` is pub(crate), this test
478        // exercises the wrap_stream serialization path through the
479        // already-public `Credential<T>` Serialize impl by going via a
480        // domain wrapper that serde renders identically:
481        let _ = (
482            CredentialMinter::issuer, // satisfy unused-import for diagnostic
483            Credential::<String>::metadata,
484            CredentialIssuer::new(
485                Origin::new("ws://test"),
486                MethodPath::try_new("auth.login").unwrap(),
487            ),
488            CredentialMetadata::new(
489                CredentialKind::Bearer,
490                AttachmentSite::Header {
491                    name: HeaderName::try_new("authorization").unwrap(),
492                },
493                Some(CredentialScheme::new("Bearer ")),
494                Vec::<Scope>::new(),
495                None,
496                None,
497                None,
498                CredentialIssuer::new(
499                    Origin::new("ws://test"),
500                    MethodPath::try_new("auth.login").unwrap(),
501                ),
502            ),
503        );
504
505        // For this regression test, we send a payload that contains the
506        // raw sentinel shape directly, mimicking what
507        // `Credential<T>::Serialize` would emit. This confirms the
508        // wrap_stream path forwards the sentinel intact and does NOT
509        // strip or transform it.
510        #[derive(Serialize)]
511        struct LoginPayload {
512            user_id: String,
513            // In production this would be `Credential<String>`; here we
514            // hand-write the sentinel JSON the Serialize impl emits so
515            // we can run this test without minter access.
516            session: serde_json::Value,
517        }
518        let payload = LoginPayload {
519            user_id: "alice".into(),
520            session: serde_json::json!({ "$credential": "cred_0" }),
521        };
522        let input_stream = stream::iter(vec![payload]);
523
524        let wrapped = wrap_stream(input_stream, "auth.login.result", vec!["auth".into()]);
525        let items: Vec<_> = wrapped.collect().await;
526
527        let content = match &items[0] {
528            PlexusStreamItem::Data { content, .. } => content,
529            _ => panic!("Expected Data item"),
530        };
531
532        // Sentinel survives intact in the body.
533        assert_eq!(
534            content.get("session").unwrap(),
535            &serde_json::json!({ "$credential": "cred_0" })
536        );
537        // No _credentials sidecar today (see RUN-NOTES §Blocker). When
538        // plexus-auth-core exposes the guard publicly this assertion
539        // flips to checking sidecar presence.
540        let obj = content.as_object().unwrap();
541        assert!(!obj.contains_key("_credentials"),
542            "sidecar absent until plexus-auth-core exposes DispatchCaptureGuard::install");
543    }
544
545
546    #[tokio::test]
547    async fn test_error_stream() {
548        let stream = error_stream(
549            RemoteError::Execution {
550                message: "Something failed".into(),
551            },
552            vec!["test".into()],
553            false,
554        );
555        let items: Vec<_> = stream.collect().await;
556
557        assert_eq!(items.len(), 1);
558        match &items[0] {
559            PlexusStreamItem::Error {
560                error,
561                recoverable,
562                metadata,
563                ..
564            } => {
565                assert_eq!(
566                    error,
567                    &RemoteError::Execution {
568                        message: "Something failed".into()
569                    }
570                );
571                assert!(!recoverable);
572                assert_eq!(metadata.provenance, vec!["test"]);
573            }
574            _ => panic!("Expected Error item"),
575        }
576    }
577
578    #[tokio::test]
579    async fn test_error_stream_carries_recoverable() {
580        let stream = error_stream(RemoteError::Unauthenticated, vec!["test".into()], true);
581        let items: Vec<_> = stream.collect().await;
582
583        assert_eq!(items.len(), 1);
584        assert!(matches!(
585            &items[0],
586            PlexusStreamItem::Error {
587                error: RemoteError::Unauthenticated,
588                recoverable: true,
589                ..
590            }
591        ));
592    }
593
594    #[tokio::test]
595    async fn test_progress_stream() {
596        let stream = progress_stream(
597            "test.import".into(),
598            serde_json::json!({"message": "indexing", "percentage": 50.0}),
599            vec!["test".into()],
600        );
601        let items: Vec<_> = stream.collect().await;
602
603        assert_eq!(items.len(), 1);
604        match &items[0] {
605            PlexusStreamItem::Progress {
606                content_type,
607                content,
608                ..
609            } => {
610                assert_eq!(content_type, "test.import");
611                let note: plexus_client::Note =
612                    serde_json::from_value(content.clone()).expect("a Note");
613                assert_eq!(note, plexus_client::Note::new("indexing").with_percentage(50.0));
614            }
615            _ => panic!("Expected Progress item"),
616        }
617    }
618
619    // ------------------------------------------------------------------
620    // RETURNS-8: the per-form wrappers
621    // ------------------------------------------------------------------
622
623    /// `(type, content)` of every frame but the last, and asserts the last
624    /// is the stream's one `done`.
625    async fn frames(stream: PlexusStream) -> Vec<(&'static str, serde_json::Value)> {
626        let items: Vec<_> = stream.collect().await;
627        let (last, body) = items.split_last().expect("at least a done");
628        assert!(matches!(last, PlexusStreamItem::Done { .. }), "ends in done");
629        body.iter()
630            .map(|item| match item {
631                PlexusStreamItem::Data { content_type, content, .. } => {
632                    assert_eq!(content_type, "t.m");
633                    ("data", content.clone().into_value())
634                }
635                PlexusStreamItem::Progress { content_type, content, .. } => {
636                    assert_eq!(content_type, "t.m");
637                    ("progress", content.clone())
638                }
639                PlexusStreamItem::Done { .. } => panic!("a second done"),
640                other => panic!("unexpected frame {other:?}"),
641            })
642            .collect()
643    }
644
645    #[tokio::test]
646    async fn wrap_one_is_one_data_frame_then_done() {
647        let got = frames(wrap_one(TestEvent { value: 1 }, "t.m", vec!["t".into()])).await;
648        assert_eq!(got, vec![("data", serde_json::json!({"value": 1}))]);
649    }
650
651    #[tokio::test]
652    async fn wrap_one_result_carries_ok_or_err() {
653        let ok: Result<u32, String> = Ok(7);
654        let err: Result<u32, String> = Err("no".into());
655        assert_eq!(
656            frames(wrap_one_result(ok, "t.m", vec!["t".into()])).await,
657            vec![("data", serde_json::json!({"ok": 7}))]
658        );
659        assert_eq!(
660            frames(wrap_one_result(err, "t.m", vec!["t".into()])).await,
661            vec![("data", serde_json::json!({"err": "no"}))]
662        );
663    }
664
665    #[tokio::test]
666    async fn wrap_result_stream_carries_on_past_an_err() {
667        let items: Vec<Result<u32, String>> = vec![Ok(1), Err("bad".into()), Ok(3)];
668        let got = frames(wrap_result_stream(stream::iter(items), "t.m", vec!["t".into()])).await;
669        assert_eq!(
670            got,
671            vec![
672                ("data", serde_json::json!({"ok": 1})),
673                ("data", serde_json::json!({"err": "bad"})),
674                ("data", serde_json::json!({"ok": 3})),
675            ]
676        );
677    }
678
679    #[tokio::test]
680    async fn wrap_progress_stream_splits_updates_from_items() {
681        let steps: Vec<Progress<u32>> = vec![
682            Progress::Update(plexus_client::Note::new("half").with_percentage(50.0)),
683            Progress::Item(9),
684        ];
685        let got = frames(wrap_progress_stream(stream::iter(steps), "t.m", vec!["t".into()])).await;
686        assert_eq!(
687            got,
688            vec![
689                ("progress", serde_json::json!({"message": "half", "percentage": 50.0})),
690                ("data", serde_json::json!(9)),
691            ]
692        );
693    }
694
695    #[tokio::test]
696    async fn wrap_result_progress_stream_maps_all_three_cases() {
697        let steps: Vec<Result<Progress<u32, String>, String>> = vec![
698            Ok(Progress::Update("step".into())),
699            Ok(Progress::Item(1)),
700            Err("refused".into()),
701        ];
702        let got = frames(wrap_result_progress_stream(
703            stream::iter(steps),
704            "t.m",
705            vec!["t".into()],
706        ))
707        .await;
708        assert_eq!(
709            got,
710            vec![
711                ("progress", serde_json::json!("step")),
712                ("data", serde_json::json!({"ok": 1})),
713                ("data", serde_json::json!({"err": "refused"})),
714            ]
715        );
716    }
717}