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