Skip to main content

abyss_plugin_protocol/
message.rs

1//! Version negotiation and broker control wire payloads.
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6/// Broker plugin protocol versions supported by this SDK release.
7#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
8#[non_exhaustive]
9#[serde(try_from = "u16", into = "u16")]
10pub enum PluginProtocolVersion {
11    /// Handshake, live stream, and structured Agent event contract.
12    V1,
13}
14
15impl PluginProtocolVersion {
16    /// Returns the integer carried on the wire.
17    #[must_use]
18    pub const fn wire_value(self) -> u16 {
19        match self {
20            Self::V1 => 1,
21        }
22    }
23}
24
25impl From<PluginProtocolVersion> for u16 {
26    fn from(version: PluginProtocolVersion) -> Self {
27        version.wire_value()
28    }
29}
30
31impl TryFrom<u16> for PluginProtocolVersion {
32    type Error = UnsupportedPluginProtocolVersion;
33
34    fn try_from(version: u16) -> Result<Self, Self::Error> {
35        match version {
36            1 => Ok(Self::V1),
37            version => Err(UnsupportedPluginProtocolVersion { version }),
38        }
39    }
40}
41
42/// An unsupported broker plugin protocol version received from the wire.
43#[derive(Debug, Error)]
44#[error("unsupported broker plugin protocol version {version}")]
45pub struct UnsupportedPluginProtocolVersion {
46    version: u16,
47}
48
49impl UnsupportedPluginProtocolVersion {
50    /// Returns the unsupported integer received from the peer.
51    #[must_use]
52    pub const fn version(&self) -> u16 {
53        self.version
54    }
55}
56
57/// Initial handshake sent from a plugin process to `abyss-broker`.
58#[derive(Debug, Deserialize, Serialize)]
59#[serde(deny_unknown_fields)]
60pub struct PluginHello {
61    /// Plugin protocol version requested by the plugin.
62    pub protocol_version: PluginProtocolVersion,
63    /// Stable identity used to describe this plugin connection.
64    pub plugin_id: String,
65    /// Capabilities enabled for this connection.
66    pub capabilities: Vec<crate::inspection::PluginCapability>,
67}
68
69impl PluginHello {
70    /// Creates a version 1 plugin handshake.
71    #[must_use]
72    pub fn new(plugin_id: String) -> Self {
73        Self {
74            protocol_version: PluginProtocolVersion::V1,
75            plugin_id,
76            capabilities: vec![crate::inspection::PluginCapability::AgentEvents],
77        }
78    }
79}
80
81/// Current plugin-to-broker messages on the shared connection.
82#[derive(Debug, Deserialize, Serialize)]
83#[serde(tag = "type", rename_all = "snake_case")]
84#[non_exhaustive]
85pub enum PluginMessage {
86    /// Initial session handshake.
87    PluginHello(PluginHello),
88    /// Correlated request decision.
89    InspectResponse(crate::inspection::InspectResponse),
90}
91
92/// Current broker-to-plugin messages on the shared connection.
93#[derive(Debug, Deserialize, Serialize)]
94#[serde(tag = "type", rename_all = "snake_case")]
95#[non_exhaustive]
96pub enum BrokerMessage {
97    /// Accepted session handshake.
98    BrokerHello(BrokerHello),
99    /// Rejected session handshake.
100    BrokerError(BrokerError),
101    /// Final session frame.
102    BrokerClose(BrokerClose),
103    /// Independent observation event.
104    AgentEvent {
105        /// Normalized event.
106        event: std::sync::Arc<crate::event::AgentEvent>,
107    },
108    /// Full request awaiting a decision before forwarding.
109    InspectRequest {
110        /// Parsed and raw request context.
111        context: std::sync::Arc<crate::inspection::AgentRequestContext>,
112    },
113}
114
115/// Handshake response sent from `abyss-broker` to one plugin process.
116#[derive(Debug, Deserialize, Serialize)]
117#[serde(deny_unknown_fields)]
118pub struct BrokerHello {
119    /// Plugin protocol version confirmed by the broker.
120    pub protocol_version: PluginProtocolVersion,
121}
122
123impl BrokerHello {
124    /// Creates a version 1 broker handshake response.
125    #[must_use]
126    pub const fn v1() -> Self {
127        Self {
128            protocol_version: PluginProtocolVersion::V1,
129        }
130    }
131}
132
133/// Handshake rejection sent as the broker's first response frame.
134#[derive(Debug, Deserialize, Serialize)]
135#[serde(deny_unknown_fields)]
136pub struct BrokerError {
137    /// Stable rejection code interpreted in the handshake phase.
138    pub code: u32,
139    /// Human-readable rejection reason suitable for diagnostics.
140    pub reason: String,
141}
142
143/// Deliberate final frame sent before the broker closes an accepted session.
144#[derive(Debug, Deserialize, Serialize)]
145#[serde(deny_unknown_fields)]
146pub struct BrokerClose {
147    /// Stable close code interpreted after a successful handshake.
148    pub code: u32,
149    /// Human-readable close reason suitable for diagnostics.
150    pub reason: String,
151}
152
153/// Stable handshake rejection meanings defined by protocol version 1.
154#[derive(Clone, Copy, Debug)]
155#[non_exhaustive]
156pub enum BrokerErrorCode {
157    /// The requested protocol version is not supported.
158    UnsupportedProtocolVersion,
159    /// The first frame is malformed or contains an invalid plugin identifier.
160    InvalidHandshake,
161    /// The broker cannot accept another plugin session.
162    ResourceLimit,
163}
164
165impl BrokerErrorCode {
166    /// Returns the integer carried in a `BrokerError` frame.
167    #[must_use]
168    pub const fn wire_value(self) -> u32 {
169        match self {
170            Self::UnsupportedProtocolVersion => 1,
171            Self::InvalidHandshake => 2,
172            Self::ResourceLimit => 3,
173        }
174    }
175}
176
177/// Stable deliberate-close meanings defined by protocol version 1.
178#[derive(Clone, Copy, Debug)]
179#[non_exhaustive]
180pub enum BrokerCloseCode {
181    /// The broker is shutting down normally.
182    BrokerShutdown,
183    /// The plugin fell behind the bounded live event stream.
184    EventStreamTooSlow,
185}
186
187impl BrokerCloseCode {
188    /// Returns the integer carried in a `BrokerClose` frame.
189    #[must_use]
190    pub const fn wire_value(self) -> u32 {
191        match self {
192            Self::BrokerShutdown => 100,
193            Self::EventStreamTooSlow => 101,
194        }
195    }
196}
197
198impl BrokerError {
199    /// Creates a typed version 1 handshake rejection payload.
200    #[must_use]
201    pub fn new<T>(code: BrokerErrorCode, reason: T) -> Self
202    where
203        T: Into<String>,
204    {
205        Self {
206            code: code.wire_value(),
207            reason: reason.into(),
208        }
209    }
210}
211
212impl BrokerClose {
213    /// Creates a typed version 1 deliberate-close payload.
214    #[must_use]
215    pub fn new<T>(code: BrokerCloseCode, reason: T) -> Self
216    where
217        T: Into<String>,
218    {
219        Self {
220            code: code.wire_value(),
221            reason: reason.into(),
222        }
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use serde_json::json;
229
230    use super::{
231        BrokerClose, BrokerError, BrokerHello, BrokerMessage, PluginHello, PluginMessage,
232        PluginProtocolVersion,
233    };
234
235    #[test]
236    fn unsupported_protocol_version_is_rejected() {
237        let error = serde_json::from_value::<PluginProtocolVersion>(json!(2_u16))
238            .expect_err("protocol version 2 must be rejected");
239
240        assert!(
241            error
242                .to_string()
243                .contains("unsupported broker plugin protocol version 2"),
244            "error should identify the unsupported protocol version"
245        );
246    }
247
248    #[test]
249    fn handshake_frames_have_explicit_tags() {
250        let plugin_hello = serde_json::to_value(PluginMessage::PluginHello(PluginHello::new(
251            "sample-plugin".to_owned(),
252        )))
253        .expect("plugin hello should serialize");
254        let broker_hello = serde_json::to_value(BrokerMessage::BrokerHello(BrokerHello::v1()))
255            .expect("broker hello should serialize");
256
257        assert_eq!(plugin_hello["type"], "plugin_hello");
258        assert_eq!(broker_hello["type"], "broker_hello");
259        assert_eq!(
260            plugin_hello["capabilities"],
261            serde_json::json!(["agent_events"])
262        );
263        assert_eq!(
264            plugin_hello["protocol_version"], 1_u16,
265            "hello must request v1"
266        );
267        assert_eq!(
268            plugin_hello["plugin_id"], "sample-plugin",
269            "plugin id must be stable"
270        );
271        assert_eq!(
272            broker_hello["protocol_version"], 1_u16,
273            "broker hello must confirm plugin protocol v1"
274        );
275    }
276
277    #[test]
278    fn broker_control_frames_have_explicit_tags() {
279        let broker_error = serde_json::to_value(BrokerMessage::BrokerError(BrokerError {
280            code: 1,
281            reason: "unsupported protocol version".to_owned(),
282        }))
283        .expect("broker error should serialize");
284        let broker_close = serde_json::to_value(BrokerMessage::BrokerClose(BrokerClose {
285            code: 101,
286            reason: "plugin event stream is too slow".to_owned(),
287        }))
288        .expect("broker close should serialize");
289
290        assert_eq!(broker_error["type"], "broker_error");
291        assert_eq!(broker_error["code"], 1_u32);
292        assert_eq!(broker_error["reason"], "unsupported protocol version");
293        assert_eq!(broker_close["type"], "broker_close");
294        assert_eq!(broker_close["code"], 101_u32);
295        assert_eq!(broker_close["reason"], "plugin event stream is too slow");
296    }
297}