buffers.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. use async_std::sync::{Arc, Mutex};
  2. use std::{
  3. cmp::Ordering,
  4. collections::{BTreeMap, VecDeque},
  5. };
  6. use chrono::Utc;
  7. use ripemd::{Digest, Ripemd160};
  8. use crate::{settings, Privmsg};
  9. pub type Buffers = Arc<Msgs>;
  10. pub struct Msgs {
  11. pub privmsgs: PrivmsgsBuffer,
  12. pub unread_msgs: UMsgs,
  13. pub seen_ids: SeenIds,
  14. }
  15. pub fn create_buffers() -> Buffers {
  16. let seen_ids = SeenIds::new();
  17. let privmsgs = PrivmsgsBuffer::new();
  18. let unread_msgs = UMsgs::new();
  19. Arc::new(Msgs { privmsgs, unread_msgs, seen_ids })
  20. }
  21. #[derive(Clone)]
  22. pub struct RingBuffer<T> {
  23. pub items: VecDeque<T>,
  24. }
  25. impl<T: Eq + PartialEq + Clone> RingBuffer<T> {
  26. pub fn new(capacity: usize) -> Self {
  27. let items = VecDeque::with_capacity(capacity);
  28. Self { items }
  29. }
  30. pub fn push(&mut self, val: T) {
  31. if self.items.len() == self.items.capacity() {
  32. self.items.pop_front();
  33. }
  34. self.items.push_back(val);
  35. }
  36. pub fn contains(&self, val: &T) -> bool {
  37. self.items.contains(val)
  38. }
  39. pub fn len(&self) -> usize {
  40. self.items.len()
  41. }
  42. pub fn is_empty(&self) -> bool {
  43. self.items.is_empty()
  44. }
  45. pub fn as_slice(&mut self) -> &mut [T] {
  46. self.items.make_contiguous()
  47. }
  48. pub fn iter(&self) -> impl Iterator<Item = &T> + DoubleEndedIterator {
  49. self.items.iter()
  50. }
  51. pub fn remove(&mut self, val: &T) -> Option<T> {
  52. if let Some(index) = self.items.iter().position(|v| v == val) {
  53. self.items.remove(index)
  54. } else {
  55. None
  56. }
  57. }
  58. }
  59. pub struct PrivmsgsBuffer {
  60. msgs: Mutex<OrderingAlgo>,
  61. }
  62. impl PrivmsgsBuffer {
  63. pub fn new() -> Self {
  64. Self { msgs: Mutex::new(OrderingAlgo::new()) }
  65. }
  66. pub async fn push(&self, privmsg: &Privmsg) {
  67. self.msgs.lock().await.push(privmsg);
  68. }
  69. pub async fn load(&self) -> Vec<Privmsg> {
  70. self.msgs.lock().await.load()
  71. }
  72. pub async fn get_msg_by_term(&self, term: u64) -> Option<Privmsg> {
  73. self.msgs.lock().await.get_msg_by_term(term)
  74. }
  75. pub async fn len(&self) -> usize {
  76. self.msgs.lock().await.len()
  77. }
  78. pub async fn is_empty(&self) -> bool {
  79. self.msgs.lock().await.is_empty()
  80. }
  81. pub async fn last_term(&self) -> u64 {
  82. self.msgs.lock().await.last_term()
  83. }
  84. pub async fn fetch_msgs(&self, term: u64) -> Vec<Privmsg> {
  85. self.msgs.lock().await.fetch_msgs(term)
  86. }
  87. }
  88. pub struct OrderingAlgo {
  89. buffer: RingBuffer<Privmsg>,
  90. orphans: RingBuffer<Orphan>,
  91. }
  92. impl Default for OrderingAlgo {
  93. fn default() -> Self {
  94. Self::new()
  95. }
  96. }
  97. impl OrderingAlgo {
  98. pub fn new() -> Self {
  99. Self {
  100. buffer: RingBuffer::new(settings::SIZE_OF_MSGS_BUFFER),
  101. orphans: RingBuffer::new(settings::SIZE_OF_MSGS_BUFFER),
  102. }
  103. }
  104. pub fn push(&mut self, privmsg: &Privmsg) {
  105. match privmsg.term.cmp(&(self.last_term() + 1)) {
  106. Ordering::Equal => self.buffer.push(privmsg.clone()),
  107. Ordering::Less => {
  108. if let Some(msg) = self.get_msg_by_term(privmsg.term) {
  109. if (msg.timestamp - privmsg.timestamp) <= settings::TERM_MAX_TIME_DIFFERENCE {
  110. self.buffer.push(privmsg.clone());
  111. }
  112. } else {
  113. self.buffer.push(privmsg.clone());
  114. }
  115. }
  116. Ordering::Greater => self.orphans.push(Orphan::new(privmsg)),
  117. }
  118. self.update();
  119. }
  120. pub fn load(&self) -> Vec<Privmsg> {
  121. self.buffer.iter().cloned().collect::<Vec<Privmsg>>()
  122. }
  123. pub fn get_msg_by_term(&self, term: u64) -> Option<Privmsg> {
  124. self.buffer.iter().find(|p| p.term == term).cloned()
  125. }
  126. pub fn len(&self) -> usize {
  127. self.buffer.len()
  128. }
  129. pub fn is_empty(&self) -> bool {
  130. self.buffer.is_empty()
  131. }
  132. pub fn last_term(&self) -> u64 {
  133. match self.buffer.len() {
  134. 0 => 0,
  135. n => self.buffer.items[n - 1].term,
  136. }
  137. }
  138. pub fn fetch_msgs(&self, term: u64) -> Vec<Privmsg> {
  139. self.buffer.iter().take_while(|p| p.term >= term).cloned().collect()
  140. }
  141. fn update(&mut self) {
  142. self.sort_orphans();
  143. self.update_orphans();
  144. self.sort_buffer();
  145. }
  146. fn sort_buffer(&mut self) {
  147. self.buffer.as_slice().sort_by(|a, b| match a.term.cmp(&b.term) {
  148. Ordering::Equal => a.timestamp.cmp(&b.timestamp),
  149. o => o,
  150. });
  151. }
  152. fn sort_orphans(&mut self) {
  153. self.orphans.as_slice().sort_by(|a, b| match a.msg.term.cmp(&b.msg.term) {
  154. Ordering::Equal => a.msg.timestamp.cmp(&b.msg.timestamp),
  155. o => o,
  156. });
  157. }
  158. fn oprhan_is_valid(orphan: &Orphan) -> bool {
  159. (orphan.timestamp + settings::LIFETIME_FOR_ORPHAN) > Utc::now().timestamp()
  160. }
  161. fn update_orphans(&mut self) {
  162. for orphan in self.orphans.clone().iter() {
  163. let privmsg = orphan.msg.clone();
  164. if !Self::oprhan_is_valid(orphan) {
  165. self.orphans.remove(orphan);
  166. continue
  167. }
  168. match privmsg.term.cmp(&(self.last_term() + 1)) {
  169. Ordering::Equal => {
  170. self.buffer.push(privmsg.clone());
  171. self.orphans.remove(orphan);
  172. }
  173. Ordering::Less => {
  174. if let Some(msg) = self.get_msg_by_term(privmsg.term) {
  175. if (msg.timestamp - privmsg.timestamp) <= settings::TERM_MAX_TIME_DIFFERENCE
  176. {
  177. self.buffer.push(privmsg.clone());
  178. }
  179. } else {
  180. self.buffer.push(privmsg.clone());
  181. }
  182. self.orphans.remove(orphan);
  183. }
  184. Ordering::Greater => {}
  185. }
  186. }
  187. }
  188. }
  189. #[derive(Clone, PartialEq, Eq)]
  190. struct Orphan {
  191. msg: Privmsg,
  192. timestamp: i64,
  193. }
  194. impl Orphan {
  195. fn new(privmsg: &Privmsg) -> Self {
  196. Self { msg: privmsg.clone(), timestamp: Utc::now().timestamp() }
  197. }
  198. }
  199. pub struct SeenIds {
  200. ids: Mutex<RingBuffer<u64>>,
  201. }
  202. impl Default for SeenIds {
  203. fn default() -> Self {
  204. Self::new()
  205. }
  206. }
  207. impl SeenIds {
  208. pub fn new() -> Self {
  209. Self { ids: Mutex::new(RingBuffer::new(settings::SIZE_OF_IDSS_BUFFER)) }
  210. }
  211. pub async fn push(&self, id: u64) -> bool {
  212. let ids = &mut self.ids.lock().await;
  213. if !ids.contains(&id) {
  214. ids.push(id);
  215. return true
  216. }
  217. false
  218. }
  219. }
  220. pub struct UMsgs {
  221. msgs: Mutex<BTreeMap<String, Privmsg>>,
  222. }
  223. impl Default for UMsgs {
  224. fn default() -> Self {
  225. Self::new()
  226. }
  227. }
  228. impl UMsgs {
  229. pub fn new() -> Self {
  230. Self { msgs: Mutex::new(BTreeMap::new()) }
  231. }
  232. pub async fn len(&self) -> usize {
  233. self.msgs.lock().await.len()
  234. }
  235. pub async fn contains(&self, key: &str) -> bool {
  236. self.msgs.lock().await.contains_key(key)
  237. }
  238. pub async fn remove(&self, key: &str) -> Option<Privmsg> {
  239. self.msgs.lock().await.remove(key)
  240. }
  241. pub async fn get(&self, key: &str) -> Option<Privmsg> {
  242. self.msgs.lock().await.get(key).cloned()
  243. }
  244. pub async fn load(&self) -> BTreeMap<String, Privmsg> {
  245. self.msgs.lock().await.clone()
  246. }
  247. pub async fn inc_read_confirms(&self, key: &str) -> bool {
  248. if let Some(msg) = self.msgs.lock().await.get_mut(key) {
  249. msg.read_confirms += 1;
  250. return true
  251. }
  252. false
  253. }
  254. pub async fn insert(&self, msg: &Privmsg) -> String {
  255. let mut hasher = Ripemd160::new();
  256. hasher.update(msg.to_string() + &msg.term.to_string() + &msg.timestamp.to_string());
  257. let key = hex::encode(hasher.finalize());
  258. let msgs = &mut self.msgs.lock().await;
  259. if msgs.len() == settings::SIZE_OF_MSGS_BUFFER {
  260. let first_key = msgs.iter().next_back().unwrap().0.clone();
  261. msgs.remove(&first_key);
  262. }
  263. msgs.insert(key.clone(), msg.clone());
  264. key
  265. }
  266. }
  267. #[cfg(test)]
  268. mod tests {
  269. use super::*;
  270. use crate::Privmsg;
  271. use rand::{seq::SliceRandom, thread_rng};
  272. #[test]
  273. fn test_ring_buffer() {
  274. let mut b = RingBuffer::<&str>::new(3);
  275. b.push("h1");
  276. b.push("h2");
  277. b.push("h3");
  278. assert_eq!(b.items, vec!["h1", "h2", "h3"]);
  279. assert_eq!(b.items.capacity(), 3);
  280. b.push("h4");
  281. assert_eq!(b.items, vec!["h2", "h3", "h4"]);
  282. assert_eq!(b.items.capacity(), 3);
  283. b.push("h5");
  284. b.push("h6");
  285. b.push("h7");
  286. b.push("h8");
  287. b.push("h9");
  288. assert_eq!(b.len(), 3);
  289. assert_eq!(b.iter().last().unwrap(), &"h9");
  290. }
  291. #[async_std::test]
  292. async fn test_privmsgs_buffer() {
  293. let pms = PrivmsgsBuffer::new();
  294. //
  295. // Fill the buffer with random generated terms in range 0..3001
  296. //
  297. let mut terms: Vec<u64> = (1..3001).collect();
  298. terms.shuffle(&mut thread_rng());
  299. for term in terms {
  300. let privmsg = Privmsg::new("nick", "#dev", &format!("message_{}", term), term);
  301. pms.push(&privmsg).await;
  302. }
  303. assert_eq!(pms.len().await, 3000);
  304. assert_eq!(pms.last_term().await, 3000);
  305. //
  306. // Fill the buffer with random generated terms in range 2000..4001
  307. // Since the buffer len now is 3000 it will take only the terms from
  308. // 3001 to 4000 without overwriting
  309. //
  310. let mut terms: Vec<u64> = (2000..4001).collect();
  311. terms.shuffle(&mut thread_rng());
  312. for term in terms {
  313. let privmsg = Privmsg::new("nick", "#dev", &format!("message_{}", term), term);
  314. pms.push(&privmsg).await;
  315. }
  316. assert_eq!(pms.len().await, settings::SIZE_OF_MSGS_BUFFER);
  317. assert_eq!(pms.last_term().await, 4000);
  318. //
  319. // Fill the buffer with random generated terms in range 4000..7001
  320. // Since the buffer max size is SIZE_OF_MSGS_BUFFER it has to remove the old msges
  321. //
  322. let mut terms: Vec<u64> = (4001..7001).collect();
  323. terms.shuffle(&mut thread_rng());
  324. for term in terms {
  325. let privmsg = Privmsg::new("nick", "#dev", &format!("message_{}", term), term);
  326. pms.push(&privmsg).await;
  327. }
  328. assert_eq!(pms.len().await, settings::SIZE_OF_MSGS_BUFFER);
  329. assert_eq!(pms.last_term().await, 7000);
  330. }
  331. #[async_std::test]
  332. async fn test_seen_ids() {
  333. let seen_ids = SeenIds::default();
  334. assert!(seen_ids.push(3000).await);
  335. assert!(seen_ids.push(3001).await);
  336. assert!(!seen_ids.push(3000).await);
  337. }
  338. #[async_std::test]
  339. async fn test_unread_msgs() {
  340. let unread_msgs = UMsgs::default();
  341. let p = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 0);
  342. let p_k = unread_msgs.insert(&p).await;
  343. let p2 = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 1);
  344. let p2_k = unread_msgs.insert(&p2).await;
  345. let p3 = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 2);
  346. let p3_k = unread_msgs.insert(&p3).await;
  347. assert_eq!(unread_msgs.len().await, 3);
  348. assert_eq!(unread_msgs.get(&p_k).await, Some(p.clone()));
  349. assert_eq!(unread_msgs.get(&p2_k).await, Some(p2));
  350. assert_eq!(unread_msgs.get(&p3_k).await, Some(p3));
  351. assert!(unread_msgs.inc_read_confirms(&p_k).await);
  352. assert!(!unread_msgs.inc_read_confirms("NONE KEY").await);
  353. assert_ne!(unread_msgs.get(&p_k).await, Some(p));
  354. assert_eq!(unread_msgs.get(&p_k).await.unwrap().read_confirms, 1);
  355. }
  356. }