| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use std::io; |
|
|
| |
| |
| |
|
|
| |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| #[repr(u8)] |
| pub enum StreamType { |
| |
| ToolRpc = 0x01, |
| |
| ChatText = 0x02, |
| |
| VoiceAudio = 0x03, |
| |
| PipelineTask = 0x04, |
| |
| PipelineResult = 0x05, |
| |
| BrainSync = 0x06, |
| |
| WeightSync = 0x07, |
| |
| Control = 0x08, |
| } |
|
|
| impl StreamType { |
| |
| pub fn from_byte(b: u8) -> Option<Self> { |
| match b { |
| 0x01 => Some(Self::ToolRpc), |
| 0x02 => Some(Self::ChatText), |
| 0x03 => Some(Self::VoiceAudio), |
| 0x04 => Some(Self::PipelineTask), |
| 0x05 => Some(Self::PipelineResult), |
| 0x06 => Some(Self::BrainSync), |
| 0x07 => Some(Self::WeightSync), |
| 0x08 => Some(Self::Control), |
| _ => None, |
| } |
| } |
|
|
| |
| pub fn as_byte(self) -> u8 { |
| self as u8 |
| } |
|
|
| |
| pub fn name(self) -> &'static str { |
| match self { |
| Self::ToolRpc => "TOOL_RPC", |
| Self::ChatText => "CHAT_TEXT", |
| Self::VoiceAudio => "VOICE_AUDIO", |
| Self::PipelineTask => "PIPELINE_TASK", |
| Self::PipelineResult => "PIPELINE_RESULT", |
| Self::BrainSync => "BRAIN_SYNC", |
| Self::WeightSync => "WEIGHT_SYNC", |
| Self::Control => "CONTROL", |
| } |
| } |
|
|
| |
| pub fn is_realtime(self) -> bool { |
| matches!(self, Self::VoiceAudio | Self::ChatText | Self::Control) |
| } |
|
|
| |
| pub fn is_bulk(self) -> bool { |
| matches!(self, Self::BrainSync | Self::WeightSync | Self::PipelineTask | Self::PipelineResult) |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| pub const MAX_FRAME_SIZE: u32 = 10_485_760; |
|
|
| |
| pub const FRAME_HEADER_SIZE: usize = 5; |
|
|
| |
| #[derive(Debug, Clone)] |
| pub struct Frame { |
| |
| pub stream_type: StreamType, |
| |
| pub payload: Vec<u8>, |
| } |
|
|
| impl Frame { |
| |
| pub fn new(stream_type: StreamType, payload: Vec<u8>) -> Self { |
| Self { stream_type, payload } |
| } |
|
|
| |
| pub fn tool_rpc(json: &str) -> Self { |
| Self::new(StreamType::ToolRpc, json.as_bytes().to_vec()) |
| } |
|
|
| |
| pub fn chat(text: &str) -> Self { |
| Self::new(StreamType::ChatText, text.as_bytes().to_vec()) |
| } |
|
|
| |
| pub fn control(json: &str) -> Self { |
| Self::new(StreamType::Control, json.as_bytes().to_vec()) |
| } |
|
|
| |
| pub fn pipeline_task(payload: Vec<u8>) -> Self { |
| Self::new(StreamType::PipelineTask, payload) |
| } |
|
|
| |
| pub fn pipeline_result(payload: Vec<u8>) -> Self { |
| Self::new(StreamType::PipelineResult, payload) |
| } |
|
|
| |
| pub fn to_bytes(&self) -> Vec<u8> { |
| let len = self.payload.len() as u32; |
| let mut buf = Vec::with_capacity(FRAME_HEADER_SIZE + self.payload.len()); |
| buf.push(self.stream_type.as_byte()); |
| buf.extend_from_slice(&len.to_be_bytes()); |
| buf.extend_from_slice(&self.payload); |
| buf |
| } |
|
|
| |
| pub fn payload_str(&self) -> Result<&str, std::str::Utf8Error> { |
| std::str::from_utf8(&self.payload) |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| pub fn read_frame(reader: &mut dyn io::Read) -> io::Result<Option<Frame>> { |
| |
| let mut header = [0u8; FRAME_HEADER_SIZE]; |
| match reader.read_exact(&mut header) { |
| Ok(()) => {}, |
| Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None), |
| Err(e) => return Err(e), |
| } |
|
|
| let type_byte = header[0]; |
| let length = u32::from_be_bytes([header[1], header[2], header[3], header[4]]); |
|
|
| |
| let stream_type = StreamType::from_byte(type_byte).ok_or_else(|| { |
| io::Error::new(io::ErrorKind::InvalidData, format!("Unknown stream type: 0x{:02x}", type_byte)) |
| })?; |
|
|
| |
| if length > MAX_FRAME_SIZE { |
| return Err(io::Error::new( |
| io::ErrorKind::InvalidData, |
| format!("Frame too large: {} bytes (max {})", length, MAX_FRAME_SIZE), |
| )); |
| } |
|
|
| |
| let mut payload = vec![0u8; length as usize]; |
| reader.read_exact(&mut payload)?; |
|
|
| Ok(Some(Frame { stream_type, payload })) |
| } |
|
|
| |
| pub fn write_frame(writer: &mut dyn io::Write, frame: &Frame) -> io::Result<()> { |
| let len = frame.payload.len(); |
| if len > MAX_FRAME_SIZE as usize { |
| return Err(io::Error::new( |
| io::ErrorKind::InvalidInput, |
| format!("Frame payload too large: {} bytes (max {})", len, MAX_FRAME_SIZE), |
| )); |
| } |
|
|
| writer.write_all(&[frame.stream_type.as_byte()])?; |
| writer.write_all(&(len as u32).to_be_bytes())?; |
| writer.write_all(&frame.payload)?; |
| writer.flush()?; |
| Ok(()) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| pub fn parse_frame(buf: &[u8]) -> Result<Option<(Frame, usize)>, io::Error> { |
| if buf.len() < FRAME_HEADER_SIZE { |
| return Ok(None); |
| } |
|
|
| let type_byte = buf[0]; |
| let length = u32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]); |
|
|
| let stream_type = StreamType::from_byte(type_byte).ok_or_else(|| { |
| io::Error::new(io::ErrorKind::InvalidData, format!("Unknown stream type: 0x{:02x}", type_byte)) |
| })?; |
|
|
| if length > MAX_FRAME_SIZE { |
| return Err(io::Error::new( |
| io::ErrorKind::InvalidData, |
| format!("Frame too large: {} bytes (max {})", length, MAX_FRAME_SIZE), |
| )); |
| } |
|
|
| let total_len = FRAME_HEADER_SIZE + length as usize; |
| if buf.len() < total_len { |
| return Ok(None); |
| } |
|
|
| let payload = buf[FRAME_HEADER_SIZE..total_len].to_vec(); |
| Ok(Some((Frame { stream_type, payload }, total_len))) |
| } |
|
|
| |
| |
| pub fn encode_frame(stream_type: StreamType, payload: &[u8]) -> Result<Vec<u8>, io::Error> { |
| if payload.len() > MAX_FRAME_SIZE as usize { |
| return Err(io::Error::new( |
| io::ErrorKind::InvalidInput, |
| format!("Payload too large: {} bytes", payload.len()), |
| )); |
| } |
| let mut buf = Vec::with_capacity(FRAME_HEADER_SIZE + payload.len()); |
| buf.push(stream_type.as_byte()); |
| buf.extend_from_slice(&(payload.len() as u32).to_be_bytes()); |
| buf.extend_from_slice(payload); |
| Ok(buf) |
| } |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| pub fn is_legacy_jsonrpc(first_byte: u8) -> bool { |
| |
| |
| first_byte == b'{' |
| } |
|
|
| |
| #[derive(Debug, Clone, Copy, PartialEq)] |
| pub enum Protocol { |
| |
| LegacyJsonRpc, |
| |
| Framed(StreamType), |
| |
| Unknown(u8), |
| } |
|
|
| pub fn detect_protocol(first_byte: u8) -> Protocol { |
| if first_byte == b'{' { |
| Protocol::LegacyJsonRpc |
| } else if let Some(st) = StreamType::from_byte(first_byte) { |
| Protocol::Framed(st) |
| } else { |
| Protocol::Unknown(first_byte) |
| } |
| } |
|
|
| |
| |
| |
|
|
| |
| pub mod control { |
| |
| pub const HEARTBEAT: &str = r#"{"type":"heartbeat"}"#; |
|
|
| |
| pub const STATUS_REQUEST: &str = r#"{"type":"status_request"}"#; |
|
|
| |
| pub const STREAM_CLOSE: &str = r#"{"type":"stream_close"}"#; |
|
|
| |
| pub const STREAM_UPGRADE: &str = r#"{"type":"stream_upgrade"}"#; |
|
|
| |
| pub const HANDSHAKE: &str = r#"{"type":"handshake"}"#; |
|
|
| |
| pub fn build_handshake(role: &str, name: &str, version: &str) -> String { |
| format!(r#"{{"type":"handshake","role":"{}","name":"{}","version":"{}"}}"#, role, name, version) |
| } |
|
|
| |
| pub fn parse_role(payload: &str) -> Option<String> { |
| if payload.contains(r#""type":"handshake""#) || payload.contains(r#""type": "handshake""#) { |
| let start = payload.find(r#""role":"#)?; |
| let role_start = start + 8; |
| payload[role_start..].find('"').map(|end| payload[role_start..role_start + end].to_string()) |
| } else { |
| None |
| } |
| } |
|
|
| |
| pub fn parse_name(payload: &str) -> Option<String> { |
| let start = payload.find(r#""name":"#)?; |
| let name_start = start + 8; |
| payload[name_start..].find('"').map(|end| payload[name_start..name_start + end].to_string()) |
| } |
| } |
|
|
| |
| |
| |
|
|
| #[cfg(test)] |
| mod tests { |
| use super::*; |
| use std::io::Cursor; |
|
|
| #[test] |
| fn test_stream_type_roundtrip() { |
| for byte in 0x01..=0x08 { |
| let st = StreamType::from_byte(byte).unwrap(); |
| assert_eq!(st.as_byte(), byte); |
| } |
| assert!(StreamType::from_byte(0x00).is_none()); |
| assert!(StreamType::from_byte(0x0A).is_none()); |
| assert!(StreamType::from_byte(0xFF).is_none()); |
| } |
|
|
| #[test] |
| fn test_frame_to_bytes_and_parse() { |
| let frame = Frame::tool_rpc(r#"{"method":"spf_status"}"#); |
| let bytes = frame.to_bytes(); |
|
|
| |
| assert_eq!(bytes[0], 0x01); |
| let len = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]); |
| assert_eq!(len as usize, frame.payload.len()); |
|
|
| |
| let (parsed, consumed) = parse_frame(&bytes).unwrap().unwrap(); |
| assert_eq!(parsed.stream_type, StreamType::ToolRpc); |
| assert_eq!(parsed.payload, frame.payload); |
| assert_eq!(consumed, bytes.len()); |
| } |
|
|
| #[test] |
| fn test_read_write_frame_sync() { |
| let original = Frame::chat("Hello from SPF mesh!"); |
| let mut buffer = Vec::new(); |
|
|
| write_frame(&mut buffer, &original).unwrap(); |
|
|
| let mut cursor = Cursor::new(&buffer); |
| let read_back = read_frame(&mut cursor).unwrap().unwrap(); |
|
|
| assert_eq!(read_back.stream_type, StreamType::ChatText); |
| assert_eq!(read_back.payload_str().unwrap(), "Hello from SPF mesh!"); |
| } |
|
|
| #[test] |
| fn test_multiple_frames() { |
| let frames = vec![ |
| Frame::tool_rpc(r#"{"method":"test1"}"#), |
| Frame::chat("message two"), |
| Frame::control(control::HEARTBEAT), |
| ]; |
|
|
| let mut buffer = Vec::new(); |
| for f in &frames { |
| write_frame(&mut buffer, f).unwrap(); |
| } |
|
|
| let mut cursor = Cursor::new(&buffer); |
| for expected in &frames { |
| let read = read_frame(&mut cursor).unwrap().unwrap(); |
| assert_eq!(read.stream_type, expected.stream_type); |
| assert_eq!(read.payload, expected.payload); |
| } |
|
|
| |
| let eof = read_frame(&mut cursor).unwrap(); |
| assert!(eof.is_none()); |
| } |
|
|
| #[test] |
| fn test_parse_frame_incomplete() { |
| |
| let bytes = vec![0x01, 0x00, 0x00, 0x00, 0x05]; |
| let result = parse_frame(&bytes).unwrap(); |
| assert!(result.is_none()); |
|
|
| |
| let result2 = parse_frame(&[0x01, 0x00]).unwrap(); |
| assert!(result2.is_none()); |
| } |
|
|
| #[test] |
| fn test_oversized_frame_rejected() { |
| let mut header = vec![0x01]; |
| let big_len = MAX_FRAME_SIZE + 1; |
| header.extend_from_slice(&big_len.to_be_bytes()); |
| header.extend_from_slice(&[0u8; 100]); |
|
|
| let result = parse_frame(&header); |
| assert!(result.is_err()); |
| } |
|
|
| #[test] |
| fn test_unknown_stream_type_rejected() { |
| let bytes = vec![0xFF, 0x00, 0x00, 0x00, 0x01, 0x42]; |
| let result = parse_frame(&bytes); |
| assert!(result.is_err()); |
| } |
|
|
| #[test] |
| fn test_legacy_detection() { |
| assert!(is_legacy_jsonrpc(b'{')); |
| assert!(!is_legacy_jsonrpc(0x01)); |
| assert!(!is_legacy_jsonrpc(0x08)); |
|
|
| assert_eq!(detect_protocol(b'{'), Protocol::LegacyJsonRpc); |
| assert_eq!(detect_protocol(0x01), Protocol::Framed(StreamType::ToolRpc)); |
| assert_eq!(detect_protocol(0x08), Protocol::Framed(StreamType::Control)); |
| assert_eq!(detect_protocol(0x09), Protocol::Unknown(0x09)); |
| assert_eq!(detect_protocol(0xAA), Protocol::Unknown(0xAA)); |
| } |
|
|
| #[test] |
| fn test_stream_type_properties() { |
| assert!(StreamType::VoiceAudio.is_realtime()); |
| assert!(StreamType::ChatText.is_realtime()); |
| assert!(!StreamType::BrainSync.is_realtime()); |
|
|
| assert!(StreamType::BrainSync.is_bulk()); |
| assert!(StreamType::WeightSync.is_bulk()); |
| assert!(!StreamType::ChatText.is_bulk()); |
| } |
|
|
| #[test] |
| fn test_encode_frame() { |
| let payload = b"test payload"; |
| let bytes = encode_frame(StreamType::PipelineTask, payload).unwrap(); |
| assert_eq!(bytes[0], 0x04); |
| let len = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]); |
| assert_eq!(len, payload.len() as u32); |
| assert_eq!(&bytes[5..], payload); |
| } |
|
|
| #[test] |
| fn test_empty_frame() { |
| let frame = Frame::new(StreamType::Control, vec![]); |
| let bytes = frame.to_bytes(); |
| assert_eq!(bytes.len(), FRAME_HEADER_SIZE); |
|
|
| let (parsed, consumed) = parse_frame(&bytes).unwrap().unwrap(); |
| assert_eq!(parsed.payload.len(), 0); |
| assert_eq!(consumed, FRAME_HEADER_SIZE); |
| } |
| } |
|
|