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 (likewise
16//! `event: error` carries only `{"message", "code"}`, with no `recoverable`).
17//! A client type that made those fields mandatory could therefore not
18//! represent what 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-macros`,
33//! which round-trips every `PlexusStreamItem` variant produced by
34//! `plexus-core` through this type.
35
36use serde::{Deserialize, Serialize};
37use serde_json::Value;
38
39/// Provenance metadata the calling layer stamps onto each item.
40///
41/// Present on the WebSocket JSON-RPC transport; absent over REST + SSE.
42#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
43pub struct StreamMetadata {
44    /// Call path through the system (e.g. `["menger", "tickets"]`).
45    #[serde(default)]
46    pub provenance: Vec<String>,
47    /// Hash of the server's Plexus configuration, for cache invalidation.
48    #[serde(default)]
49    pub plexus_hash: String,
50    /// Unix timestamp (seconds) at which the item was wrapped.
51    #[serde(default)]
52    pub timestamp: i64,
53}
54
55/// One item of a Plexus response stream, as delivered by a [`Transport`].
56///
57/// [`Transport`]: crate::Transport
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59#[serde(tag = "type", rename_all = "snake_case")]
60pub enum StreamItem {
61    /// A payload item. `content` is the activation's own event, still as
62    /// JSON; [`crate::decode`] is what turns it into the method's event type.
63    Data {
64        #[serde(default, skip_serializing_if = "Option::is_none")]
65        metadata: Option<StreamMetadata>,
66        /// e.g. `"tickets.watch"`. Absent over REST + SSE.
67        #[serde(default, skip_serializing_if = "Option::is_none")]
68        content_type: Option<String>,
69        content: Value,
70    },
71
72    /// A progress report. Carries no payload; never terminates the stream.
73    Progress {
74        #[serde(default, skip_serializing_if = "Option::is_none")]
75        metadata: Option<StreamMetadata>,
76        message: String,
77        #[serde(default, skip_serializing_if = "Option::is_none")]
78        percentage: Option<f32>,
79    },
80
81    /// An **in-band** error raised by the hub or the activation — as opposed
82    /// to a [`crate::TransportError`], which is the connection failing.
83    /// Terminates the stream.
84    Error {
85        #[serde(default, skip_serializing_if = "Option::is_none")]
86        metadata: Option<StreamMetadata>,
87        message: String,
88        #[serde(default, skip_serializing_if = "Option::is_none")]
89        code: Option<String>,
90        /// The REST bridge does not emit this field; it defaults to `false`.
91        #[serde(default)]
92        recoverable: bool,
93    },
94
95    /// A server-to-client request (bidirectional activations). The typed
96    /// client has no answer channel, so [`crate::decode`] skips these; a
97    /// consumer that needs them reads the raw [`StreamItem`] stream.
98    #[serde(rename_all = "camelCase")]
99    Request {
100        request_id: String,
101        request_data: Value,
102        #[serde(default)]
103        timeout_ms: u64,
104    },
105
106    /// Normal end of stream.
107    Done {
108        #[serde(default, skip_serializing_if = "Option::is_none")]
109        metadata: Option<StreamMetadata>,
110    },
111}
112
113impl StreamItem {
114    /// Convenience constructor for a data item with no server metadata —
115    /// the shape the REST + SSE bridge produces.
116    pub fn data(content: Value) -> Self {
117        StreamItem::Data {
118            metadata: None,
119            content_type: None,
120            content,
121        }
122    }
123
124    /// Convenience constructor for a terminal `done` item.
125    pub fn done() -> Self {
126        StreamItem::Done { metadata: None }
127    }
128
129    /// `true` for the two variants after which no further item may arrive.
130    pub fn is_terminal(&self) -> bool {
131        matches!(self, StreamItem::Done { .. } | StreamItem::Error { .. })
132    }
133
134    /// The provenance metadata, when the transport carried it.
135    pub fn metadata(&self) -> Option<&StreamMetadata> {
136        match self {
137            StreamItem::Data { metadata, .. }
138            | StreamItem::Progress { metadata, .. }
139            | StreamItem::Error { metadata, .. }
140            | StreamItem::Done { metadata } => metadata.as_ref(),
141            StreamItem::Request { .. } => None,
142        }
143    }
144}