SPFsmartGATE / src /framing.rs
JosephStoneCellAI's picture
Upload 45 files
1269259 verified
// SPF Smart Gateway - Message Framing Protocol
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Length-prefixed message framing for persistent bidirectional streams.
// Replaces one-shot read_to_end/finish pattern in mesh transport.
// Supports 8 stream types: TOOL_RPC, CHAT, VOICE, PIPELINE, BRAIN_SYNC, WEIGHT_SYNC, CONTROL
//
// Frame format: [1-byte type][4-byte length BE][payload bytes]
// Max frame size: 10MB (matches existing mesh limit)
//
// Depends on: nothing (Layer 2 protocol definition)
use std::io;
// ============================================================================
// STREAM TYPES
// ============================================================================
/// Stream type identifiers — first byte of every frame
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum StreamType {
/// Tool RPC calls (existing mesh functionality) — JSON-RPC format
ToolRpc = 0x01,
/// Text chat messages (user ↔ user, user ↔ agent, agent ↔ agent)
ChatText = 0x02,
/// Voice audio frames (Opus codec)
VoiceAudio = 0x03,
/// Pipeline task assignment (orchestrator → worker)
PipelineTask = 0x04,
/// Pipeline result (worker → orchestrator)
PipelineResult = 0x05,
/// Brain knowledge sync between nodes
BrainSync = 0x06,
/// Transformer weight sharing / delta sync
WeightSync = 0x07,
/// Control messages: heartbeat, status, peer management
Control = 0x08,
}
impl StreamType {
/// Convert byte to 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,
}
}
/// Convert StreamType to byte
pub fn as_byte(self) -> u8 {
self as u8
}
/// Human-readable name for logging
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",
}
}
/// Whether this stream type carries real-time data (low latency required)
pub fn is_realtime(self) -> bool {
matches!(self, Self::VoiceAudio | Self::ChatText | Self::Control)
}
/// Whether this stream type carries bulk data (high throughput preferred)
pub fn is_bulk(self) -> bool {
matches!(self, Self::BrainSync | Self::WeightSync | Self::PipelineTask | Self::PipelineResult)
}
}
// ============================================================================
// FRAME FORMAT
// ============================================================================
/// Maximum frame payload size: 10MB (matches mesh.rs MAX_MSG_SIZE)
pub const MAX_FRAME_SIZE: u32 = 10_485_760;
/// Frame header size: 1 (type) + 4 (length) = 5 bytes
pub const FRAME_HEADER_SIZE: usize = 5;
/// A single framed message ready for transmission
#[derive(Debug, Clone)]
pub struct Frame {
/// Stream type identifier
pub stream_type: StreamType,
/// Payload bytes (JSON, audio, binary, etc.)
pub payload: Vec<u8>,
}
impl Frame {
/// Create a new frame
pub fn new(stream_type: StreamType, payload: Vec<u8>) -> Self {
Self { stream_type, payload }
}
/// Create a Tool RPC frame from JSON string
pub fn tool_rpc(json: &str) -> Self {
Self::new(StreamType::ToolRpc, json.as_bytes().to_vec())
}
/// Create a Chat frame from text
pub fn chat(text: &str) -> Self {
Self::new(StreamType::ChatText, text.as_bytes().to_vec())
}
/// Create a Control frame from JSON
pub fn control(json: &str) -> Self {
Self::new(StreamType::Control, json.as_bytes().to_vec())
}
/// Create a Pipeline Task frame
pub fn pipeline_task(payload: Vec<u8>) -> Self {
Self::new(StreamType::PipelineTask, payload)
}
/// Create a Pipeline Result frame
pub fn pipeline_result(payload: Vec<u8>) -> Self {
Self::new(StreamType::PipelineResult, payload)
}
/// Serialize frame to wire format: [type:1][length:4 BE][payload:N]
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
}
/// Payload as UTF-8 string (for JSON/text frames)
pub fn payload_str(&self) -> Result<&str, std::str::Utf8Error> {
std::str::from_utf8(&self.payload)
}
}
// ============================================================================
// FRAME READER / WRITER — for use with any Read/Write stream
// ============================================================================
/// Read a single frame from a byte stream.
/// Returns None on clean EOF (stream closed by peer).
/// Returns Err on protocol violations or I/O errors.
pub fn read_frame(reader: &mut dyn io::Read) -> io::Result<Option<Frame>> {
// Read header: 5 bytes [type:1][length:4]
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]]);
// Validate stream type
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))
})?;
// Validate frame size
if length > MAX_FRAME_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Frame too large: {} bytes (max {})", length, MAX_FRAME_SIZE),
));
}
// Read payload
let mut payload = vec![0u8; length as usize];
reader.read_exact(&mut payload)?;
Ok(Some(Frame { stream_type, payload }))
}
/// Write a single frame to a byte stream.
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(())
}
// ============================================================================
// ASYNC FRAME READER / WRITER — for tokio AsyncRead/AsyncWrite
// ============================================================================
/// Read a frame from an async byte stream (iroh SendStream/RecvStream).
/// This operates on raw byte slices for compatibility with iroh's API.
///
/// For iroh streams: caller reads bytes into buffer, passes to parse_frame.
/// iroh RecvStream doesn't implement AsyncRead directly — we work with
/// the bytes it gives us.
/// Parse a frame from a complete byte buffer.
/// Returns (frame, bytes_consumed) on success.
/// Returns None if buffer doesn't contain a complete frame yet.
pub fn parse_frame(buf: &[u8]) -> Result<Option<(Frame, usize)>, io::Error> {
if buf.len() < FRAME_HEADER_SIZE {
return Ok(None); // Need more data
}
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); // Need more data
}
let payload = buf[FRAME_HEADER_SIZE..total_len].to_vec();
Ok(Some((Frame { stream_type, payload }, total_len)))
}
/// Serialize a frame into a byte buffer for writing to iroh SendStream.
/// Same as Frame::to_bytes() but takes components directly.
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)
}
// ============================================================================
// LEGACY DETECTION
// ============================================================================
/// Detect whether incoming data is legacy JSON-RPC or new framed protocol.
/// Legacy mesh messages start with '{' (0x7B) — raw JSON.
/// New framed messages start with 0x01-0x08 — stream type byte.
///
/// Call this on the first byte(s) of a new stream to determine protocol version.
pub fn is_legacy_jsonrpc(first_byte: u8) -> bool {
// ASCII '{' = 0x7B. All stream types are 0x01-0x08.
// No overlap — clean detection.
first_byte == b'{'
}
/// Detect protocol from first byte
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Protocol {
/// Legacy one-shot JSON-RPC (existing mesh behavior)
LegacyJsonRpc,
/// New framed protocol with persistent streams
Framed(StreamType),
/// Unknown protocol
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)
}
}
// ============================================================================
// CONTROL MESSAGES
// ============================================================================
/// Well-known control message types (sent as JSON in Control frames)
pub mod control {
/// Heartbeat — sent periodically to keep stream alive
pub const HEARTBEAT: &str = r#"{"type":"heartbeat"}"#;
/// Status request
pub const STATUS_REQUEST: &str = r#"{"type":"status_request"}"#;
/// Peer closing stream gracefully
pub const STREAM_CLOSE: &str = r#"{"type":"stream_close"}"#;
/// Peer requesting stream type upgrade/change
pub const STREAM_UPGRADE: &str = r#"{"type":"stream_upgrade"}"#;
/// Initial role/team/version exchange on persistent stream connect.
pub const HANDSHAKE: &str = r#"{"type":"handshake"}"#;
/// Build a handshake frame JSON string from role/team/name/version.
pub fn build_handshake(role: &str, name: &str, version: &str) -> String {
format!(r#"{{"type":"handshake","role":"{}","name":"{}","version":"{}"}}"#, role, name, version)
}
/// Parse role from a handshake frame payload. Returns None if not a handshake.
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
}
}
/// Parse name from a handshake frame payload.
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())
}
}
// ============================================================================
// TESTS
// ============================================================================
#[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();
// Verify header
assert_eq!(bytes[0], 0x01); // TOOL_RPC
let len = u32::from_be_bytes([bytes[1], bytes[2], bytes[3], bytes[4]]);
assert_eq!(len as usize, frame.payload.len());
// Parse back
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);
}
// Next read should return None (EOF)
let eof = read_frame(&mut cursor).unwrap();
assert!(eof.is_none());
}
#[test]
fn test_parse_frame_incomplete() {
// Only header, no payload
let bytes = vec![0x01, 0x00, 0x00, 0x00, 0x05]; // type=TOOL_RPC, len=5
let result = parse_frame(&bytes).unwrap();
assert!(result.is_none()); // Needs 5 more bytes
// Too short for header
let result2 = parse_frame(&[0x01, 0x00]).unwrap();
assert!(result2.is_none());
}
#[test]
fn test_oversized_frame_rejected() {
let mut header = vec![0x01]; // TOOL_RPC
let big_len = MAX_FRAME_SIZE + 1;
header.extend_from_slice(&big_len.to_be_bytes());
header.extend_from_slice(&[0u8; 100]); // some payload bytes
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]; // type=0xFF
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); // Just header, no payload
let (parsed, consumed) = parse_frame(&bytes).unwrap().unwrap();
assert_eq!(parsed.payload.len(), 0);
assert_eq!(consumed, FRAME_HEADER_SIZE);
}
}