ps_hkey/async_store/
mod.rs1pub mod in_memory;
2pub mod mixed;
3
4use std::sync::Arc;
5
6use ps_cypher::validate_ecc;
7use ps_datachunk::{Bytes, DataChunk, OwnedDataChunk, PsDataChunkError};
8use ps_hash::Hash;
9use ps_promise::{Promise, PromiseRejection};
10
11use crate::{
12 constants::{MAX_DECRYPTED_SIZE, MAX_ENCRYPTED_SIZE, MAX_SIZE_RAW},
13 Hkey, LongHkeyExpanded, PsHkeyError,
14};
15
16pub trait AsyncStore
17where
18 Self: Clone + Sized + Send + Sync + 'static,
19{
20 type Chunk: DataChunk + Send + Sync + Unpin;
21 type Error: From<PsDataChunkError> + From<PsHkeyError> + PromiseRejection + Send + Unpin;
22
23 fn get(&self, hash: &Hash) -> Promise<Self::Chunk, Self::Error>;
24
25 fn put_encrypted<C: DataChunk>(&self, chunk: C) -> Promise<(), Self::Error>;
26
27 fn put(&self, data: Bytes) -> Promise<Hkey, Self::Error> {
28 let this = self.clone();
29
30 Promise::new(async move {
31 if data.len() <= MAX_SIZE_RAW {
32 return Ok(Hkey::Raw(Arc::from(&*data)));
33 }
34
35 if data.len() <= MAX_ENCRYPTED_SIZE && validate_ecc(&data) {
36 let chunk = OwnedDataChunk::from_bytes(data)?;
37 let hash = chunk.hash();
38
39 this.put_encrypted(chunk).await?;
40
41 Ok(Hkey::Direct(hash))
42 } else if data.len() <= MAX_DECRYPTED_SIZE {
43 let chunk = OwnedDataChunk::from_bytes(data)?;
44 let encrypted = chunk.encrypt()?;
45 let hkey = Hkey::Encrypted(encrypted.hash(), encrypted.key());
46
47 this.put_encrypted(encrypted).await?;
48
49 Ok(hkey)
50 } else {
51 LongHkeyExpanded::from_blob_async(&this, &data)
52 .await?
53 .shrink_async(&this)
54 .await
55 }
56 })
57 }
58}