surrealcs 0.4.4

The SurrealCS client code for SurrealDB
Documentation
//! de-registers a new transaction with the router.
use tokio::sync::mpsc;

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

/// de-registers a new transaction with the router.
///
/// # Arguments
/// * `index`: the index of the transaction to deregister
/// * `allocator`: the allocator to use for the transaction
pub async fn deregister(index: usize, allocator: &mut Allocator<mpsc::Sender<TransactionMessage>>) {
	let sender = match allocator.deallocate(index) {
		Ok(unwrapped_sender) => unwrapped_sender,
		Err(e) => {
			tracing::error!("{:?}", e);
			return ();
		}
	};
	let response_message = TransactionMessage::Unregistered;

	match sender.send(response_message).await {
		Ok(_) => {}
		Err(e) => {
			// nothing else needs to be done here as the client ID has already been deallocated
			tracing::error!(
				"error when sending message back to client for deregistering a transaction: {}",
				e
			);
		}
	}
}

#[cfg(test)]
mod tests {

	use super::*;
	use tokio::time::{timeout, Duration};

	#[tokio::test]
	async fn test_deregister() {
		let (tx, mut rx) = mpsc::channel(1);
		let mut allocator = Allocator::new();
		let index = allocator.allocate(tx);
		deregister(index, &mut allocator).await;
		let message = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
		match message {
			TransactionMessage::Unregistered => {}
			_ => panic!("expected an unregistered message"),
		}

		// check that the connection is deallocated
		assert!(allocator.connection_pool[0].is_none());
		assert_eq!(allocator.free_connections.len(), 1);
	}
}