datastore.rs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. use std::marker::PhantomData;
  2. use log::debug;
  3. use sled::Batch;
  4. use crate::{
  5. util::serial::{deserialize, serialize, Decodable, Encodable},
  6. Error, Result,
  7. };
  8. use super::primitives::{Log, NodeId};
  9. const SLED_LOGS_TREE: &[u8] = b"_logs";
  10. const SLED_COMMITS_TREE: &[u8] = b"_commits";
  11. const _SLED_COMMITS_LENGTH_TREE: &[u8] = b"_commit_length";
  12. const SLED_VOTED_FOR_TREE: &[u8] = b"_voted_for";
  13. const SLED_CURRENT_TERM_TREE: &[u8] = b"_current_term";
  14. const SLED_ID_TREE: &[u8] = b"_id";
  15. pub struct DataStore<T> {
  16. _db: sled::Db,
  17. pub logs: DataTree<Log>,
  18. pub commits: DataTree<T>,
  19. pub voted_for: DataTree<Option<NodeId>>,
  20. pub current_term: DataTree<u64>,
  21. pub id: DataTree<NodeId>,
  22. }
  23. impl<T: Encodable + Decodable> DataStore<T> {
  24. pub fn new(db_path: &str) -> Result<Self> {
  25. let _db = sled::open(db_path)?;
  26. let logs = DataTree::new(&_db, SLED_LOGS_TREE)?;
  27. let commits = DataTree::new(&_db, SLED_COMMITS_TREE)?;
  28. let voted_for = DataTree::new(&_db, SLED_VOTED_FOR_TREE)?;
  29. let current_term = DataTree::new(&_db, SLED_CURRENT_TERM_TREE)?;
  30. let id = DataTree::new(&_db, SLED_ID_TREE)?;
  31. Ok(Self { _db, logs, commits, voted_for, current_term, id })
  32. }
  33. pub async fn flush(&self) -> Result<()> {
  34. debug!(target: "raft", "DataStore flush");
  35. self._db.flush_async().await?;
  36. Ok(())
  37. }
  38. }
  39. pub struct DataTree<T> {
  40. tree: sled::Tree,
  41. phantom: PhantomData<T>,
  42. }
  43. impl<T: Decodable + Encodable> DataTree<T> {
  44. pub fn new(db: &sled::Db, tree_name: &[u8]) -> Result<Self> {
  45. let tree = db.open_tree(tree_name)?;
  46. Ok(Self { tree, phantom: PhantomData })
  47. }
  48. pub fn insert(&self, data: &T) -> Result<()> {
  49. let serialized = serialize(data);
  50. let last_index: u64 = if let Some(d) = self.tree.last()? {
  51. u64::from_be_bytes(d.0.to_vec().try_into().unwrap()) + 1
  52. } else {
  53. 0
  54. };
  55. self.tree.insert(last_index.to_be_bytes(), serialized)?;
  56. Ok(())
  57. }
  58. pub fn wipe_insert_all(&self, data: &[T]) -> Result<()> {
  59. self.tree.clear()?;
  60. let mut batch = Batch::default();
  61. for (i, d) in data.iter().enumerate() {
  62. let serialized = serialize(d);
  63. batch.insert(&(i as u64).to_be_bytes(), serialized);
  64. }
  65. self.tree.apply_batch(batch)?;
  66. Ok(())
  67. }
  68. pub fn get_all(&self) -> Result<Vec<T>> {
  69. let mut ret: Vec<T> = Vec::new();
  70. for i in self.tree.iter() {
  71. let da = deserialize(&i?.1)?;
  72. ret.push(da)
  73. }
  74. Ok(ret)
  75. }
  76. pub fn len(&self) -> u64 {
  77. self.tree.len() as u64
  78. }
  79. pub fn get_last(&self) -> Result<Option<T>> {
  80. if let Some(found) = self.tree.last()? {
  81. let da = deserialize(&found.1)?;
  82. return Ok(Some(da))
  83. }
  84. Ok(None)
  85. }
  86. pub fn get(&self, index: u64) -> Result<T> {
  87. let index_bytes = index.to_be_bytes();
  88. if let Some(found) = self.tree.get(index_bytes)? {
  89. let da = deserialize(&found)?;
  90. return Ok(da)
  91. }
  92. Err(Error::RaftError(format!(
  93. "Unable to get the item with index {} {:?}",
  94. index,
  95. self.is_empty()
  96. )))
  97. }
  98. pub fn is_empty(&self) -> bool {
  99. self.tree.is_empty()
  100. }
  101. }