surrealcs_kernel/messages/client/
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
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
//! Defines the messages to be sent between actors on the same machine. The reason why there is a difference between these
//! messages and messages sent over TCP is that the channel operators cannot be sent over a network to different machines.
use std::fmt::Debug;

use nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};
use tokio::sync::mpsc;

use crate::messages::server::interface::{ServerMessage, ServerTransactionMessage};
use crate::messages::server::wrapper::WrappedServerMessage;

/// The message that is to be sent between actors on the same machine.
///
/// # Fields
/// * `TransactionOperation`: a transaction operation that is to be sent to the key value store and thus over a TCP connection
/// * `Register`: a message to register a transaction actor with the router
/// * `Ping`: a message to ping the connection to ensure it is still alive (router ID, connection ID)
/// * `Deregister`: a message to deregister a transaction actor from the router
/// * `CloseConnection`: a message to close the connection
/// * `Registered`: a message to confirm that a transaction actor has been registered
/// * `Unregistered`: a message to confirm that a transaction actor has been deregistered
/// * `Error`: a message to send an error to the client
#[derive(Debug, Clone)]
pub enum TransactionMessage {
	TransactionOperation(WrappedServerMessage),
	Register(mpsc::Sender<TransactionMessage>),
	Ping((usize, String)),
	Deregister(usize),
	CloseConnection,
	// below are returns
	Registered(usize),
	Unregistered,
	Error(NanoServiceError),
}

impl TransactionMessage {
	/// Extracts the transaction operation and server ID.
	///
	/// # Returns
	/// A tuple containing the server ID and the transaction operation.
	pub fn extract_transaction_operation(
		self,
	) -> Result<(usize, ServerTransactionMessage), NanoServiceError> {
		match self {
			TransactionMessage::TransactionOperation(op) => {
				let transaction = match op.message {
					ServerMessage::Error(trans) => return Err(trans),
					ServerMessage::SendOperation(trans) => trans,
					ServerMessage::BeginTransaction(trans) => trans,
					ServerMessage::CommitTransaction => ServerTransactionMessage::Commit,
					ServerMessage::RollbackTransaction => ServerTransactionMessage::Rollback,
					_ => {
						return Err(NanoServiceError::new(
							format!("ServerMessage not SendOperation: {:?}", op.message),
							NanoServiceErrorStatus::Unknown,
						))
					}
				};
				let server_id = match op.server_id {
					Some(id) => id,
					None => {
						return Err(NanoServiceError::new(
							"Server id not found".to_string(),
							NanoServiceErrorStatus::Unknown,
						))
					}
				};
				Ok((server_id, transaction))
			}
			TransactionMessage::Error(e) => {
				tracing::error!("message error: {:?}", e);
				Err(e)
			}
			_ => Err(NanoServiceError::new(
				"TransactionMessage not TransactionOperation".to_string(),
				NanoServiceErrorStatus::Unknown,
			)),
		}
	}
}

#[cfg(test)]
mod tests {

	use super::*;
	use crate::messages::server::kv_operations::MessagePut;

	static CONNECTION_ID: &str = "1-1234567890";
	static _TRANSACTION_ID: &str = "1-1-1234567890";

	#[test]
	fn test_extract_transaction_operation() {
		let transaction = ServerTransactionMessage::Put(MessagePut {
			key: b"key".to_vec(),
			value: b"value".to_vec(),
			version: None,
		});
		let mut wrapped = WrappedServerMessage::new(
			1,
			ServerMessage::SendOperation(transaction),
			CONNECTION_ID.into(),
		);
		wrapped.server_id = Some(1);
		let message = TransactionMessage::TransactionOperation(wrapped);

		let result = message.extract_transaction_operation().unwrap();
		assert_eq!(result.0, 1);

		// extract the transaction
		let extracted_transaction = match result.1 {
			ServerTransactionMessage::Put(transaction) => transaction,
			_ => panic!("Transaction not Put"),
		};
		assert_eq!(extracted_transaction.key, b"key".to_vec());
		assert_eq!(extracted_transaction.value, b"value".to_vec());
	}

	#[test]
	fn test_extract_transaction_operation_error_wrong_transaction_message_type() {
		let message = TransactionMessage::Register(mpsc::channel(1).0);
		let result = message.extract_transaction_operation();

		assert!(result.is_err());
		assert_eq!("TransactionMessage not TransactionOperation", result.err().unwrap().message);
	}

	#[test]
	fn test_extract_transaction_no_server_id() {
		let transaction = ServerTransactionMessage::Put(MessagePut {
			key: b"key".to_vec(),
			value: b"value".to_vec(),
			version: None,
		});
		let wrapped = WrappedServerMessage::new(
			1,
			ServerMessage::SendOperation(transaction),
			CONNECTION_ID.into(),
		);
		let message = TransactionMessage::TransactionOperation(wrapped);
		let result = message.extract_transaction_operation();

		assert!(result.is_err());
		assert_eq!("Server id not found", result.err().unwrap().message);
	}
}