Skip to main content

plexus_client/
envelope.rs

1//! The Plexus wire envelope, as a **client** sees it.
2//!
3//! # Why this is not `plexus_core::plexus::types::PlexusStreamItem`
4//!
5//! The server-side envelope requires `metadata` on every non-`Request`
6//! variant, and the WebSocket JSON-RPC transport does deliver it. The REST
7//! bridge does **not**: `stream_sse_response` re-frames each item and emits
8//! only
9//!
10//! ```text
11//! event: data
12//! data: {"content": <event JSON>}
13//! ```
14//!
15//! — dropping `metadata` and `content_type` entirely (and a REST unary
16//! body carries an error's `RemoteError` with no `recoverable`). A client
17//! type that made those fields mandatory could therefore not represent what
18//! the REST transport actually receives.
19//!
20//! So [`StreamItem`] is deliberately the **looser** type: every field the
21//! REST bridge drops is `Option` / `#[serde(default)]`. It deserializes the
22//! full WebSocket envelope losslessly, *and* an SSE transport can construct
23//! the same type from an `(event-name, data-payload)` pair — which is what
24//! makes one typed client work over both transports.
25//!
26//! (An SSE `data:` payload is not itself a `StreamItem`: the discriminant
27//! lives in the frame's `event:` field, not in the JSON. Reassembling the
28//! two is the SSE transport's job; this type is the target shape it
29//! reassembles *into*.)
30//!
31//! Wire compatibility with the server envelope is a regression gate, not an
32//! assumption — see `tests/client_envelope_compat.rs` in `plexus-core`,
33//! which round-trips every `PlexusStreamItem` 0.7 frame produced by
34//! `plexus-core` through this type, byte for byte.
35//!
36//! # 0.7 (RETURNS-6)
37//!
38//! The progress frame carries the method's typed progress value as
39//! `content` (beside the call's `content_type`, as a data frame does); the
40//! error frame carries a typed [`RemoteError`] — beside spec/05's
41//! `message`, `code` and flattened `error_kind` fields, which main's typed
42//! refusals (AUTH-2, POLYGLOT-5) put there and RETURNS-36 kept.
43
44use serde::de::DeserializeOwned;
45use serde::{Deserialize, Serialize};
46use serde_json::value::RawValue;
47use serde_json::Value;
48use std::sync::Arc;
49
50use crate::remote_error::RemoteError;
51
52/// Provenance metadata the calling layer stamps onto each item.
53///
54/// Present on the WebSocket JSON-RPC transport; absent over REST + SSE.
55#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
56pub struct StreamMetadata {
57    /// Call path through the system (e.g. `["menger", "tickets"]`).
58    #[serde(default)]
59    pub provenance: Vec<String>,
60    /// Hash of the server's Plexus configuration, for cache invalidation.
61    #[serde(default)]
62    pub plexus_hash: String,
63    /// Unix timestamp (seconds) at which the item was wrapped.
64    #[serde(default)]
65    pub timestamp: i64,
66}
67
68/// One item of a Plexus response stream, as delivered by a [`Transport`].
69///
70/// [`Transport`]: crate::Transport
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72#[serde(tag = "type", rename_all = "snake_case")]
73pub enum StreamItem {
74    /// A payload item. `content` is the activation's own event, still as
75    /// JSON; [`crate::decode`] is what turns it into the method's event type.
76    Data {
77        #[serde(default, skip_serializing_if = "Option::is_none")]
78        metadata: Option<StreamMetadata>,
79        /// e.g. `"tickets.watch"`. Absent over REST + SSE.
80        #[serde(default, skip_serializing_if = "Option::is_none")]
81        content_type: Option<String>,
82        content: Value,
83    },
84
85    /// A progress report: the method's progress value `P` as JSON
86    /// (`{"message", "percentage"}` for the default [`crate::Note`]). Never
87    /// terminates the stream.
88    Progress {
89        #[serde(default, skip_serializing_if = "Option::is_none")]
90        metadata: Option<StreamMetadata>,
91        /// e.g. `"tickets.import"` — the call's method, as on its data
92        /// items. Optional for the same reason `Data`'s is.
93        #[serde(default, skip_serializing_if = "Option::is_none")]
94        content_type: Option<String>,
95        content: Value,
96    },
97
98    /// An **in-band** call failure reported by the service — as opposed to a
99    /// [`crate::TransportError`], which is the connection failing. Typed:
100    /// its [`RemoteError`]'s `Display` is the human line. Terminates the
101    /// stream.
102    Error {
103        #[serde(default, skip_serializing_if = "Option::is_none")]
104        metadata: Option<StreamMetadata>,
105        /// A REST unary body carries no `recoverable`; it defaults to
106        /// `false`.
107        #[serde(default)]
108        recoverable: bool,
109        /// spec/05's human line (never parsed for meaning). Absent from a
110        /// REST unary body.
111        #[serde(default, skip_serializing_if = "Option::is_none")]
112        message: Option<String>,
113        /// spec/05's code: the JSON-RPC code in decimal, or the refusal's
114        /// kind.
115        #[serde(default, skip_serializing_if = "Option::is_none")]
116        code: Option<String>,
117        /// RETURNS-6: why the call failed, typed — what a typed client
118        /// decodes.
119        error: RemoteError,
120        /// spec/05's flattened fields beside the others (`error_kind`,
121        /// `grant`, `scope`, `roles`, `held_on`, `max`, …), kept whole.
122        #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
123        fields: serde_json::Map<String, Value>,
124    },
125
126    /// A server-to-client request (bidirectional activations). The typed
127    /// client has no answer channel, so [`crate::decode`] skips these; a
128    /// consumer that needs them reads the raw [`StreamItem`] stream.
129    #[serde(rename_all = "camelCase")]
130    Request {
131        request_id: String,
132        request_data: Value,
133        #[serde(default)]
134        timeout_ms: u64,
135    },
136
137    /// Normal end of stream.
138    Done {
139        #[serde(default, skip_serializing_if = "Option::is_none")]
140        metadata: Option<StreamMetadata>,
141    },
142}
143
144impl StreamItem {
145    /// Convenience constructor for a data item with no server metadata —
146    /// the shape the REST + SSE bridge produces.
147    pub fn data(content: Value) -> Self {
148        StreamItem::Data {
149            metadata: None,
150            content_type: None,
151            content,
152        }
153    }
154
155    /// Convenience constructor for a terminal `done` item.
156    pub fn done() -> Self {
157        StreamItem::Done { metadata: None }
158    }
159
160    /// `true` for the two variants after which no further item may arrive.
161    pub fn is_terminal(&self) -> bool {
162        matches!(self, StreamItem::Done { .. } | StreamItem::Error { .. })
163    }
164
165    /// The provenance metadata, when the transport carried it.
166    pub fn metadata(&self) -> Option<&StreamMetadata> {
167        match self {
168            StreamItem::Data { metadata, .. }
169            | StreamItem::Progress { metadata, .. }
170            | StreamItem::Error { metadata, .. }
171            | StreamItem::Done { metadata } => metadata.as_ref(),
172            StreamItem::Request { .. } => None,
173        }
174    }
175}
176
177/// An item's content as a typed client reads it (PERF.115-36): the JSON text
178/// the wire carried, decoded straight into the method's event when it is
179/// read, never into a [`Value`] first. A transport that has no text (one in
180/// process, a script) hands over the `Value` it holds.
181#[derive(Debug, Clone)]
182pub struct Content(Repr);
183
184#[derive(Debug, Clone)]
185enum Repr {
186    Text(Box<RawValue>),
187    Value(Value),
188    /// The whole notification the item came in, its content at
189    /// `params.result.content`, which is read only when it is decoded: once,
190    /// straight into the event. Where the reader found it by the frame's
191    /// bytes, its span, which is decoded alone first. Only a WebSocket reader
192    /// makes one.
193    #[cfg_attr(not(any(feature = "ws-native", feature = "ws-web")), allow(dead_code))]
194    Frame(Box<str>, Option<(usize, usize)>),
195}
196
197/// A notification read for its item's content alone; everything else in it
198/// is passed over.
199#[derive(Deserialize)]
200struct InFrame<C> {
201    params: InParams<C>,
202}
203
204#[derive(Deserialize)]
205struct InParams<C> {
206    result: InItem<C>,
207}
208
209#[derive(Deserialize)]
210struct InItem<C> {
211    content: C,
212}
213
214impl Content {
215    /// A data item's content inside its whole notification (`text`), read
216    /// when it is decoded; at `span`, where the reader found it there.
217    #[cfg_attr(not(any(feature = "ws-native", feature = "ws-web")), allow(dead_code))]
218    pub(crate) fn frame(text: &str, span: Option<std::ops::Range<usize>>) -> Self {
219        Content(Repr::Frame(text.into(), span.map(|s| (s.start, s.end))))
220    }
221
222    /// Whether the content is still inside its whole notification, and
223    /// whether the reader said where.
224    #[cfg(test)]
225    pub(crate) fn in_frame(&self) -> Option<bool> {
226        match self.0 {
227            Repr::Frame(_, span) => Some(span.is_some()),
228            _ => None,
229        }
230    }
231
232    /// The JSON text the wire carried, when the transport kept it.
233    pub fn as_text(&self) -> Option<&str> {
234        match &self.0 {
235            Repr::Text(text) => Some(text.get()),
236            Repr::Value(_) => None,
237            Repr::Frame(frame, _) => serde_json::from_str::<InFrame<&RawValue>>(frame).ok().map(|f| f.params.result.content.get()),
238        }
239    }
240
241    /// The content decoded into `E`: from the text, or from the `Value`.
242    pub fn decode<E: DeserializeOwned>(self) -> Result<E, serde_json::Error> {
243        match self.0 {
244            Repr::Text(text) => serde_json::from_str(text.get()),
245            Repr::Value(value) => serde_json::from_value(value),
246            Repr::Frame(frame, span) => {
247                // The span is where the content begins and the frame's three
248                // closing braces; it is the content alone, or no one value,
249                // which the frame's own reading answers.
250                if let Some(event) = span.and_then(|(start, end)| serde_json::from_str(&frame[start..end]).ok()) {
251                    return Ok(event);
252                }
253                serde_json::from_str::<InFrame<E>>(&frame).map(|f| f.params.result.content)
254            }
255        }
256    }
257
258    /// The content as a `Value`, for a caller that wants one.
259    pub fn into_value(self) -> Result<Value, serde_json::Error> {
260        match self.0 {
261            Repr::Text(text) => serde_json::from_str(text.get()),
262            Repr::Value(value) => Ok(value),
263            Repr::Frame(..) => self.decode(),
264        }
265    }
266}
267
268impl From<Box<RawValue>> for Content {
269    fn from(text: Box<RawValue>) -> Self {
270        Content(Repr::Text(text))
271    }
272}
273
274impl From<Value> for Content {
275    fn from(value: Value) -> Self {
276        Content(Repr::Value(value))
277    }
278}
279
280/// One item of a response stream as a typed client reads it (PERF.115-36):
281/// a [`StreamItem`] whose content is still the wire's JSON ([`Content`]), and
282/// nothing read that a typed decode does not use: no metadata, no request's
283/// data. [`Transport::call_raw`](crate::Transport::call_raw) yields these and
284/// [`decode_raw`](crate::decode_raw) turns them into events; a consumer that
285/// wants the metadata, or answers requests, reads [`StreamItem`]s.
286#[derive(Debug, Clone)]
287pub enum RawItem {
288    /// A payload item: its content, and its `content_type`, which every item
289    /// of a call shares.
290    Data {
291        content_type: Option<Arc<str>>,
292        content: Content,
293    },
294    /// A progress report: the method's progress value `P` (a [`Content`],
295    /// decoded when an opted-in caller reads it), its `content_type` the
296    /// call's. Never terminates the stream.
297    Progress {
298        content_type: Option<Arc<str>>,
299        content: Content,
300    },
301    /// The call failed: its typed [`RemoteError`] (RETURNS-6), beside
302    /// spec/05's `message` and `code`. Terminates the stream.
303    Error {
304        message: Option<String>,
305        code: Option<String>,
306        recoverable: bool,
307        error: Box<RemoteError>,
308    },
309    /// A server-to-client request. A typed client has no answer channel and
310    /// skips it.
311    Request,
312    /// Normal end of stream.
313    Done,
314}
315
316impl RawItem {
317    /// `true` for the two variants after which no further item may arrive.
318    pub fn is_terminal(&self) -> bool {
319        matches!(self, RawItem::Done | RawItem::Error { .. })
320    }
321}
322
323impl From<StreamItem> for RawItem {
324    fn from(item: StreamItem) -> Self {
325        match item {
326            StreamItem::Data { content_type, content, .. } => RawItem::Data {
327                content_type: content_type.map(Arc::from),
328                content: content.into(),
329            },
330            StreamItem::Progress { content_type, content, .. } => RawItem::Progress {
331                content_type: content_type.map(Arc::from),
332                content: content.into(),
333            },
334            StreamItem::Error { message, code, recoverable, error, .. } => RawItem::Error {
335                message,
336                code,
337                recoverable,
338                error: Box::new(error),
339            },
340            StreamItem::Request { .. } => RawItem::Request,
341            StreamItem::Done { .. } => RawItem::Done,
342        }
343    }
344}