use crate::field::Field; use std::{ collections::HashMap, sync::{ mpsc::{channel, Receiver, Sender}, Arc, RwLock, }, }; use uuid::Uuid; #[derive(Clone, Debug)] enum MTTError { DocumentAlreadyExists(String), DocumentNotFound(String), RouteNoListeners, } #[derive(Clone, Debug, Eq, Hash, PartialEq)] enum Action { NewDocumentType, Query, Reply, Update, } #[derive(Clone)] enum NameID { ID(Uuid), Name(String), } impl From<&str> for NameID { fn from(value: &str) -> Self { Self::Name(value.to_string()) } } impl From for NameID { fn from(value: String) -> Self { Self::Name(value) } } impl From for NameID { fn from(value: Uuid) -> Self { Self::ID(value) } } impl From<&NameID> for NameID { fn from(value: &NameID) -> Self { value.clone() } } #[derive(Clone)] struct Message { msg_id: Uuid, document_id: NameID, action: Action, //instructions: ?, } impl Message { fn new(doc_id: D, action: Action) -> Self where D: Into, { Self { msg_id: Uuid::new_v4(), document_id: doc_id.into(), action: action, } } fn get_message_id(&self) -> &Uuid { &self.msg_id } fn get_document_id(&self) -> &NameID { &self.document_id } fn get_action(&self) -> &Action { &self.action } } #[cfg(test)] mod messages { use super::*; #[test] fn can_the_document_be_a_stringi_reference() { let dts = ["one", "two"]; for document in dts.into_iter() { let msg = Message::new(document, Action::NewDocumentType); match msg.get_document_id() { NameID::ID(_) => unreachable!("should have been a string id"), NameID::Name(data) => assert_eq!(data, document), } assert_eq!(msg.get_action(), &Action::NewDocumentType); } } #[test] fn can_the_document_be_a_string() { let dts = ["one".to_string(), "two".to_string()]; for document in dts.into_iter() { let msg = Message::new(document.clone(), Action::Update); match msg.get_document_id() { NameID::ID(_) => unreachable!("should have been a string id"), NameID::Name(data) => assert_eq!(data, &document), } assert_eq!(msg.get_action(), &Action::Update); } } #[test] fn can_the_document_be_an_id() { let document = Uuid::new_v4(); let msg = Message::new(document.clone(), Action::Query); match msg.get_document_id() { NameID::ID(data) => assert_eq!(data, &document), NameID::Name(_) => unreachable!("should have been an id"), } assert_eq!(msg.action, Action::Query); } #[test] fn is_the_message_id_random() { let mut ids: Vec = Vec::new(); for _ in 0..5 { let msg = Message::new("tester", Action::NewDocumentType); let id = msg.get_message_id().clone(); assert!(!ids.contains(&id), "{:?} containts {}", ids, id); ids.push(id); } } } #[derive(Eq, Hash, PartialEq)] struct Route { action: Action, doc_type: Option, } impl Route { fn new(doc_type: Option, action: Action) -> Self { Self { action: action, doc_type: doc_type, } } } struct QueueData { senders: HashMap>, names: HashMap, routes: HashMap>, } impl QueueData { fn new() -> Self { Self { senders: HashMap::new(), names: HashMap::new(), routes: HashMap::new(), } } fn get_doc_id(&self, nameid: N) -> Result where N: Into, { let sender_id = match nameid.into() { NameID::Name(name) => match self.names.get(&name) { Some(id) => id.clone(), None => return Err(MTTError::DocumentNotFound(name.clone())), }, NameID::ID(id) => id.clone(), }; if self.senders.contains_key(&sender_id) { Ok(sender_id) } else { Err(MTTError::DocumentNotFound(sender_id.to_string())) } } fn register(&mut self, name: String, tx: Sender) -> Result { match self.get_doc_id(name.as_str()) { Ok(_) => return Err(MTTError::DocumentAlreadyExists(name)), Err(_) => (), } let mut id = Uuid::new_v4(); while self.senders.contains_key(&id) { id = Uuid::new_v4(); } self.senders.insert(id.clone(), tx); self.names.insert(name, id.clone()); Ok(id) } fn send(&self, msg: Message) -> Result<(), MTTError> { let doc_id = match self.get_doc_id(msg.get_document_id()) { Ok(id) => id.clone(), Err(err) => return Err(err), }; let route = Route::new(Some(doc_id), msg.get_action().clone()); match self.routes.get(&route) { Some(senders) => { for sender_id in senders.iter() { let tx = self.senders.get(sender_id).unwrap(); tx.send(msg.clone()).unwrap(); } } None => {} } Ok(()) } fn add_route( &mut self, sender_id: &Uuid, doc_type: Option, action: Action, ) -> Result<(), MTTError> where N: Into, { let doc_id = match doc_type { Some(data) => match self.get_doc_id(data) { Ok(id) => Some(id.clone()), Err(err) => return Err(err), }, None => None, }; let route = Route::new(doc_id, action); match self.routes.get_mut(&route) { Some(mut senders) => senders.push(sender_id.clone()), None => { self.routes.insert(route, [sender_id.clone()].to_vec()); } } Ok(()) } } #[cfg(test)] mod queuedatas { use super::*; use std::{sync::mpsc::RecvTimeoutError, time::Duration}; static TIMEOUT: Duration = Duration::from_millis(500); #[test] fn can_a_new_document_type_be_rgistered() { let name = Uuid::new_v4().to_string(); let action = Action::Query; let (tx, rx) = channel(); let mut queuedata = QueueData::new(); let id = queuedata.register(name.clone(), tx).unwrap(); queuedata.add_route(&id, Some(name.clone()), action); let msg = Message::new(name.clone(), Action::Query); queuedata.send(msg.clone()).unwrap(); let result = rx.recv_timeout(TIMEOUT).unwrap(); assert_eq!(result.get_message_id(), msg.get_message_id()); let msg = Message::new(id.clone(), Action::Query); queuedata.send(msg.clone()).unwrap(); let result = rx.recv_timeout(TIMEOUT).unwrap(); assert_eq!(result.get_message_id(), msg.get_message_id()); } #[test] fn does_a_bad_document_name_fail() { let docname = Uuid::new_v4().to_string(); let queuedata = QueueData::new(); let msg = Message::new(docname.clone(), Action::Query); match queuedata.send(msg) { Ok(_) => unreachable!("should have been an error"), Err(data) => match data { MTTError::DocumentNotFound(doc) => assert_eq!(doc, docname), _ => unreachable!("should have been a not found error"), }, } } #[test] fn should_error_on_duplicate_name_registration() { let name = Uuid::new_v4().to_string(); let (tx1, _) = channel(); let (tx2, _) = channel(); let mut queuedata = QueueData::new(); queuedata.register(name.clone(), tx1).unwrap(); match queuedata.register(name.clone(), tx2) { Ok(_) => unreachable!("should have been an weeoe"), Err(data) => match data { MTTError::DocumentAlreadyExists(output) => assert_eq!(output, name), _ => unreachable!("should have been an already exists errorr"), }, } } #[test] fn is_send_okay_if_no_one_is_listening() { let mut queuedata = QueueData::new(); let name = "something"; let (tx, _) = channel(); queuedata.register(name.to_string(), tx).unwrap(); let msg = Message::new("something", Action::NewDocumentType); match queuedata.send(msg) { Ok(_) => {} Err(err) => unreachable!("got {:?}: should not error", err), } } #[test] fn can_certain_messages_be_ignored() { let mut queuedata = QueueData::new(); let doctype = "test"; let (tx, rx) = channel(); let id = queuedata.register(doctype.to_string(), tx).unwrap(); queuedata.add_route(&id, Some(doctype.to_string()), Action::Query); let msg = Message::new(doctype, Action::Query); queuedata.send(msg.clone()).unwrap(); let result = rx.recv_timeout(TIMEOUT).unwrap(); assert_eq!(result.get_message_id(), msg.get_message_id()); let msg = Message::new(doctype, Action::Reply); match rx.recv_timeout(TIMEOUT) { Ok(_) => unreachable!("should timeout"), Err(err) => match err { RecvTimeoutError::Timeout => {} _ => unreachable!("should timeout"), }, } } #[test] fn can_more_than_one_document_respond() { let mut queuedata = QueueData::new(); let name1 = "task"; let name2 = "work"; let action = Action::Query; let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); let id1 = queuedata.register(name1.to_string(), tx1).unwrap(); let id2 = queuedata.register(name2.to_string(), tx2).unwrap(); queuedata.add_route(&id1, Some(name1.to_string()), action.clone()); queuedata.add_route(&id2, Some(name1.to_string()), action.clone()); let msg = Message::new(name1, action.clone()); queuedata.send(msg.clone()).unwrap(); let result1 = rx1.recv_timeout(TIMEOUT).unwrap(); let result2 = rx2.recv_timeout(TIMEOUT).unwrap(); assert_eq!(result1.get_message_id(), msg.get_message_id()); assert_eq!(result1.get_message_id(), result2.get_message_id()); } } #[derive(Clone)] struct Queue { queue_data: Arc>, } impl Queue { fn new() -> Self { Self { queue_data: Arc::new(RwLock::new(QueueData::new())), } } } #[cfg(test)] mod queues { use super::*; #[test] fn create_a_queue() { Queue::new(); } } struct Document; impl Document { fn new() -> Self { Self {} } fn start(queue: Queue) {} fn listen(&self) {} } #[cfg(test)] mod documents { use super::*; #[test] fn create_document_creation() { let queue = Queue::new(); Document::start(queue.clone()); } } // Create a double hash map. posswible names that leads to an id that is int eh ids // \and the second is the id and the sender to be used.and a third for who wants to // listen to what. // // The queue has a read write lock on the abbove strucutee. A clone of this is given to // every process.