buffers.rs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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(Default, 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. #[derive(Default)]
  60. pub struct PrivmsgsBuffer {
  61. msgs: Mutex<OrderingAlgo>,
  62. }
  63. impl PrivmsgsBuffer {
  64. pub fn new() -> Self {
  65. Self { msgs: Mutex::new(OrderingAlgo::new()) }
  66. }
  67. pub async fn push(&self, privmsg: &Privmsg) {
  68. self.msgs.lock().await.push(privmsg);
  69. }
  70. pub async fn load(&self) -> Vec<Privmsg> {
  71. self.msgs.lock().await.load()
  72. }
  73. pub async fn get_msg_by_term(&self, term: u64) -> Option<Privmsg> {
  74. self.msgs.lock().await.get_msg_by_term(term)
  75. }
  76. pub async fn len(&self) -> usize {
  77. self.msgs.lock().await.len()
  78. }
  79. pub async fn is_empty(&self) -> bool {
  80. self.msgs.lock().await.is_empty()
  81. }
  82. pub async fn last_term(&self) -> u64 {
  83. self.msgs.lock().await.last_term()
  84. }
  85. pub async fn fetch_msgs(&self, term: u64) -> Vec<Privmsg> {
  86. self.msgs.lock().await.fetch_msgs(term)
  87. }
  88. }
  89. pub struct OrderingAlgo {
  90. buffer: RingBuffer<Privmsg>,
  91. orphans: RingBuffer<Orphan>,
  92. }
  93. impl Default for OrderingAlgo {
  94. fn default() -> Self {
  95. Self::new()
  96. }
  97. }
  98. impl OrderingAlgo {
  99. pub fn new() -> Self {
  100. Self {
  101. buffer: RingBuffer::new(settings::SIZE_OF_MSGS_BUFFER),
  102. orphans: RingBuffer::new(settings::SIZE_OF_MSGS_BUFFER),
  103. }
  104. }
  105. pub fn push(&mut self, privmsg: &Privmsg) {
  106. match privmsg.term.cmp(&(self.last_term() + 1)) {
  107. Ordering::Equal => self.buffer.push(privmsg.clone()),
  108. Ordering::Less => {
  109. if let Some(msg) = self.get_msg_by_term(privmsg.term) {
  110. if (msg.timestamp - privmsg.timestamp) <= settings::TERM_MAX_TIME_DIFFERENCE {
  111. self.buffer.push(privmsg.clone());
  112. }
  113. } else {
  114. self.buffer.push(privmsg.clone());
  115. }
  116. }
  117. Ordering::Greater => self.orphans.push(Orphan::new(privmsg)),
  118. }
  119. self.update();
  120. }
  121. pub fn load(&self) -> Vec<Privmsg> {
  122. self.buffer.iter().cloned().collect::<Vec<Privmsg>>()
  123. }
  124. pub fn get_msg_by_term(&self, term: u64) -> Option<Privmsg> {
  125. self.buffer.iter().find(|p| p.term == term).cloned()
  126. }
  127. pub fn len(&self) -> usize {
  128. self.buffer.len()
  129. }
  130. pub fn is_empty(&self) -> bool {
  131. self.buffer.is_empty()
  132. }
  133. pub fn last_term(&self) -> u64 {
  134. match self.buffer.len() {
  135. 0 => 0,
  136. n => self.buffer.items[n - 1].term,
  137. }
  138. }
  139. pub fn fetch_msgs(&self, term: u64) -> Vec<Privmsg> {
  140. self.buffer.iter().take_while(|p| p.term >= term).cloned().collect()
  141. }
  142. fn update(&mut self) {
  143. self.sort_orphans();
  144. self.update_orphans();
  145. self.sort_buffer();
  146. }
  147. fn sort_buffer(&mut self) {
  148. self.buffer.as_slice().sort_by(|a, b| match a.term.cmp(&b.term) {
  149. Ordering::Equal => a.timestamp.cmp(&b.timestamp),
  150. o => o,
  151. });
  152. }
  153. fn sort_orphans(&mut self) {
  154. self.orphans.as_slice().sort_by(|a, b| match a.msg.term.cmp(&b.msg.term) {
  155. Ordering::Equal => a.msg.timestamp.cmp(&b.msg.timestamp),
  156. o => o,
  157. });
  158. }
  159. fn oprhan_is_valid(orphan: &Orphan) -> bool {
  160. (orphan.timestamp + settings::LIFETIME_FOR_ORPHAN) > Utc::now().timestamp()
  161. }
  162. fn update_orphans(&mut self) {
  163. for orphan in self.orphans.clone().iter() {
  164. let privmsg = orphan.msg.clone();
  165. if !Self::oprhan_is_valid(orphan) {
  166. self.orphans.remove(orphan);
  167. continue
  168. }
  169. match privmsg.term.cmp(&(self.last_term() + 1)) {
  170. Ordering::Equal => {
  171. self.buffer.push(privmsg.clone());
  172. self.orphans.remove(orphan);
  173. }
  174. Ordering::Less => {
  175. if let Some(msg) = self.get_msg_by_term(privmsg.term) {
  176. if (msg.timestamp - privmsg.timestamp) <= settings::TERM_MAX_TIME_DIFFERENCE
  177. {
  178. self.buffer.push(privmsg.clone());
  179. }
  180. } else {
  181. self.buffer.push(privmsg.clone());
  182. }
  183. self.orphans.remove(orphan);
  184. }
  185. Ordering::Greater => {}
  186. }
  187. }
  188. }
  189. }
  190. #[derive(Clone, PartialEq, Eq)]
  191. struct Orphan {
  192. msg: Privmsg,
  193. timestamp: i64,
  194. }
  195. impl Orphan {
  196. fn new(privmsg: &Privmsg) -> Self {
  197. Self { msg: privmsg.clone(), timestamp: Utc::now().timestamp() }
  198. }
  199. }
  200. pub struct SeenIds {
  201. ids: RingBuffer<u64>,
  202. }
  203. impl Default for SeenIds {
  204. fn default() -> Self {
  205. Self::new()
  206. }
  207. }
  208. impl SeenIds {
  209. pub fn new() -> Self {
  210. Self { ids: RingBuffer::new(settings::SIZE_OF_IDSS_BUFFER) }
  211. }
  212. pub fn push(&mut self, id: u64) -> bool {
  213. if !self.ids.contains(&id) {
  214. self.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. #[test]
  272. fn test_ring_buffer() {
  273. let mut b = RingBuffer::<&str>::new(3);
  274. b.push("h1");
  275. b.push("h2");
  276. b.push("h3");
  277. assert_eq!(b.items, vec!["h1", "h2", "h3"]);
  278. assert_eq!(b.items.capacity(), 3);
  279. b.push("h4");
  280. assert_eq!(b.items, vec!["h2", "h3", "h4"]);
  281. assert_eq!(b.items.capacity(), 3);
  282. b.push("h5");
  283. b.push("h6");
  284. b.push("h7");
  285. b.push("h8");
  286. b.push("h9");
  287. assert_eq!(b.len(), 3);
  288. assert_eq!(b.iter().last().unwrap(), &"h9");
  289. }
  290. #[async_std::test]
  291. async fn test_unread_msgs() {
  292. let unread_msgs = UMsgs::default();
  293. let p = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 0);
  294. let p_k = unread_msgs.insert(&p).await;
  295. let p2 = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 1);
  296. let p2_k = unread_msgs.insert(&p2).await;
  297. let p3 = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 2);
  298. let p3_k = unread_msgs.insert(&p3).await;
  299. assert_eq!(unread_msgs.len().await, 3);
  300. assert_eq!(unread_msgs.get(&p_k).await, Some(p.clone()));
  301. assert_eq!(unread_msgs.get(&p2_k).await, Some(p2));
  302. assert_eq!(unread_msgs.get(&p3_k).await, Some(p3));
  303. assert!(unread_msgs.inc_read_confirms(&p_k).await);
  304. assert!(!unread_msgs.inc_read_confirms("NONE KEY").await);
  305. assert_ne!(unread_msgs.get(&p_k).await, Some(p));
  306. assert_eq!(unread_msgs.get(&p_k).await.unwrap().read_confirms, 1);
  307. }
  308. }