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);
}
}
}
pub async fn await_message<T>(
handle: &mut Transaction<T>,
) -> Result<TransactionMessage, NanoServiceError> {
match handle.receiver.recv().await {
Some(message) => Ok(message),
None => {
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");
}
}
}
}