surrealcs_kernel/messages/serialization/bincode_processes/
message.rs

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
//! Defines the functions performing serialization and deserialization of messages using bincode.
use 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;

/// Serializes a server message into bytes using bincode.
///
/// # Arguments
/// * `wrapped_message`: the message to be serialized
///
/// # Returns
/// a vector of bytes representing the serialized message
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)
}

/// Deserializes a server message from a stream of bytes.
///
/// # Arguments
/// * `reader`: the stream of bytes to be deserialized
///
/// # Returns
/// the deserialized server message
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);
	}
}