buffers.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use async_std::sync::{Arc, Mutex};
  19. use std::{
  20. cmp::Ordering,
  21. collections::{BTreeMap, VecDeque},
  22. };
  23. use chrono::Utc;
  24. use ripemd::{Digest, Ripemd160};
  25. use crate::{settings, Privmsg};
  26. pub type Buffers = Arc<Msgs>;
  27. pub struct Msgs {
  28. pub privmsgs: PrivmsgsBuffer,
  29. pub unread_msgs: UMsgs,
  30. pub seen_ids: SeenIds,
  31. }
  32. pub fn create_buffers() -> Buffers {
  33. let seen_ids = SeenIds::new();
  34. let privmsgs = PrivmsgsBuffer::new();
  35. let unread_msgs = UMsgs::new();
  36. Arc::new(Msgs { privmsgs, unread_msgs, seen_ids })
  37. }
  38. #[derive(Default, Clone)]
  39. pub struct RingBuffer<T> {
  40. pub items: VecDeque<T>,
  41. }
  42. impl<T: Eq + PartialEq + Clone> RingBuffer<T> {
  43. pub fn new(capacity: usize) -> Self {
  44. let items = VecDeque::with_capacity(capacity);
  45. Self { items }
  46. }
  47. pub fn push(&mut self, val: T) {
  48. if self.items.len() == self.items.capacity() {
  49. self.items.pop_front();
  50. }
  51. self.items.push_back(val);
  52. }
  53. pub fn contains(&self, val: &T) -> bool {
  54. self.items.contains(val)
  55. }
  56. pub fn len(&self) -> usize {
  57. self.items.len()
  58. }
  59. pub fn is_empty(&self) -> bool {
  60. self.items.is_empty()
  61. }
  62. pub fn as_slice(&mut self) -> &mut [T] {
  63. self.items.make_contiguous()
  64. }
  65. pub fn iter(&self) -> impl Iterator<Item = &T> + DoubleEndedIterator {
  66. self.items.iter()
  67. }
  68. pub fn remove(&mut self, val: &T) -> Option<T> {
  69. if let Some(index) = self.items.iter().position(|v| v == val) {
  70. self.items.remove(index)
  71. } else {
  72. None
  73. }
  74. }
  75. }
  76. #[derive(Default)]
  77. pub struct PrivmsgsBuffer {
  78. msgs: Mutex<OrderingAlgo>,
  79. }
  80. impl PrivmsgsBuffer {
  81. pub fn new() -> Self {
  82. Self { msgs: Mutex::new(OrderingAlgo::new()) }
  83. }
  84. pub async fn push(&self, privmsg: &Privmsg) {
  85. self.msgs.lock().await.push(privmsg);
  86. }
  87. pub async fn load(&self) -> Vec<Privmsg> {
  88. self.msgs.lock().await.load()
  89. }
  90. pub async fn get_msg_by_term(&self, term: u64) -> Option<Privmsg> {
  91. self.msgs.lock().await.get_msg_by_term(term)
  92. }
  93. pub async fn len(&self) -> usize {
  94. self.msgs.lock().await.len()
  95. }
  96. pub async fn is_empty(&self) -> bool {
  97. self.msgs.lock().await.is_empty()
  98. }
  99. pub async fn last_term(&self) -> u64 {
  100. self.msgs.lock().await.last_term()
  101. }
  102. pub async fn fetch_msgs(&self, term: u64) -> Vec<Privmsg> {
  103. self.msgs.lock().await.fetch_msgs(term)
  104. }
  105. }
  106. pub struct OrderingAlgo {
  107. buffer: RingBuffer<Privmsg>,
  108. orphans: RingBuffer<Orphan>,
  109. }
  110. impl Default for OrderingAlgo {
  111. fn default() -> Self {
  112. Self::new()
  113. }
  114. }
  115. impl OrderingAlgo {
  116. pub fn new() -> Self {
  117. Self {
  118. buffer: RingBuffer::new(settings::SIZE_OF_MSGS_BUFFER),
  119. orphans: RingBuffer::new(settings::SIZE_OF_MSGS_BUFFER),
  120. }
  121. }
  122. pub fn push(&mut self, privmsg: &Privmsg) {
  123. match privmsg.term.cmp(&(self.last_term() + 1)) {
  124. Ordering::Equal => self.buffer.push(privmsg.clone()),
  125. Ordering::Less => {
  126. if let Some(msg) = self.get_msg_by_term(privmsg.term) {
  127. if (msg.timestamp - privmsg.timestamp) <= settings::TERM_MAX_TIME_DIFFERENCE {
  128. self.buffer.push(privmsg.clone());
  129. }
  130. } else {
  131. self.buffer.push(privmsg.clone());
  132. }
  133. }
  134. Ordering::Greater => self.orphans.push(Orphan::new(privmsg)),
  135. }
  136. self.update();
  137. }
  138. pub fn load(&self) -> Vec<Privmsg> {
  139. self.buffer.iter().cloned().collect::<Vec<Privmsg>>()
  140. }
  141. pub fn get_msg_by_term(&self, term: u64) -> Option<Privmsg> {
  142. self.buffer.iter().find(|p| p.term == term).cloned()
  143. }
  144. pub fn len(&self) -> usize {
  145. self.buffer.len()
  146. }
  147. pub fn is_empty(&self) -> bool {
  148. self.buffer.is_empty()
  149. }
  150. pub fn last_term(&self) -> u64 {
  151. match self.buffer.len() {
  152. 0 => 0,
  153. n => self.buffer.items[n - 1].term,
  154. }
  155. }
  156. pub fn fetch_msgs(&self, term: u64) -> Vec<Privmsg> {
  157. self.buffer.iter().take_while(|p| p.term >= term).cloned().collect()
  158. }
  159. fn update(&mut self) {
  160. self.sort_orphans();
  161. self.update_orphans();
  162. self.sort_buffer();
  163. }
  164. fn sort_buffer(&mut self) {
  165. self.buffer.as_slice().sort_by(|a, b| match a.term.cmp(&b.term) {
  166. Ordering::Equal => a.timestamp.cmp(&b.timestamp),
  167. o => o,
  168. });
  169. }
  170. fn sort_orphans(&mut self) {
  171. self.orphans.as_slice().sort_by(|a, b| match a.msg.term.cmp(&b.msg.term) {
  172. Ordering::Equal => a.msg.timestamp.cmp(&b.msg.timestamp),
  173. o => o,
  174. });
  175. }
  176. fn oprhan_is_valid(orphan: &Orphan) -> bool {
  177. (orphan.timestamp + settings::LIFETIME_FOR_ORPHAN) > Utc::now().timestamp()
  178. }
  179. fn update_orphans(&mut self) {
  180. for orphan in self.orphans.clone().iter() {
  181. let privmsg = orphan.msg.clone();
  182. if !Self::oprhan_is_valid(orphan) {
  183. self.orphans.remove(orphan);
  184. continue
  185. }
  186. match privmsg.term.cmp(&(self.last_term() + 1)) {
  187. Ordering::Equal => {
  188. self.buffer.push(privmsg.clone());
  189. self.orphans.remove(orphan);
  190. }
  191. Ordering::Less => {
  192. if let Some(msg) = self.get_msg_by_term(privmsg.term) {
  193. if (msg.timestamp - privmsg.timestamp) <= settings::TERM_MAX_TIME_DIFFERENCE
  194. {
  195. self.buffer.push(privmsg.clone());
  196. }
  197. } else {
  198. self.buffer.push(privmsg.clone());
  199. }
  200. self.orphans.remove(orphan);
  201. }
  202. Ordering::Greater => {}
  203. }
  204. }
  205. }
  206. }
  207. #[derive(Clone, PartialEq, Eq)]
  208. struct Orphan {
  209. msg: Privmsg,
  210. timestamp: i64,
  211. }
  212. impl Orphan {
  213. fn new(privmsg: &Privmsg) -> Self {
  214. Self { msg: privmsg.clone(), timestamp: Utc::now().timestamp() }
  215. }
  216. }
  217. pub struct SeenIds {
  218. ids: RingBuffer<u64>,
  219. }
  220. impl Default for SeenIds {
  221. fn default() -> Self {
  222. Self::new()
  223. }
  224. }
  225. impl SeenIds {
  226. pub fn new() -> Self {
  227. Self { ids: RingBuffer::new(settings::SIZE_OF_IDSS_BUFFER) }
  228. }
  229. pub fn push(&mut self, id: u64) -> bool {
  230. if !self.ids.contains(&id) {
  231. self.ids.push(id);
  232. return true
  233. }
  234. false
  235. }
  236. }
  237. pub struct UMsgs {
  238. msgs: Mutex<BTreeMap<String, Privmsg>>,
  239. }
  240. impl Default for UMsgs {
  241. fn default() -> Self {
  242. Self::new()
  243. }
  244. }
  245. impl UMsgs {
  246. pub fn new() -> Self {
  247. Self { msgs: Mutex::new(BTreeMap::new()) }
  248. }
  249. pub async fn len(&self) -> usize {
  250. self.msgs.lock().await.len()
  251. }
  252. pub async fn contains(&self, key: &str) -> bool {
  253. self.msgs.lock().await.contains_key(key)
  254. }
  255. pub async fn remove(&self, key: &str) -> Option<Privmsg> {
  256. self.msgs.lock().await.remove(key)
  257. }
  258. pub async fn get(&self, key: &str) -> Option<Privmsg> {
  259. self.msgs.lock().await.get(key).cloned()
  260. }
  261. pub async fn load(&self) -> BTreeMap<String, Privmsg> {
  262. self.msgs.lock().await.clone()
  263. }
  264. pub async fn inc_read_confirms(&self, key: &str) -> bool {
  265. if let Some(msg) = self.msgs.lock().await.get_mut(key) {
  266. msg.read_confirms += 1;
  267. return true
  268. }
  269. false
  270. }
  271. pub async fn insert(&self, msg: &Privmsg) -> String {
  272. let mut hasher = Ripemd160::new();
  273. hasher.update(msg.to_string() + &msg.term.to_string() + &msg.timestamp.to_string());
  274. let key = hex::encode(hasher.finalize());
  275. let msgs = &mut self.msgs.lock().await;
  276. if msgs.len() == settings::SIZE_OF_MSGS_BUFFER {
  277. let first_key = msgs.iter().next_back().unwrap().0.clone();
  278. msgs.remove(&first_key);
  279. }
  280. msgs.insert(key.clone(), msg.clone());
  281. key
  282. }
  283. }
  284. #[cfg(test)]
  285. mod tests {
  286. use super::*;
  287. use crate::Privmsg;
  288. #[test]
  289. fn test_ring_buffer() {
  290. let mut b = RingBuffer::<&str>::new(3);
  291. b.push("h1");
  292. b.push("h2");
  293. b.push("h3");
  294. assert_eq!(b.items, vec!["h1", "h2", "h3"]);
  295. assert_eq!(b.items.capacity(), 3);
  296. b.push("h4");
  297. assert_eq!(b.items, vec!["h2", "h3", "h4"]);
  298. assert_eq!(b.items.capacity(), 3);
  299. b.push("h5");
  300. b.push("h6");
  301. b.push("h7");
  302. b.push("h8");
  303. b.push("h9");
  304. assert_eq!(b.len(), 3);
  305. assert_eq!(b.iter().last().unwrap(), &"h9");
  306. }
  307. #[async_std::test]
  308. async fn test_unread_msgs() {
  309. let unread_msgs = UMsgs::default();
  310. let p = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 0);
  311. let p_k = unread_msgs.insert(&p).await;
  312. let p2 = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 1);
  313. let p2_k = unread_msgs.insert(&p2).await;
  314. let p3 = Privmsg::new("nick", "#dev", &format!("message_{}", 0), 2);
  315. let p3_k = unread_msgs.insert(&p3).await;
  316. assert_eq!(unread_msgs.len().await, 3);
  317. assert_eq!(unread_msgs.get(&p_k).await, Some(p.clone()));
  318. assert_eq!(unread_msgs.get(&p2_k).await, Some(p2));
  319. assert_eq!(unread_msgs.get(&p3_k).await, Some(p3));
  320. assert!(unread_msgs.inc_read_confirms(&p_k).await);
  321. assert!(!unread_msgs.inc_read_confirms("NONE KEY").await);
  322. assert_ne!(unread_msgs.get(&p_k).await, Some(p));
  323. assert_eq!(unread_msgs.get(&p_k).await.unwrap().read_confirms, 1);
  324. }
  325. }