mod.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 std::collections::HashMap;
  19. use async_std::sync::{Arc, Mutex};
  20. use chrono::Utc;
  21. use log::{debug, error};
  22. use crate::{net, util::async_util, Result};
  23. mod consensus;
  24. mod consensus_candidate;
  25. mod consensus_follower;
  26. mod consensus_leader;
  27. mod datastore;
  28. mod primitives;
  29. mod protocol_raft;
  30. mod settings;
  31. pub use consensus::{gen_id, Raft};
  32. pub use datastore::DataStore;
  33. pub use primitives::NetMsg;
  34. pub use protocol_raft::ProtocolRaft;
  35. pub use settings::RaftSettings;
  36. // Auxilary function to periodically prun items, based on when they were received.
  37. async fn prune_map<T: Clone + Eq + std::hash::Hash>(
  38. map: Arc<Mutex<HashMap<T, i64>>>,
  39. seen_duration: i64,
  40. ) {
  41. loop {
  42. async_util::sleep(seen_duration as u64).await;
  43. debug!(target: "raft", "Pruning item in map");
  44. let now = Utc::now().timestamp();
  45. let mut map = map.lock().await;
  46. for (k, v) in map.clone().iter() {
  47. if now - v > seen_duration {
  48. map.remove(k);
  49. }
  50. }
  51. }
  52. }
  53. async fn p2p_send_loop(receiver: smol::channel::Receiver<NetMsg>, p2p: net::P2pPtr) -> Result<()> {
  54. loop {
  55. let msg: NetMsg = receiver.recv().await?;
  56. if let Err(e) = p2p.broadcast(msg).await {
  57. error!(target: "raft", "error occurred during broadcasting a msg: {}", e);
  58. continue
  59. }
  60. }
  61. }