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