mod cache; mod messages; use cache::Cache; use messages::{ReceiveMsg, SendMsg, SessionRequest}; use std::{ sync::mpsc::{channel, Sender}, thread::spawn, }; use uuid::Uuid; /// Application connection to the database #[derive(Clone)] pub struct MoreThanText { id: Option, tx: Sender, } impl MoreThanText { /// Create a MoreThanText database. /// /// Example: /// /// ``` /// use morethantext::MoreThanText; /// /// MoreThanText::new(); /// ``` pub fn new() -> Self { let (tx, rx) = channel(); spawn(move || { let mut cache = Cache::new(rx); cache.listen(); }); Self { id: None, tx: tx } } /// Opens an existing or new session with the database. /// /// If the string is None, incorrect, or expired, /// a new session will be created. /// /// Example: /// /// ``` /// use morethantext::MoreThanText; /// /// let mut mtt = MoreThanText::new(); /// mtt.open_session(None); /// mtt.open_session(Some("7b1ff340-7dfa-4f29-b144-601384e54423".to_string())); /// ``` pub fn open_session(&mut self, id: Option) { let (tx, rx) = channel(); let request = SessionRequest { id: id, tx: tx, }; self.tx.send(SendMsg::OpenSession(request)).unwrap(); match rx.recv().unwrap() { ReceiveMsg::Session(sid) => self.id = Some(sid), } } /// Get the session id /// /// Example: /// /// ``` /// use morethantext::MoreThanText; /// /// let mut mtt = MoreThanText::new(); /// mtt.get_id(); /// ``` pub fn get_id(&self) -> String { match self.id { Some(sid) => sid.to_string(), None => "none".to_string(), } } } #[cfg(test)] mod mtt_client { use super::*; #[test] fn uniques_ids() { let mut mtt = MoreThanText::new(); let mut ids: Vec = Vec::new(); for _ in 1..10 { mtt.open_session(None); let id = mtt.id.clone().unwrap(); if ids.contains(&id) { assert!(false, "{} is a duplicate id", id); } ids.push(id); } } #[test] fn existing_ids_are_reused() { let mut mtt = MoreThanText::new(); mtt.open_session(None); let holder = mtt.id.clone().unwrap().to_string(); mtt.open_session(Some(holder.clone())); assert_eq!(mtt.id.clone().unwrap().to_string(), holder); } #[test] fn bad_ids_generate_new_ones() { let mut mtt = MoreThanText::new(); mtt.open_session(Some("bad test string".to_string())); assert!(mtt.id.is_some()); } #[test] fn incorrect_ids_generate_new_ones() { let mut mtt = MoreThanText::new(); let holder = Uuid::new_v4(); mtt.open_session(Some(holder.clone().to_string())); assert_ne!(mtt.id, Some(holder)); } }