surrealcs 0.4.4

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

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

/// Registers a new transaction with the router.
///
/// # Arguments
/// * `sender`: the sender of the transaction
/// * `allocator`: the allocator to use for the transaction
pub async fn register(
	sender: mpsc::Sender<TransactionMessage>,
	allocator: &mut Allocator<mpsc::Sender<TransactionMessage>>,
) {
	let address = sender.clone();
	let index = allocator.allocate(address);
	let response_message = TransactionMessage::Registered(index);
	match sender.send(response_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 registering a transaction: {}",
				e
			);
		}
	}
}

#[cfg(test)]
mod tests {

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

	#[tokio::test]
	async fn test_register() {
		let (tx, mut rx) = mpsc::channel(1);
		let mut allocator = Allocator::new();
		register(tx, &mut allocator).await;
		let message = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
		let id = match message {
			TransactionMessage::Registered(id) => id,
			_ => panic!("expected a registered message"),
		};

		// directly get the connection from the allocator
		let sender = allocator.extract_connection(id).unwrap();
		let message = TransactionMessage::Registered(0);
		sender.0.send(message).await.unwrap();

		// check that this is the same connection
		let message = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
		match message {
			TransactionMessage::Registered(_) => {}
			_ => panic!("expected a registered message"),
		}
	}
}