surrealcs 0.4.4

The SurrealCS client code for SurrealDB
Documentation
//! General utilities for the transaction interface
use super::interface::Transaction;
use nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};
use surrealcs_kernel::messages::client::message::TransactionMessage;
use tokio::sync::mpsc;

#[allow(dead_code)]
pub async fn close_tcp_connection(sender: mpsc::Sender<TransactionMessage>) {
	let message = TransactionMessage::CloseConnection;
	match sender.send(message).await {
		Ok(_) => {
			println!("Successfully sent close connection message to writer");
			tracing::info!("Successfully sent close connection message to writer");
		}
		Err(e) => {
			println!("Error sending close connection message to writer: {}", e);
			tracing::error!("Error sending close connection message to writer: {}", e);
		}
	}
}

/// Util function that awaits a message from the router for all transaction operations.
///
/// # Arguments
/// * `handle`: the handle for the transaction that is awaiting a message
///
/// # Returns
/// The message that was recieved from the router
pub async fn await_message<T>(
	handle: &mut Transaction<T>,
) -> Result<TransactionMessage, NanoServiceError> {
	// TODO => maybe introduce a timeout here
	match handle.receiver.recv().await {
		Some(message) => Ok(message),
		None => {
			// TODO => look into inspecting for an error and rolling back if not
			Err(NanoServiceError::new(
				"Failed to recieve response from the server".to_string(),
				NanoServiceErrorStatus::Unknown,
			))
		}
	}
}

#[cfg(test)]
mod tests {

	use super::*;
	use crate::transactions::interface::interface::Any;
	use std::marker::PhantomData;
	use tokio::sync::mpsc;

	#[tokio::test]
	async fn test_await_message() {
		let (tx_tx, tx_rx) = mpsc::channel::<TransactionMessage>(1);
		let (tx, _rx) = mpsc::channel::<TransactionMessage>(1);

		let mut handle: Transaction<Any> = Transaction {
			client_id: 0,
			server_id: None,
			receiver: tx_rx,
			sender: tx,
			connection_id: "1-1234567890".into(),
			transaction_id: "1-1234567890".into(),
			state: PhantomData,
		};

		let message = TransactionMessage::Registered(0);
		tx_tx.send(message).await.unwrap();

		let response = await_message(&mut handle).await.unwrap();
		match response {
			TransactionMessage::Registered(index) => {
				assert_eq!(index, 0);
			}
			_ => {
				panic!("wrong message type");
			}
		}
	}
}