1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#![warn(missing_docs)]
#![allow(clippy::ptr_offset_with_cast)]
use std::str::FromStr;
use async_trait::async_trait;
use itertools::Itertools;
use serde::de::DeserializeOwned;
use sled;
use super::PersistenceStorageOperation;
use super::PersistenceStorageReadAndWrite;
use super::PersistenceStorageRemove;
use crate::err::Error;
use crate::err::Result;
trait KvStorageBasic {
fn get_db(&self) -> &sled::Db;
}
#[allow(dead_code)]
pub struct KvStorage {
db: sled::Db,
cap: usize,
path: String,
}
impl KvStorage {
pub async fn new_with_cap_and_path<P>(cap: usize, path: P) -> Result<Self>
where P: AsRef<std::path::Path> {
let db = sled::Config::new()
.path(path.as_ref())
.mode(sled::Mode::HighThroughput)
.cache_capacity(cap as u64)
.open()
.map_err(Error::SledError)?;
Ok(Self {
db,
cap,
path: path.as_ref().to_string_lossy().to_string(),
})
}
pub async fn new_with_cap(cap: usize) -> Result<Self> {
Self::new_with_cap_and_path(cap, "./data").await
}
pub async fn new_with_path<P>(path: P) -> Result<Self>
where P: AsRef<std::path::Path> {
Self::new_with_cap_and_path(200000000, path).await
}
pub async fn new() -> Result<Self> {
Self::new_with_cap(200000000).await
}
#[cfg(test)]
pub async fn delete(self) -> Result<()> {
let path = self.path.clone();
drop(self);
tokio::fs::remove_dir_all(path.as_str())
.await
.map_err(Error::IOError)?;
Ok(())
}
pub fn random_path(prefix: &str) -> String {
let p = std::path::Path::new(prefix).join(uuid::Uuid::new_v4().to_string());
p.to_string_lossy().to_string()
}
}
impl KvStorageBasic for KvStorage {
fn get_db(&self) -> &sled::Db {
&self.db
}
}
#[async_trait]
impl PersistenceStorageOperation for KvStorage {
async fn clear(&self) -> Result<()> {
self.db.clear().map_err(Error::SledError)?;
Ok(())
}
async fn count(&self) -> Result<u64> {
Ok(self.db.len() as u64)
}
async fn max_size(&self) -> Result<usize> {
Ok(self.cap)
}
async fn total_size(&self) -> Result<usize> {
Ok(self.db.len())
}
async fn prune(&self) -> Result<()> {
Ok(())
}
async fn close(self) -> Result<()> {
Ok(())
}
}
#[async_trait]
impl<K, V, I> PersistenceStorageReadAndWrite<K, V> for I
where
K: ToString + FromStr + std::marker::Sync + Send,
V: DeserializeOwned + serde::Serialize + std::marker::Sync + Send,
I: PersistenceStorageOperation + std::marker::Sync + KvStorageBasic,
{
async fn get(&self, key: &K) -> Result<V> {
let k = key.to_string();
let k = k.as_bytes();
let v = self
.get_db()
.get(k)
.map_err(Error::SledError)?
.ok_or(Error::EntryNotFound)?;
bincode::deserialize(v.as_ref()).map_err(Error::BincodeDeserialize)
}
async fn put(&self, key: &K, value: &V) -> Result<()> {
self.prune().await?;
let data = bincode::serialize(value).map_err(Error::BincodeSerialize)?;
self.get_db()
.insert(key.to_string().as_bytes(), data)
.map_err(Error::SledError)?;
Ok(())
}
async fn get_all(&self) -> Result<Vec<(K, V)>> {
let iter = self.get_db().iter();
Ok(iter
.flatten()
.flat_map(|(k, v)| {
Some((
K::from_str(std::str::from_utf8(k.as_ref()).ok()?).ok()?,
bincode::deserialize(v.as_ref()).ok()?,
))
})
.collect_vec())
}
}
#[async_trait]
impl<K, I> PersistenceStorageRemove<K> for I
where
K: ToString + std::marker::Sync,
I: PersistenceStorageOperation + std::marker::Sync + KvStorageBasic,
{
async fn remove(&self, key: &K) -> Result<()> {
self.get_db()
.remove(key.to_string().as_bytes())
.map_err(Error::SledError)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use serde::Deserialize;
use serde::Serialize;
use super::*;
#[derive(Debug, Serialize, Deserialize)]
struct TestStorageStruct {
content: String,
}
#[tokio::test]
async fn test_kv_storage_put_delete() {
let storage = KvStorage::new_with_cap_and_path(4096, "temp/db")
.await
.unwrap();
let key1 = "test1".to_owned();
let data1 = TestStorageStruct {
content: "test1".to_string(),
};
storage.put(&key1, &data1).await.unwrap();
let count1 = storage.count().await.unwrap();
assert!(count1 == 1, "expect count1.1 is {}, got {}", 1, count1);
let got_v1: TestStorageStruct = storage.get(&key1).await.unwrap();
assert!(
got_v1.content.eq(data1.content.as_str()),
"expect value1 is {}, got {}",
data1.content,
got_v1.content
);
let key2 = "test2".to_owned();
let data2 = TestStorageStruct {
content: "test2".to_string(),
};
storage.put(&key2, &data2).await.unwrap();
let count_got_2 = storage.count().await.unwrap();
assert!(count_got_2 == 2, "expect count 2, got {}", count_got_2);
let all_entries: Vec<(String, TestStorageStruct)> = storage.get_all().await.unwrap();
assert!(
all_entries.len() == 2,
"all_entries len expect 2, got {}",
all_entries.len()
);
let keys = vec![key1, key2];
let values = vec![data1.content, data2.content];
assert!(
all_entries
.iter()
.any(|(k, v)| { keys.contains(k) && values.contains(&v.content) }),
"not found items"
);
storage.clear().await.unwrap();
let count1 = storage.count().await.unwrap();
assert!(count1 == 0, "expect count1.2 is {}, got {}", 0, count1);
storage.get_db().flush_async().await.unwrap();
drop(storage)
}
}