overlay2.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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::{btree_map::Iter, BTreeMap};
  19. use sled::{
  20. transaction::{ConflictableTransactionError, TransactionError},
  21. Batch, IVec, Transactional,
  22. };
  23. #[derive(Debug, PartialEq)]
  24. struct CacheNotFoundError;
  25. struct TreeCache(BTreeMap<IVec, IVec>);
  26. impl TreeCache {
  27. fn new() -> Self {
  28. Self(BTreeMap::new())
  29. }
  30. fn contains_key(&self, key: &IVec) -> bool {
  31. self.0.contains_key(key)
  32. }
  33. fn get(&self, key: &IVec) -> Option<IVec> {
  34. self.0.get(key).cloned()
  35. }
  36. fn insert(&mut self, key: IVec, value: IVec) -> Option<IVec> {
  37. self.0.insert(key, value)
  38. }
  39. fn remove(&mut self, key: &IVec) -> Option<IVec> {
  40. self.0.remove(key)
  41. }
  42. fn iter(&self) -> Iter<'_, IVec, IVec> {
  43. self.0.iter()
  44. }
  45. }
  46. /// We instantiate an overlay on top of a `sled::Tree` directly.
  47. pub struct TreeOverlay {
  48. tree: sled::Tree,
  49. cache: TreeCache,
  50. removed: BTreeMap<IVec, IVec>,
  51. }
  52. impl TreeOverlay {
  53. pub fn new(db: &sled::Tree) -> Self {
  54. Self { tree: db.clone(), cache: TreeCache::new(), removed: BTreeMap::new() }
  55. }
  56. pub fn contains_key(&self, key: &[u8]) -> Result<bool, sled::Error> {
  57. if self.removed.contains_key::<IVec>(&key.into()) {
  58. return Ok(false)
  59. }
  60. if self.cache.contains_key(&key.into()) || self.tree.contains_key(key)? {
  61. return Ok(true)
  62. }
  63. Ok(false)
  64. }
  65. pub fn get(&self, key: &[u8]) -> Result<Option<IVec>, sled::Error> {
  66. if self.removed.contains_key::<IVec>(&key.into()) {
  67. return Ok(None)
  68. }
  69. if let Some(v) = self.cache.get(&key.into()) {
  70. return Ok(Some(v.clone()))
  71. }
  72. self.tree.get(key)
  73. }
  74. pub fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<Option<IVec>, sled::Error> {
  75. let mut prev: Option<IVec> = self.cache.insert(key.into(), value.into());
  76. if self.removed.contains_key::<IVec>(&key.into()) {
  77. self.removed.remove(key);
  78. return Ok(None)
  79. }
  80. if prev.is_none() {
  81. prev = self.tree.get::<IVec>(key.into())?;
  82. }
  83. Ok(prev)
  84. }
  85. pub fn remove(&mut self, key: &[u8]) -> Result<Option<IVec>, sled::Error> {
  86. if self.removed.contains_key::<IVec>(&key.into()) {
  87. return Ok(None)
  88. }
  89. self.removed.insert(key.into(), vec![].into());
  90. Ok(self.cache.remove(&key.into()))
  91. }
  92. pub fn aggregate(&self) -> Option<sled::Batch> {
  93. if self.cache.0.is_empty() && self.removed.is_empty() {
  94. return None
  95. }
  96. let mut batch = Batch::default();
  97. for (k, v) in self.cache.iter() {
  98. batch.insert(k, v);
  99. }
  100. for k in self.removed.keys() {
  101. batch.remove(k);
  102. }
  103. Some(batch)
  104. }
  105. }
  106. /// We instantiate overlays on top of requested
  107. /// sled tree keys.
  108. pub struct SledOverlay2 {
  109. db: sled::Db,
  110. trees: BTreeMap<IVec, sled::Tree>,
  111. caches: BTreeMap<IVec, TreeOverlay>,
  112. }
  113. impl SledOverlay2 {
  114. pub fn new(db: &sled::Db, trees_keys: &[&str]) -> Result<Self, sled::Error> {
  115. let mut trees = BTreeMap::new();
  116. let mut caches = BTreeMap::new();
  117. for tree_key in trees_keys {
  118. let tree = db.open_tree(tree_key)?;
  119. let cache = TreeOverlay::new(&tree);
  120. trees.insert(tree_key.clone().into(), tree.clone());
  121. caches.insert(tree_key.clone().into(), cache);
  122. }
  123. Ok(Self { db: db.clone(), trees, caches })
  124. }
  125. fn get_cache(&self, tree_key: IVec) -> Result<&TreeOverlay, sled::Error> {
  126. if let Some(v) = self.caches.get(&tree_key) {
  127. return Ok(v)
  128. }
  129. Err(sled::Error::CollectionNotFound(tree_key.clone()))
  130. }
  131. fn get_cache_mut(&mut self, tree_key: IVec) -> Result<&mut TreeOverlay, sled::Error> {
  132. if let Some(v) = self.caches.get_mut(&tree_key) {
  133. return Ok(v)
  134. }
  135. Err(sled::Error::CollectionNotFound(tree_key.clone()))
  136. }
  137. pub fn contains_key(&self, tree_key: &str, key: &[u8]) -> Result<bool, sled::Error> {
  138. let cache = self.get_cache(tree_key.clone().into())?;
  139. cache.contains_key(key)
  140. }
  141. pub fn get(&self, tree_key: &str, key: &[u8]) -> Result<Option<IVec>, sled::Error> {
  142. let cache = self.get_cache(tree_key.clone().into())?;
  143. cache.get(key)
  144. }
  145. pub fn insert(
  146. &mut self,
  147. tree_key: &str,
  148. key: &[u8],
  149. value: &[u8],
  150. ) -> Result<Option<IVec>, sled::Error> {
  151. let cache = self.get_cache_mut(tree_key.clone().into())?;
  152. cache.insert(key, value)
  153. }
  154. pub fn remove(&mut self, tree_key: &str, key: &[u8]) -> Result<Option<IVec>, sled::Error> {
  155. let cache = self.get_cache_mut(tree_key.clone().into())?;
  156. cache.remove(key)
  157. }
  158. pub fn execute(&mut self) -> Result<(), TransactionError<sled::Error>> {
  159. let mut trees = vec![];
  160. let mut batches = vec![];
  161. for (key, tree) in &self.trees {
  162. let cache = self.get_cache(key.clone())?;
  163. if let Some(batch) = cache.aggregate() {
  164. trees.push(tree);
  165. batches.push(batch);
  166. }
  167. }
  168. trees.transaction(|trees| {
  169. for (index, tree) in trees.iter().enumerate() {
  170. tree.apply_batch(&batches[index])?;
  171. }
  172. Ok::<(), ConflictableTransactionError<sled::Error>>(())
  173. })?;
  174. self.db.flush()?;
  175. Ok(())
  176. }
  177. }