hashtree_collection/
state.rs1use std::collections::BTreeMap;
2use std::sync::Arc;
3
4use hashtree_core::{Cid, HashTree, HashTreeConfig, Store};
5
6use crate::helpers::find_manifest_cid;
7use crate::{CollectionDefinition, CollectionError, MANIFEST_BY_ID};
8
9#[derive(Debug, Clone, Default, PartialEq)]
10pub struct CollectionState {
11 pub by_id_root: Option<Cid>,
12 pub key_roots: BTreeMap<String, Option<Cid>>,
13 pub search_roots: BTreeMap<String, Option<Cid>>,
14}
15
16impl CollectionState {
17 pub fn key_root(&self, name: &str) -> Option<&Cid> {
18 self.key_roots.get(name).and_then(Option::as_ref)
19 }
20
21 pub fn search_root(&self, name: &str) -> Option<&Cid> {
22 self.search_roots.get(name).and_then(Option::as_ref)
23 }
24}
25
26#[derive(Debug, Clone, Default)]
27pub struct CollectionOptions {
28 pub btree_order: Option<usize>,
29}
30
31pub fn create_empty_collection_state<T>(definition: &CollectionDefinition<T>) -> CollectionState {
32 CollectionState {
33 by_id_root: None,
34 key_roots: definition
35 .key_indexes()
36 .iter()
37 .map(|index| (index.name().to_string(), None))
38 .collect(),
39 search_roots: definition
40 .search_indexes()
41 .iter()
42 .map(|index| (index.name().to_string(), None))
43 .collect(),
44 }
45}
46
47pub async fn load_collection_state<S: Store, T>(
48 store: Arc<S>,
49 definition: &CollectionDefinition<T>,
50 root: Option<&Cid>,
51) -> Result<CollectionState, CollectionError> {
52 let mut state = create_empty_collection_state(definition);
53 let Some(root) = root else {
54 return Ok(state);
55 };
56
57 let tree = HashTree::new(HashTreeConfig::new(store));
58 let entries = tree.list_directory(root).await?;
59 state.by_id_root = find_manifest_cid(&entries, MANIFEST_BY_ID);
60 for index in definition.key_indexes() {
61 state.key_roots.insert(
62 index.name().to_string(),
63 find_manifest_cid(&entries, index.name()),
64 );
65 }
66 for index in definition.search_indexes() {
67 state.search_roots.insert(
68 index.name().to_string(),
69 find_manifest_cid(&entries, index.name()),
70 );
71 }
72 Ok(state)
73}