Skip to main content

rust_ipfs/repo/store/default_impl/
keystore.rs

1#[cfg(not(target_arch = "wasm32"))]
2use connexa::keystore::store::fs::FilesystemKeystore as PersistenceKeystore;
3use connexa::keystore::{EncryptedEntry, KeyMetadata, Keystore};
4
5#[cfg(target_arch = "wasm32")]
6use connexa::keystore::store::indexeddb::IndexedDbKeystore as PersistenceKeystore;
7
8use connexa::keystore::store::memory::MemoryKeystore;
9use either::Either;
10
11use connexa::keystore::Error;
12
13type KeystoreResult<T> = Result<T, Error>;
14
15pub struct DefaultKeystore {
16    keystore: Either<MemoryKeystore, PersistenceKeystore>,
17}
18
19impl Default for DefaultKeystore {
20    fn default() -> Self {
21        Self {
22            keystore: Either::Left(MemoryKeystore::default()),
23        }
24    }
25}
26
27impl DefaultKeystore {
28    #[cfg(not(target_arch = "wasm32"))]
29    pub fn set_path(path: impl AsRef<std::path::Path>) -> Self {
30        Self {
31            keystore: Either::Right(PersistenceKeystore::new(path)),
32        }
33    }
34
35    #[cfg(target_arch = "wasm32")]
36    pub fn set_identifier(namespace: impl Into<Option<String>>) -> Self {
37        let namespace = namespace.into();
38        let namespace = namespace.unwrap_or_else(|| "rust-ipfs".into());
39        Self {
40            keystore: Either::Right(PersistenceKeystore::new(namespace)),
41        }
42    }
43}
44
45impl Keystore for DefaultKeystore {
46    async fn put(&self, entry: EncryptedEntry) -> KeystoreResult<()> {
47        match &self.keystore {
48            Either::Left(keystore) => keystore.put(entry).await,
49            Either::Right(keystore) => keystore.put(entry).await,
50        }
51    }
52
53    async fn put_many(&self, entries: Vec<EncryptedEntry>) -> KeystoreResult<()> {
54        match &self.keystore {
55            Either::Left(keystore) => keystore.put_many(entries).await,
56            Either::Right(keystore) => keystore.put_many(entries).await,
57        }
58    }
59
60    async fn get(&self, label: &str) -> KeystoreResult<Option<EncryptedEntry>> {
61        match &self.keystore {
62            Either::Left(keystore) => keystore.get(label).await,
63            Either::Right(keystore) => keystore.get(label).await,
64        }
65    }
66
67    async fn list(&self) -> KeystoreResult<Vec<KeyMetadata>> {
68        match &self.keystore {
69            Either::Left(keystore) => keystore.list().await,
70            Either::Right(keystore) => keystore.list().await,
71        }
72    }
73
74    async fn remove(&self, label: &str) -> KeystoreResult<bool> {
75        match &self.keystore {
76            Either::Left(keystore) => keystore.remove(label).await,
77            Either::Right(keystore) => keystore.remove(label).await,
78        }
79    }
80}