surrealcs 0.4.4

The SurrealCS client code for SurrealDB
Documentation
//! Sends a transaction operation back to the client.
use tokio::sync::mpsc;

use surrealcs_kernel::messages::server::wrapper::WrappedServerMessage;
use surrealcs_kernel::{allocator::Allocator, messages::client::message::TransactionMessage};

/// Sends a transaction operation back to the client.
///
/// # Arguments
/// * `unwrapped_message`: the message to send back to the client
/// * `allocator`: the allocator to use for the transaction
pub async fn send_transaction_operation(
	unwrapped_message: WrappedServerMessage,
	allocator: &mut Allocator<mpsc::Sender<TransactionMessage>>,
) {
	let sender = match allocator.extract_connection(unwrapped_message.client_id) {
		Ok(unwrapped_sender) => unwrapped_sender.0,
		Err(e) => {
			tracing::error!("{:?}", e);
			return ();
		}
	};
	let message = TransactionMessage::TransactionOperation(unwrapped_message);
	match sender.send(message).await {
		Ok(_) => {}
		Err(e) => {
			// we might deallocate the client ID here as we cannot send the message back to the client
			tracing::error!(
				"error when sending message back to client for transaction operation: {}",
				e
			);
		}
	}
}

#[cfg(test)]
mod tests {

	use super::*;
	use surrealcs_kernel::messages::server::interface::ServerMessage;
	use surrealcs_kernel::messages::server::interface::ServerTransactionMessage;
	use tokio::time::{timeout, Duration};

	#[tokio::test]
	async fn test_send_transaction_operation() {
		let (tx, mut rx) = mpsc::channel(1);
		let mut allocator = Allocator::new();
		let id = 0;
		allocator.allocate(tx);
		let message = WrappedServerMessage {
			client_id: id,
			message: ServerMessage::SendOperation(ServerTransactionMessage::Commit),
			server_id: Some(0),
			connection_id: "some fake test ID".to_string(),
			transaction_id: Some("some fake transaction ID".to_string()),
		};
		send_transaction_operation(message, &mut allocator).await;
		let message = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
		match message {
			TransactionMessage::TransactionOperation(_) => {}
			_ => panic!("expected a transaction operation message"),
		}
	}
}