Skip to main content

crisol_core/protocol/
mod.rs

1//! The transport-agnostic host protocol.
2//!
3//! Messages are JSON documents. On a byte stream they are length-prefixed with a
4//! four-byte big-endian length, so the same frames travel over stdio, a socket, or a
5//! WebSocket binary message. The protocol is versioned and rejects a newer version.
6//!
7//! ```
8//! use crisol_core::protocol;
9//! ```
10
11pub mod data_buffer;
12pub mod events;
13pub use data_buffer::{BufferColumn, DataBuffer, dataset_from_columns};
14pub use events::HostEvent;
15
16use std::io::{Read, Write};
17
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20
21use crate::spec::Patch;
22
23/// The protocol version understood by this host.
24/// # Example
25///
26/// ```
27/// use crisol_core::protocol::PROTOCOL_VERSION;
28/// ```
29pub const PROTOCOL_VERSION: u32 = 1;
30
31/// One protocol message.
32#[derive(Clone, Debug, Serialize, Deserialize)]
33#[serde(tag = "type", rename_all = "snake_case")]
34#[non_exhaustive]
35/// # Example
36///
37/// ```
38/// use crisol_core::protocol::Message;
39/// ```
40pub enum Message {
41    /// First message on a connection.
42    Hello {
43        /// Protocol version.
44        version: u32,
45        /// Capabilities, such as `data` or `patches`.
46        capabilities: Vec<String>,
47    },
48    /// A request with a correlation id.
49    Request {
50        /// Correlation id.
51        id: u64,
52        /// The request.
53        request: Request,
54    },
55    /// A response to a request.
56    Response {
57        /// Correlation id.
58        id: u64,
59        /// The response.
60        response: Response,
61    },
62    /// An event emitted by the host.
63    Event {
64        /// The event.
65        event: HostEvent,
66    },
67    /// A patch without a request id.
68    Patch {
69        /// The patch.
70        patch: Patch,
71    },
72    /// A data buffer (large columns; a binary transport may carry it out of band).
73    Data {
74        /// Dataset name.
75        name: String,
76        /// Columns.
77        columns: Vec<BufferColumn>,
78    },
79    /// An error frame.
80    Error {
81        /// Human-readable message.
82        message: String,
83    },
84}
85
86/// A host request.
87#[derive(Clone, Debug, Serialize, Deserialize)]
88#[serde(tag = "op", rename_all = "snake_case")]
89#[non_exhaustive]
90/// # Example
91///
92/// ```
93/// use crisol_core::protocol::Request;
94/// ```
95pub enum Request {
96    /// Apply a patch.
97    ApplyPatch {
98        /// The patch.
99        patch: Patch,
100    },
101    /// Read the current spec.
102    GetSpec,
103    /// Run a command by id.
104    RunCommand {
105        /// Command id.
106        id: String,
107    },
108    /// Replace a named dataset.
109    SetData {
110        /// Dataset name.
111        name: String,
112        /// Columns.
113        columns: Vec<BufferColumn>,
114    },
115    /// Reload the spec from its path.
116    Reload,
117}
118
119/// A host response.
120#[derive(Clone, Debug, Serialize, Deserialize)]
121#[serde(tag = "result", rename_all = "snake_case")]
122#[non_exhaustive]
123/// # Example
124///
125/// ```
126/// use crisol_core::protocol::Response;
127/// ```
128pub enum Response {
129    /// The current spec.
130    Spec {
131        /// Spec JSON.
132        spec: Value,
133    },
134    /// Events produced by the operation.
135    Events {
136        /// Events.
137        events: Vec<HostEvent>,
138    },
139    /// Success with no payload.
140    Ok,
141    /// An error.
142    Error {
143        /// Human-readable message.
144        message: String,
145    },
146    /// The generated JSON Schema.
147    Schema {
148        /// Schema JSON.
149        schema: Value,
150    },
151}
152
153/// Why a protocol message could not be decoded or accepted.
154#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
155#[non_exhaustive]
156/// # Example
157///
158/// ```
159/// use crisol_core::protocol::ProtocolError;
160/// ```
161pub enum ProtocolError {
162    /// Malformed JSON.
163    #[error("invalid protocol JSON: {0}")]
164    Json(String),
165    /// A newer protocol version.
166    #[error("unsupported protocol version {0}")]
167    UnsupportedVersion(u32),
168    /// A frame is too large.
169    #[error("frame of {0} bytes is too large")]
170    FrameTooLarge(usize),
171}
172
173impl Message {
174    /// Encode as compact JSON.
175    ///
176    /// # Errors
177    /// When serialization fails (it does not for these types).
178    pub fn encode(&self) -> Result<String, ProtocolError> {
179        serde_json::to_string(self).map_err(|error| ProtocolError::Json(error.to_string()))
180    }
181
182    /// Decode JSON and validate the protocol version.
183    ///
184    /// # Errors
185    /// When the JSON is malformed or the message claims a newer version.
186    pub fn decode(json: &str) -> Result<Self, ProtocolError> {
187        let message: Self = serde_json::from_str(json).map_err(|error| ProtocolError::Json(error.to_string()))?;
188        if let Self::Hello { version, .. } = message
189            && version > PROTOCOL_VERSION
190        {
191            return Err(ProtocolError::UnsupportedVersion(version));
192        }
193        Ok(message)
194    }
195}
196
197/// A framed read or write error.
198#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
199#[non_exhaustive]
200/// # Example
201///
202/// ```
203/// use crisol_core::protocol::FrameError;
204/// ```
205pub enum FrameError {
206    /// The underlying stream failed.
207    #[error("{0}")]
208    Io(String),
209    /// The peer closed the stream cleanly before a new frame began.
210    #[error("the stream was closed")]
211    Closed,
212    /// The payload was not valid JSON or protocol.
213    #[error(transparent)]
214    Protocol(ProtocolError),
215}
216
217/// Largest frame accepted by [`read_frame`].
218const MAX_FRAME_BYTES: usize = 64 * 1024 * 1024;
219
220/// Write one length-prefixed frame.
221///
222/// # Errors
223/// When encoding or writing fails.
224/// # Example
225///
226/// ```
227/// use crisol_core::protocol::write_frame;
228/// ```
229pub fn write_frame(mut writer: impl Write, message: &Message) -> Result<(), FrameError> {
230    let json = message.encode().map_err(FrameError::Protocol)?;
231    let length =
232        u32::try_from(json.len()).map_err(|_| FrameError::Protocol(ProtocolError::FrameTooLarge(json.len())))?;
233    writer
234        .write_all(&length.to_be_bytes())
235        .and_then(|()| writer.write_all(json.as_bytes()))
236        .and_then(|()| writer.flush())
237        .map_err(|error| FrameError::Io(error.to_string()))
238}
239
240/// Read one length-prefixed frame.
241///
242/// # Errors
243/// When reading, decoding, or validating fails.
244/// # Example
245///
246/// ```
247/// use crisol_core::protocol::read_frame;
248/// ```
249pub fn read_frame(mut reader: impl Read) -> Result<Message, FrameError> {
250    let mut length = [0u8; 4];
251    match reader.read_exact(&mut length) {
252        Ok(()) => {}
253        // `read_exact` reports a clean end of stream as `UnexpectedEof`; the message text
254        // is not stable, so match on the kind.
255        Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => return Err(FrameError::Closed),
256        Err(error) => return Err(FrameError::Io(error.to_string())),
257    }
258    let length = u32::from_be_bytes(length) as usize;
259    if length > MAX_FRAME_BYTES {
260        return Err(FrameError::Protocol(ProtocolError::FrameTooLarge(length)));
261    }
262    // Grow with the bytes that arrive instead of reserving the announced length.
263    let mut bytes = Vec::new();
264    let read = reader
265        .take(length as u64)
266        .read_to_end(&mut bytes)
267        .map_err(|error| FrameError::Io(error.to_string()))?;
268    if read != length {
269        return Err(FrameError::Io("the frame ended early".to_owned()));
270    }
271    let json =
272        String::from_utf8(bytes).map_err(|error| FrameError::Protocol(ProtocolError::Json(error.to_string())))?;
273    Message::decode(&json).map_err(FrameError::Protocol)
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn messages_round_trip_and_versions_are_checked() {
282        let message = Message::Hello {
283            version: PROTOCOL_VERSION,
284            capabilities: vec!["patches".to_owned()],
285        };
286        let json = message.encode().expect("encode");
287        let back = Message::decode(&json).expect("decode");
288        assert_eq!(back.encode().expect("encode"), json);
289        let newer = r#"{"type":"hello","version":99,"capabilities":[]}"#;
290        assert!(matches!(
291            Message::decode(newer),
292            Err(ProtocolError::UnsupportedVersion(99))
293        ));
294    }
295
296    #[test]
297    fn frames_round_trip() {
298        let message = Message::Response {
299            id: 7,
300            response: Response::Ok,
301        };
302        let mut bytes = Vec::new();
303        write_frame(&mut bytes, &message).expect("write");
304        let back = read_frame(std::io::Cursor::new(bytes)).expect("read");
305        assert_eq!(back.encode().expect("encode"), message.encode().expect("encode"));
306    }
307}