This repository was archived by the owner on Feb 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathdht_store.rs
More file actions
509 lines (469 loc) · 18.6 KB
/
dht_store.rs
File metadata and controls
509 lines (469 loc) · 18.6 KB
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
use crate::{
content_store::{AddContent, GetContent},
dht::{
aspect_map::{AspectMap, AspectMapBare},
pending_validations::{PendingValidationWithTimeout, ValidationTimeout},
},
};
use holochain_core_types::{
chain_header::ChainHeader,
crud_status::CrudStatus,
eav::{Attribute, EaviQuery, EntityAttributeValueIndex},
entry::Entry,
error::{HcResult, HolochainError},
network::{
entry_aspect::EntryAspect,
query::{GetLinksQueryConfiguration, Pagination, SortOrder},
},
};
use holochain_json_api::{error::JsonError, json::JsonString};
use holochain_locksmith::RwLock;
use holochain_persistence_api::{
cas::{
content::{Address, AddressableContent, Content},
storage::ContentAddressableStorage,
},
eav::{EavFilter, EntityAttributeValueStorage, IndexFilter},
};
use crate::{dht::pending_validations::PendingValidation, state::StateWrapper};
use chrono::{offset::FixedOffset, DateTime};
use holochain_json_api::error::JsonResult;
use holochain_persistence_api::error::PersistenceResult;
use std::{
collections::{BTreeSet, VecDeque},
convert::TryFrom,
sync::Arc,
time::Duration,
};
/// The state-slice for the DHT.
/// Holds the CAS and EAVi that's used for the agent's local shard
/// as well as the holding list, i.e. list of all entries held for the DHT.
#[derive(Clone, Debug)]
pub struct DhtStore {
// Storages holding local shard data
content_storage: Arc<RwLock<dyn ContentAddressableStorage>>,
meta_storage: Arc<RwLock<dyn EntityAttributeValueStorage<Attribute>>>,
/// All the entry aspects that the network has told us to hold
holding_map: AspectMap,
pub(crate) queued_holding_workflows: VecDeque<PendingValidationWithTimeout>,
}
impl PartialEq for DhtStore {
fn eq(&self, other: &DhtStore) -> bool {
let content = &self.content_storage.clone();
let other_content = &other.content_storage.clone();
let meta = &self.meta_storage.clone();
let other_meta = &other.meta_storage.clone();
self.holding_map == other.holding_map
&& (*content.read().unwrap()).get_id() == (*other_content.read().unwrap()).get_id()
&& *meta.read().unwrap() == *other_meta.read().unwrap()
}
}
#[derive(Clone, Debug, Deserialize, Serialize, DefaultJson)]
pub struct DhtStoreSnapshot {
pub holding_map: AspectMapBare,
queued_holding_workflows: VecDeque<PendingValidationWithTimeout>,
}
impl From<&StateWrapper> for DhtStoreSnapshot {
fn from(state: &StateWrapper) -> Self {
DhtStoreSnapshot {
holding_map: state.dht().get_holding_map().bare().clone(),
queued_holding_workflows: state.dht().queued_holding_workflows.clone(),
}
}
}
pub static DHT_STORE_SNAPSHOT_ADDRESS: &str = "DhtStore";
impl AddressableContent for DhtStoreSnapshot {
fn content(&self) -> Content {
self.to_owned().into()
}
fn try_from_content(content: &Content) -> JsonResult<Self> {
Self::try_from(content.to_owned())
}
fn address(&self) -> Address {
DHT_STORE_SNAPSHOT_ADDRESS.into()
}
}
#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)]
pub fn create_get_links_eavi_query<'a>(
address: Address,
link_type: Option<String>,
tag: Option<String>,
) -> Result<EaviQuery<'a>, HolochainError> {
Ok(EaviQuery::new(
Some(address).into(),
EavFilter::predicate(move |attr: Attribute| match attr {
Attribute::LinkTag(query_link_type, query_tag)
| Attribute::RemovedLink(query_link_type, query_tag) => {
link_type
.clone()
.map(|link_type| link_type == query_link_type)
.unwrap_or(true)
&& tag
.clone()
.map(|tag| tag.to_uppercase() == query_tag.to_uppercase())
.unwrap_or(true)
}
_ => false,
}),
None.into(),
IndexFilter::LatestByAttribute,
Some(EavFilter::predicate(move |attr: Attribute| match attr {
//the problem with this is the tombstone match will be matching against regex
//at this stage of the eavi_query all three vectors (e,a,v) have already been matched
//it would be safe to assume at this point that any value that we match using this method
//will be a tombstone
Attribute::RemovedLink(_, _) => true,
_ => false,
})),
))
}
#[holochain_tracing_macros::newrelic_autotrace(HOLOCHAIN_CORE)]
impl DhtStore {
// LifeCycle
// =========
pub fn new(
content_storage: Arc<RwLock<dyn ContentAddressableStorage>>,
meta_storage: Arc<RwLock<dyn EntityAttributeValueStorage<Attribute>>>,
) -> Self {
DhtStore {
content_storage,
meta_storage,
holding_map: AspectMap::new(),
queued_holding_workflows: VecDeque::new(),
}
}
pub fn new_from_snapshot(
content_storage: Arc<RwLock<dyn ContentAddressableStorage>>,
meta_storage: Arc<RwLock<dyn EntityAttributeValueStorage<Attribute>>>,
snapshot: DhtStoreSnapshot,
) -> Self {
let mut new_dht_store = Self::new(content_storage, meta_storage);
new_dht_store.holding_map = snapshot.holding_map.into();
new_dht_store.queued_holding_workflows = snapshot.queued_holding_workflows;
new_dht_store
}
///This algorithmn works by querying the EAVI Query for entries that match the address given, the link _type given, the tag given and a tombstone query set of RemovedLink(link_type,tag)
///this means no matter how many links are added after one is removed, we will always say that the link has been removed.
///One thing to remember is that LinkAdd entries occupy the "Value" aspect of our EAVI link stores.
///When that set is obtained, we filter based on the LinkTag and RemovedLink attributes to evaluate if they are "live" or "deleted". A reminder that links cannot be modified
//returns a vector so that the view is maintained and not sorted by a btreeset
pub fn get_links(
&self,
address: Address,
link_type: Option<String>,
tag: Option<String>,
crud_filter: Option<CrudStatus>,
configuration: GetLinksQueryConfiguration,
) -> Result<Vec<(EntityAttributeValueIndex, CrudStatus)>, HolochainError> {
let get_links_query = create_get_links_eavi_query(address, link_type, tag)?;
let filtered = self.meta_storage.read()?.fetch_eavi(&get_links_query)?;
let pagination = configuration.pagination;
let filter_with_sort_order: Box<dyn Iterator<Item = EntityAttributeValueIndex>> =
match configuration.sort_order.unwrap_or_default() {
SortOrder::Ascending => Box::new(filtered.into_iter()),
SortOrder::Descending => Box::new(filtered.into_iter().rev()),
};
let filter_with_pagination: Box<dyn Iterator<Item = EntityAttributeValueIndex>> =
match pagination {
Some(paginate) => match paginate {
Pagination::Time(time_pagination) => {
let paginated_time = time_pagination.clone();
Box::new(
filter_with_sort_order
.skip_while(move |eavi| {
let from_time: DateTime<FixedOffset> =
paginated_time.from_time.into();
from_time.timestamp_nanos() <= eavi.index()
})
.take(time_pagination.limit),
)
}
Pagination::Size(size_pagination) => Box::new(
filter_with_sort_order
.skip(size_pagination.page_size * size_pagination.page_number)
.take(size_pagination.page_size),
),
},
None => filter_with_sort_order,
};
Ok(filter_with_pagination
.map(|s| match s.attribute() {
Attribute::LinkTag(_, _) => (s, CrudStatus::Live),
_ => (s, CrudStatus::Deleted),
})
.filter(|link_crud| crud_filter.map(|crud| crud == link_crud.1).unwrap_or(true))
.collect())
}
pub fn get_all_metas(
&self,
address: &Address,
) -> Result<BTreeSet<EntityAttributeValueIndex>, HolochainError> {
let query = EaviQuery::new(
Some(address.to_owned()).into(),
EavFilter::predicate(move |attr: Attribute| match attr {
Attribute::LinkTag(_, _)
| Attribute::RemovedLink(_, _)
| Attribute::CrudLink
| Attribute::CrudStatus => true,
_ => false,
}),
None.into(),
IndexFilter::LatestByAttribute,
None,
);
Ok(self.meta_storage.read()?.fetch_eavi(&query)?)
}
/// Get all headers for an entry by first looking in the DHT meta store
/// for header addresses, then resolving them with the DHT CAS
pub fn get_headers(&self, entry_address: Address) -> Result<Vec<ChainHeader>, HolochainError> {
self.meta_storage
.read()
.unwrap()
// fetch all EAV references to chain headers for this entry
.fetch_eavi(&EaviQuery::new(
Some(entry_address).into(),
Some(Attribute::EntryHeader).into(),
None.into(),
IndexFilter::LatestByAttribute,
None,
))?
.into_iter()
// get the header addresses
.map(|eavi| eavi.value())
// fetch the header content from CAS
.map(|address| self.get(&address))
// rearrange
.collect::<Result<Vec<Option<_>>, _>>()
.map(|r| {
r.into_iter()
// ignore None values
.flatten()
.map(|entry| match entry {
Entry::ChainHeader(chain_header) => Ok(chain_header),
_ => Err(HolochainError::ErrorGeneric(
"Unexpected non-chain_header entry".to_string(),
)),
})
.collect::<Result<Vec<_>, _>>()
})?
.map_err(|err| {
let hc_error: HolochainError = err;
hc_error
})
}
/// Add an entry and header to the CAS and EAV, respectively
pub fn add_header_for_entry(
&mut self,
entry: &Entry,
header: &ChainHeader,
) -> Result<(), HolochainError> {
let eavi = EntityAttributeValueIndex::new(
&entry.address(),
&Attribute::EntryHeader,
&header.address(),
)?;
self.add(header)?;
self.meta_storage.write().unwrap().add_eavi(&eavi)?;
Ok(())
}
pub fn mark_aspect_as_held(&mut self, aspect: &EntryAspect) {
self.holding_map.add(aspect);
}
pub fn get_holding_map(&self) -> &AspectMap {
&self.holding_map
}
pub(crate) fn fetch_eavi(
&self,
query: &EaviQuery,
) -> PersistenceResult<BTreeSet<EntityAttributeValueIndex>> {
self.meta_storage.read().unwrap().fetch_eavi(query)
}
pub(crate) fn add_eavi(
&mut self,
eavi: &EntityAttributeValueIndex,
) -> PersistenceResult<Option<EntityAttributeValueIndex>> {
self.meta_storage.write().unwrap().add_eavi(&eavi)
}
pub(crate) fn next_queued_holding_workflow(
&self,
) -> Option<(PendingValidation, Option<Duration>)> {
self.queued_holding_workflows
.clone()
.into_iter()
// filter so only free pending (those without dependencies also pending) are considered
.filter(free_pending_filter(&self.queued_holding_workflows))
// skip those for which the sleep delay has not elapsed
.skip_while(|PendingValidationWithTimeout { timeout, .. }| {
if let Some(ValidationTimeout {
time_of_dispatch,
delay,
}) = timeout
{
let maybe_time_elapsed = time_of_dispatch.elapsed();
if let Ok(time_elapsed) = maybe_time_elapsed {
if time_elapsed < *delay {
return true;
}
}
}
false
})
.map(|PendingValidationWithTimeout { pending, timeout }| {
(pending, timeout.map(|t| Some(t.delay)).unwrap_or(None))
})
.next()
}
pub(crate) fn has_exact_queued_holding_workflow(&self, pending: &PendingValidation) -> bool {
self.queued_holding_workflows.iter().any(
|PendingValidationWithTimeout {
pending: current, ..
}| current == pending,
)
}
pub(crate) fn has_same_queued_holding_worfkow(&self, pending: &PendingValidation) -> bool {
self.queued_holding_workflows.iter().any(
|PendingValidationWithTimeout {
pending: current, ..
}| {
current.entry_with_header.header.entry_address()
== pending.entry_with_header.header.entry_address()
&& current.workflow == pending.workflow
},
)
}
pub(crate) fn queued_holding_workflows(&self) -> &VecDeque<PendingValidationWithTimeout> {
&self.queued_holding_workflows
}
pub(crate) fn remove_holding_workflow(
&mut self,
item: &PendingValidation,
) -> Option<PendingValidationWithTimeout> {
self.queued_holding_workflows()
.iter()
.position(|PendingValidationWithTimeout { pending, .. }| pending == item)
.and_then(|index| self.queued_holding_workflows.remove(index))
}
}
use im::HashSet;
fn free_pending_filter<I>(pending: &I) -> Box<dyn Fn(&PendingValidationWithTimeout) -> bool>
where
I: IntoIterator<Item = PendingValidationWithTimeout> + Clone,
{
// collect up the address of everything we have in the pending queue
let unique_pending: HashSet<Address> = pending
.clone()
.into_iter()
.map(|p| p.pending.entry_with_header.entry.address())
.collect();
Box::new(move |p| {
p.pending
.dependencies
.iter()
.all(|dep_addr| !unique_pending.contains(dep_addr))
})
}
impl GetContent for DhtStore {
fn get_raw(&self, address: &Address) -> HcResult<Option<Content>> {
Ok((*self.content_storage.read().unwrap()).fetch(address)?)
}
}
impl AddContent for DhtStore {
fn add<T: AddressableContent>(&mut self, content: &T) -> HcResult<()> {
(*self.content_storage.write().unwrap())
.add(content)
.map_err(|e| e.into())
}
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::{
dht::pending_validations::{PendingValidationStruct, ValidatingWorkflow},
network::entry_with_header::EntryWithHeader,
};
use holochain_core_types::{
chain_header::test_chain_header_with_sig,
entry::{test_entry, test_entry_a, test_entry_b, test_entry_c},
};
use holochain_persistence_api::{
cas::storage::ExampleContentAddressableStorage, eav::ExampleEntityAttributeValueStorage,
};
#[test]
fn get_headers_roundtrip() {
let mut store = DhtStore::new(
Arc::new(RwLock::new(
ExampleContentAddressableStorage::new().unwrap(),
)),
Arc::new(RwLock::new(ExampleEntityAttributeValueStorage::new())),
);
let entry = test_entry();
let header1 = test_chain_header_with_sig("sig1");
let header2 = test_chain_header_with_sig("sig2");
store.add_header_for_entry(&entry, &header1).unwrap();
store.add_header_for_entry(&entry, &header2).unwrap();
let headers = store.get_headers(entry.address()).unwrap();
assert_eq!(headers, vec![header1, header2]);
}
fn pending_validation_for_entry(
entry: Entry,
dependencies: Vec<Address>,
) -> PendingValidationWithTimeout {
let header = test_chain_header_with_sig("sig1");
let mut pending_struct = PendingValidationStruct::new(
EntryWithHeader { entry, header },
ValidatingWorkflow::HoldEntry,
);
pending_struct.dependencies = dependencies;
PendingValidationWithTimeout::new(Arc::new(pending_struct.clone()), None)
}
#[test]
fn test_dependency_resolution_no_dependencies() {
// A and B have no dependencies. Both should be free
let a = pending_validation_for_entry(test_entry_a(), Vec::new());
let b = pending_validation_for_entry(test_entry_b(), Vec::new());
let pending_list = vec![a.clone(), b.clone()];
assert_eq!(
pending_list
.clone()
.into_iter()
.filter(free_pending_filter(&pending_list))
.collect::<Vec<_>>(),
vec![a, b]
);
}
#[test]
fn test_dependency_resolution_chain() {
// A depends on B and B depends on C. C should be free
let a = pending_validation_for_entry(test_entry_a(), vec![test_entry_b().address()]);
let b = pending_validation_for_entry(test_entry_b(), vec![test_entry_c().address()]);
let c = pending_validation_for_entry(test_entry_c(), vec![]);
let pending_list = vec![a.clone(), b.clone(), c.clone()];
assert_eq!(
pending_list
.clone()
.into_iter()
.filter(free_pending_filter(&pending_list))
.collect::<Vec<_>>(),
vec![c]
);
}
#[test]
fn test_dependency_resolution_tree() {
// A depends on B and C. B and C should be free
let a = pending_validation_for_entry(
test_entry_a(),
vec![test_entry_b().address(), test_entry_c().address()],
);
let b = pending_validation_for_entry(test_entry_b(), vec![]);
let c = pending_validation_for_entry(test_entry_c(), vec![]);
let pending_list = vec![a.clone(), b.clone(), c.clone()];
assert_eq!(
pending_list
.clone()
.into_iter()
.filter(free_pending_filter(&pending_list))
.collect::<Vec<_>>(),
vec![b, c]
);
}
}