icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
//! Framing: a 4-byte little-endian payload length, a 1-byte kind, then the payload.

use std::borrow::Cow;

use serde::{Deserialize, Serialize};

use crate::error::ProtocolError;

/// Bytes before the payload.
pub const HEADER_LEN: usize = 5;

/// The largest payload either end accepts.
pub const MAX_FRAME_BYTES: u64 = 64 * 1024 * 1024;

/// What a frame's payload holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FrameKind {
    /// A JSON message.
    Json,
    /// The attachment announced by the JSON frame before it.
    Binary,
}

impl FrameKind {
    const fn byte(self) -> u8 {
        match self {
            FrameKind::Json => 0,
            FrameKind::Binary => 1,
        }
    }

    fn from_byte(byte: u8) -> Result<Self, ProtocolError> {
        match byte {
            0 => Ok(FrameKind::Json),
            1 => Ok(FrameKind::Binary),
            other => Err(ProtocolError::Malformed(format!(
                "unknown frame kind {other}"
            ))),
        }
    }
}

/// The attachment a JSON frame announces; the binary frame follows it immediately.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
    /// The binary payload's length.
    pub bytes: u64,
    /// Its media type, such as `image/x-rgba`.
    pub media: Cow<'static, str>,
}

/// One frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WireFrame {
    /// What the payload holds.
    pub kind: FrameKind,
    /// The payload.
    pub payload: Vec<u8>,
}

impl WireFrame {
    /// A JSON frame.
    #[must_use]
    pub fn json(payload: Vec<u8>) -> Self {
        Self {
            kind: FrameKind::Json,
            payload,
        }
    }

    /// A binary frame.
    #[must_use]
    pub fn binary(payload: Vec<u8>) -> Self {
        Self {
            kind: FrameKind::Binary,
            payload,
        }
    }

    /// The frame as bytes, header first.
    pub fn encode(&self) -> Result<Vec<u8>, ProtocolError> {
        let length = u64::try_from(self.payload.len()).unwrap_or(u64::MAX);
        let header_length = u32::try_from(length)
            .ok()
            .filter(|_| length <= MAX_FRAME_BYTES)
            .ok_or(ProtocolError::FrameTooLarge(length))?;
        let mut bytes = Vec::with_capacity(HEADER_LEN + self.payload.len());
        bytes.extend_from_slice(&header_length.to_le_bytes());
        bytes.push(self.kind.byte());
        bytes.extend_from_slice(&self.payload);
        Ok(bytes)
    }

    /// Reads a header: the kind and the payload length that follows it.
    pub fn decode_header(header: [u8; HEADER_LEN]) -> Result<(FrameKind, usize), ProtocolError> {
        let [a, b, c, d, kind] = header;
        let length = u32::from_le_bytes([a, b, c, d]);
        if u64::from(length) > MAX_FRAME_BYTES {
            return Err(ProtocolError::FrameTooLarge(u64::from(length)));
        }
        let length =
            usize::try_from(length).map_err(|_| ProtocolError::FrameTooLarge(u64::from(length)))?;
        Ok((FrameKind::from_byte(kind)?, length))
    }

    /// Reads one frame from the front of `bytes`, returning it and how many bytes it took,
    /// or `None` when `bytes` ends before the frame does.
    pub fn decode(bytes: &[u8]) -> Result<Option<(WireFrame, usize)>, ProtocolError> {
        let Some((header, rest)) = bytes.split_first_chunk::<HEADER_LEN>() else {
            return Ok(None);
        };
        let (kind, length) = Self::decode_header(*header)?;
        let Some(payload) = rest.get(..length) else {
            return Ok(None);
        };
        let frame = WireFrame {
            kind,
            payload: payload.to_vec(),
        };
        Ok(Some((frame, HEADER_LEN + length)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn frames_round_trip() -> Result<(), ProtocolError> {
        for frame in [
            WireFrame::json(br#"{"id":1}"#.to_vec()),
            WireFrame::binary(vec![0, 1, 2, 255]),
            WireFrame::json(Vec::new()),
        ] {
            let bytes = frame.encode()?;
            assert_eq!(bytes.len(), HEADER_LEN + frame.payload.len());
            assert_eq!(WireFrame::decode(&bytes)?, Some((frame, bytes.len())));
        }
        Ok(())
    }

    #[test]
    fn a_json_frame_with_its_attachment_decodes_in_order() -> Result<(), ProtocolError> {
        let announce =
            WireFrame::json(br#"{"attachment":{"bytes":3,"media":"image/x-rgba"}}"#.to_vec());
        let attachment = WireFrame::binary(vec![9, 8, 7]);
        let mut stream = announce.encode()?;
        stream.extend(attachment.encode()?);
        let Some((first, used)) = WireFrame::decode(&stream)? else {
            panic!("first frame incomplete");
        };
        assert_eq!(first, announce);
        assert_eq!(
            WireFrame::decode(&stream[used..])?.map(|f| f.0),
            Some(attachment)
        );
        Ok(())
    }

    #[test]
    fn truncated_frames_wait_for_more() -> Result<(), ProtocolError> {
        let bytes = WireFrame::json(b"hello".to_vec()).encode()?;
        for end in 0..bytes.len() {
            assert_eq!(WireFrame::decode(&bytes[..end])?, None, "{end}");
        }
        Ok(())
    }

    #[test]
    fn oversized_and_unknown_frames_are_refused() {
        let too_long = u32::try_from(MAX_FRAME_BYTES + 1).unwrap_or(u32::MAX);
        let [a, b, c, d] = too_long.to_le_bytes();
        assert_eq!(
            WireFrame::decode_header([a, b, c, d, 0]),
            Err(ProtocolError::FrameTooLarge(MAX_FRAME_BYTES + 1))
        );
        assert!(matches!(
            WireFrame::decode_header([0, 0, 0, 0, 7]),
            Err(ProtocolError::Malformed(_))
        ));
    }

    #[test]
    fn attachments_serialise_as_the_plan_shows() -> Result<(), serde_json::Error> {
        let attachment = Attachment {
            bytes: 4,
            media: Cow::Borrowed("image/x-rgba"),
        };
        assert_eq!(
            serde_json::to_string(&attachment)?,
            r#"{"bytes":4,"media":"image/x-rgba"}"#
        );
        Ok(())
    }
}