Spaces:
Build error
Build error
File size: 7,471 Bytes
4b1daed | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 | //! Wire Format Definitions
//!
//! Binary protocol wire format
use bytes::{Buf, BufMut, BytesMut};
use std::io;
/// Protocol magic header: "MEMA" in ASCII
pub const MAGIC_HEADER: u32 = 0x4D454D41;
/// Current protocol version
pub const PROTOCOL_VERSION: u8 = 1;
/// Frame header size in bytes
pub const HEADER_SIZE: usize = 31;
/// Message types for the protocol
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum MessageType {
// Memory operations
Store = 0x01,
Retrieve = 0x02,
Update = 0x03,
Delete = 0x04,
BatchStore = 0x05,
// Context operations
GetContextWindow = 0x10,
Consolidate = 0x11,
// Streaming
Subscribe = 0x20,
Unsubscribe = 0x21,
MemoryEvent = 0x22,
// Management
ApplyTtl = 0x30,
DetectConflicts = 0x31,
ResolveConflict = 0x32,
// Health check
Ping = 0x40,
Pong = 0x41,
// Responses
Success = 0x80,
Error = 0x81,
Partial = 0x82,
}
impl From<u8> for MessageType {
fn from(value: u8) -> Self {
match value {
0x01 => MessageType::Store,
0x02 => MessageType::Retrieve,
0x03 => MessageType::Update,
0x04 => MessageType::Delete,
0x05 => MessageType::BatchStore,
0x10 => MessageType::GetContextWindow,
0x11 => MessageType::Consolidate,
0x20 => MessageType::Subscribe,
0x21 => MessageType::Unsubscribe,
0x22 => MessageType::MemoryEvent,
0x30 => MessageType::ApplyTtl,
0x31 => MessageType::DetectConflicts,
0x32 => MessageType::ResolveConflict,
0x40 => MessageType::Ping,
0x41 => MessageType::Pong,
0x80 => MessageType::Success,
0x81 => MessageType::Error,
0x82 => MessageType::Partial,
_ => MessageType::Error,
}
}
}
/// Protocol flags
pub mod flags {
/// Body is LZ4 compressed
pub const COMPRESSED: u8 = 0x01;
/// CRC32 checksum is present
pub const CHECKSUM: u8 = 0x02;
/// Body is encrypted with ChaCha20-Poly1305
pub const ENCRYPTED: u8 = 0x04;
}
/// Frame header structure
///
/// Binary layout (31 bytes):
/// ```text
/// +----------------+----------------+----------------+----------------+
/// | Magic (4 bytes) | Version (1) | Type (1) | Flags (1) |
/// +----------------+----------------+----------------+----------------+
/// | Message ID (16 bytes) |
/// +----------------+----------------+----------------+----------------+
/// | Body Length (8 bytes) |
/// +----------------+----------------+----------------+----------------+
/// ```
#[derive(Debug, Clone)]
pub struct FrameHeader {
/// Magic header (should be MAGIC_HEADER)
pub magic: u32,
/// Protocol version
pub version: u8,
/// Message type
pub message_type: MessageType,
/// Flags (compression, checksum, encryption)
pub flags: u8,
/// Unique message ID for correlation
pub message_id: [u8; 16],
/// Length of the body in bytes
pub body_length: u64,
}
impl FrameHeader {
/// Create a new frame header
pub fn new(message_type: MessageType, body_length: u64) -> Self {
let mut message_id = [0u8; 16];
// Generate random message ID
getrandom(&mut message_id);
Self {
magic: MAGIC_HEADER,
version: PROTOCOL_VERSION,
message_type,
flags: 0,
message_id,
body_length,
}
}
/// Create a response header for a request
pub fn response(request: &FrameHeader, message_type: MessageType, body_length: u64) -> Self {
Self {
magic: MAGIC_HEADER,
version: PROTOCOL_VERSION,
message_type,
flags: 0,
message_id: request.message_id,
body_length,
}
}
/// Write the header to a buffer
pub fn write_to(&self, buf: &mut BytesMut) {
buf.put_u32(self.magic);
buf.put_u8(self.version);
buf.put_u8(self.message_type as u8);
buf.put_u8(self.flags);
buf.put_slice(&self.message_id);
buf.put_u64(self.body_length);
}
/// Read a header from a buffer
pub fn read_from(buf: &mut BytesMut) -> io::Result<Option<Self>> {
if buf.len() < HEADER_SIZE {
return Ok(None);
}
let magic = buf.get_u32();
if magic != MAGIC_HEADER {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Invalid magic header: {:08x}", magic),
));
}
let version = buf.get_u8();
let message_type = MessageType::from(buf.get_u8());
let flags = buf.get_u8();
let mut message_id = [0u8; 16];
buf.copy_to_slice(&mut message_id);
let body_length = buf.get_u64();
Ok(Some(Self {
magic,
version,
message_type,
flags,
message_id,
body_length,
}))
}
/// Check if body is compressed
pub fn is_compressed(&self) -> bool {
self.flags & flags::COMPRESSED != 0
}
/// Check if checksum is present
pub fn has_checksum(&self) -> bool {
self.flags & flags::CHECKSUM != 0
}
/// Check if body is encrypted
pub fn is_encrypted(&self) -> bool {
self.flags & flags::ENCRYPTED != 0
}
/// Set compression flag
pub fn set_compressed(&mut self) {
self.flags |= flags::COMPRESSED;
}
/// Set checksum flag
pub fn set_checksum(&mut self) {
self.flags |= flags::CHECKSUM;
}
}
/// Complete frame with header and body
#[derive(Debug, Clone)]
pub struct Frame {
pub header: FrameHeader,
pub body: Vec<u8>,
}
impl Frame {
/// Create a new frame
pub fn new(message_type: MessageType, body: Vec<u8>) -> Self {
Self {
header: FrameHeader::new(message_type, body.len() as u64),
body,
}
}
/// Create a success response
pub fn success(request: &FrameHeader, body: Vec<u8>) -> Self {
Self {
header: FrameHeader::response(request, MessageType::Success, body.len() as u64),
body,
}
}
/// Create an error response
pub fn error(request: &FrameHeader, message: &str) -> Self {
let body = message.as_bytes().to_vec();
Self {
header: FrameHeader::response(request, MessageType::Error, body.len() as u64),
body,
}
}
}
/// Simple random bytes generator
fn getrandom(buf: &mut [u8]) {
use rand::RngCore;
rand::thread_rng().fill_bytes(buf);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_header_roundtrip() {
let header = FrameHeader::new(MessageType::Store, 1024);
let mut buf = BytesMut::with_capacity(HEADER_SIZE);
header.write_to(&mut buf);
let parsed = FrameHeader::read_from(&mut buf).unwrap().unwrap();
assert_eq!(parsed.magic, MAGIC_HEADER);
assert_eq!(parsed.version, PROTOCOL_VERSION);
assert_eq!(parsed.body_length, 1024);
}
#[test]
fn test_message_type_conversion() {
assert_eq!(MessageType::from(0x01), MessageType::Store);
assert_eq!(MessageType::from(0x80), MessageType::Success);
}
}
|