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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use super::*;
use crate::kbucket;
use libp2p_core::PeerId;
use smallvec::SmallVec;
use std::borrow::Cow;
use std::collections::{hash_map, hash_set, HashMap, HashSet};
use std::iter;
pub struct MemoryStore {
local_key: kbucket::Key<PeerId>,
config: MemoryStoreConfig,
records: HashMap<Key, Record>,
providers: HashMap<Key, SmallVec<[ProviderRecord; K_VALUE.get()]>>,
provided: HashSet<ProviderRecord>,
}
pub struct MemoryStoreConfig {
pub max_records: usize,
pub max_value_bytes: usize,
pub max_providers_per_key: usize,
pub max_provided_keys: usize,
}
impl Default for MemoryStoreConfig {
fn default() -> Self {
Self {
max_records: 1024,
max_value_bytes: 65 * 1024,
max_provided_keys: 1024,
max_providers_per_key: K_VALUE.get(),
}
}
}
impl MemoryStore {
pub fn new(local_id: PeerId) -> Self {
Self::with_config(local_id, Default::default())
}
pub fn with_config(local_id: PeerId, config: MemoryStoreConfig) -> Self {
MemoryStore {
local_key: kbucket::Key::new(local_id),
config,
records: HashMap::default(),
provided: HashSet::default(),
providers: HashMap::default(),
}
}
pub fn retain<F>(&mut self, f: F)
where
F: FnMut(&Key, &mut Record) -> bool
{
self.records.retain(f);
}
}
impl<'a> RecordStore<'a> for MemoryStore {
type RecordsIter = iter::Map<
hash_map::Values<'a, Key, Record>,
fn(&'a Record) -> Cow<'a, Record>
>;
type ProvidedIter = iter::Map<
hash_set::Iter<'a, ProviderRecord>,
fn(&'a ProviderRecord) -> Cow<'a, ProviderRecord>
>;
fn get(&'a self, k: &Key) -> Option<Cow<'_, Record>> {
self.records.get(k).map(Cow::Borrowed)
}
fn put(&'a mut self, r: Record) -> Result<()> {
if r.value.len() >= self.config.max_value_bytes {
return Err(Error::ValueTooLarge)
}
let num_records = self.records.len();
match self.records.entry(r.key.clone()) {
hash_map::Entry::Occupied(mut e) => {
e.insert(r);
}
hash_map::Entry::Vacant(e) => {
if num_records >= self.config.max_records {
return Err(Error::MaxRecords)
}
e.insert(r);
}
}
Ok(())
}
fn remove(&'a mut self, k: &Key) {
self.records.remove(k);
}
fn records(&'a self) -> Self::RecordsIter {
self.records.values().map(Cow::Borrowed)
}
fn add_provider(&'a mut self, record: ProviderRecord) -> Result<()> {
let num_keys = self.providers.len();
let providers = match self.providers.entry(record.key.clone()) {
e@hash_map::Entry::Occupied(_) => e,
e@hash_map::Entry::Vacant(_) => {
if self.config.max_provided_keys == num_keys {
return Err(Error::MaxProvidedKeys)
}
e
}
}.or_insert_with(Default::default);
if let Some(i) = providers.iter().position(|p| p.provider == record.provider) {
providers.as_mut()[i] = record;
} else {
let local_key = self.local_key.clone();
let key = kbucket::Key::new(record.key.clone());
let provider = kbucket::Key::new(record.provider.clone());
if let Some(i) = providers.iter().position(|p| {
let pk = kbucket::Key::new(p.provider.clone());
provider.distance(&key) < pk.distance(&key)
}) {
if local_key.preimage() == &record.provider {
self.provided.insert(record.clone());
}
providers.insert(i, record);
if providers.len() > self.config.max_providers_per_key {
if let Some(p) = providers.pop() {
self.provided.remove(&p);
}
}
}
else if providers.len() < self.config.max_providers_per_key {
if local_key.preimage() == &record.provider {
self.provided.insert(record.clone());
}
providers.push(record);
}
}
Ok(())
}
fn providers(&'a self, key: &Key) -> Vec<ProviderRecord> {
self.providers.get(key).map_or_else(Vec::new, |ps| ps.clone().into_vec())
}
fn provided(&'a self) -> Self::ProvidedIter {
self.provided.iter().map(Cow::Borrowed)
}
fn remove_provider(&'a mut self, key: &Key, provider: &PeerId) {
if let hash_map::Entry::Occupied(mut e) = self.providers.entry(key.clone()) {
let providers = e.get_mut();
if let Some(i) = providers.iter().position(|p| &p.provider == provider) {
let p = providers.remove(i);
self.provided.remove(&p);
}
if providers.len() == 0 {
e.remove();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use multihash::{wrap, Code};
use quickcheck::*;
use rand::Rng;
fn random_multihash() -> Multihash {
wrap(Code::Sha2_256, &rand::thread_rng().gen::<[u8; 32]>())
}
fn distance(r: &ProviderRecord) -> kbucket::Distance {
kbucket::Key::new(r.key.clone())
.distance(&kbucket::Key::new(r.provider.clone()))
}
#[test]
fn put_get_remove_record() {
fn prop(r: Record) {
let mut store = MemoryStore::new(PeerId::random());
assert!(store.put(r.clone()).is_ok());
assert_eq!(Some(Cow::Borrowed(&r)), store.get(&r.key));
store.remove(&r.key);
assert!(store.get(&r.key).is_none());
}
quickcheck(prop as fn(_))
}
#[test]
fn add_get_remove_provider() {
fn prop(r: ProviderRecord) {
let mut store = MemoryStore::new(PeerId::random());
assert!(store.add_provider(r.clone()).is_ok());
assert!(store.providers(&r.key).contains(&r));
store.remove_provider(&r.key, &r.provider);
assert!(!store.providers(&r.key).contains(&r));
}
quickcheck(prop as fn(_))
}
#[test]
fn providers_ordered_by_distance_to_key() {
fn prop(providers: Vec<kbucket::Key<PeerId>>) -> bool {
let mut store = MemoryStore::new(PeerId::random());
let key = Key::from(random_multihash());
let mut records = providers.into_iter().map(|p| {
ProviderRecord::new(key.clone(), p.into_preimage(), Vec::new())
}).collect::<Vec<_>>();
for r in &records {
assert!(store.add_provider(r.clone()).is_ok());
}
records.sort_by(|r1, r2| distance(r1).cmp(&distance(r2)));
records.truncate(store.config.max_providers_per_key);
records == store.providers(&key).to_vec()
}
quickcheck(prop as fn(_) -> _)
}
#[test]
fn provided() {
let id = PeerId::random();
let mut store = MemoryStore::new(id.clone());
let key = random_multihash();
let rec = ProviderRecord::new(key, id.clone(), Vec::new());
assert!(store.add_provider(rec.clone()).is_ok());
assert_eq!(vec![Cow::Borrowed(&rec)], store.provided().collect::<Vec<_>>());
store.remove_provider(&rec.key, &id);
assert_eq!(store.provided().count(), 0);
}
#[test]
fn update_provider() {
let mut store = MemoryStore::new(PeerId::random());
let key = random_multihash();
let prv = PeerId::random();
let mut rec = ProviderRecord::new(key, prv, Vec::new());
assert!(store.add_provider(rec.clone()).is_ok());
assert_eq!(vec![rec.clone()], store.providers(&rec.key).to_vec());
rec.expires = Some(Instant::now());
assert!(store.add_provider(rec.clone()).is_ok());
assert_eq!(vec![rec.clone()], store.providers(&rec.key).to_vec());
}
#[test]
fn max_provided_keys() {
let mut store = MemoryStore::new(PeerId::random());
for _ in 0 .. store.config.max_provided_keys {
let key = random_multihash();
let prv = PeerId::random();
let rec = ProviderRecord::new(key, prv, Vec::new());
let _ = store.add_provider(rec);
}
let key = random_multihash();
let prv = PeerId::random();
let rec = ProviderRecord::new(key, prv, Vec::new());
match store.add_provider(rec) {
Err(Error::MaxProvidedKeys) => {}
_ => panic!("Unexpected result"),
}
}
}