surrealcs_kernel/messages/serialization/bincode_processes/
message.rsuse nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};
use revision::Revisioned;
use tokio::io::AsyncReadExt;
use tokio::net::tcp::OwnedReadHalf;
use crate::messages::serialization::header::MessageHeader;
use crate::messages::server::wrapper::WrappedServerMessage;
pub fn serialize_server_message(
wrapped_message: &WrappedServerMessage,
) -> Result<Vec<u8>, NanoServiceError> {
let mut serialized_message = Vec::new();
wrapped_message.serialize_revisioned(&mut serialized_message).map_err(|e| {
NanoServiceError::new(
format!("Failed to serialize message metadata: {}", e),
NanoServiceErrorStatus::BadRequest,
)
})?;
let length = serialized_message.len();
let mut message_header = MessageHeader {
value: length,
}
.to_bytes();
message_header.extend(serialized_message);
Ok(message_header)
}
pub async fn deserialize_from_stream(
reader: &mut OwnedReadHalf,
) -> Result<WrappedServerMessage, NanoServiceError> {
let mut header_bytes = [0u8; 8];
reader.read_exact(&mut header_bytes).await.map_err(|e| {
NanoServiceError::new(
format!("Failed to read message header: {}", e),
NanoServiceErrorStatus::BadRequest,
)
})?;
let message_header = MessageHeader::from_bytes(&header_bytes);
let mut message_bytes = vec![0u8; message_header.value];
reader.read_exact(&mut message_bytes).await.map_err(|e| {
NanoServiceError::new(
format!("Failed to read message header: {}", e),
NanoServiceErrorStatus::BadRequest,
)
})?;
let wrapped_message = WrappedServerMessage::deserialize_revisioned(
&mut message_bytes.as_slice(),
)
.map_err(|e| {
NanoServiceError::new(
format!("Failed to deserialize message metadata: {}", e),
NanoServiceErrorStatus::BadRequest,
)
})?;
Ok(wrapped_message)
}
#[cfg(test)]
mod tests {
use crate::messages::server::interface::ServerMessage;
use super::*;
static CONNECTION_ID: &str = "1-1234567890";
#[test]
fn test_serialize_server_message() {
let wrapped_message =
WrappedServerMessage::new(2, ServerMessage::Ping(5), CONNECTION_ID.into());
let serialized = serialize_server_message(&wrapped_message).unwrap();
let message = &mut serialized.as_slice()[8..].to_owned();
let deserialized =
WrappedServerMessage::deserialize_revisioned(&mut message.as_slice()).unwrap();
assert_eq!(wrapped_message, deserialized);
}
}