use std::time::Instant;
use crate::AttoTokens;
use crate::Client;
use crate::client::payment::PaymentOption;
use crate::client::{GetError, PutError};
use crate::self_encryption::EncryptionStream;
pub use crate::Bytes;
pub use crate::client::data_types::chunk::DataMapChunk;
pub use crate::client::high_level::data::stream::DataStream;
impl Client {
pub async fn data_get(&self, data_map: &DataMapChunk) -> Result<Bytes, GetError> {
info!(
"Fetching private data from datamap {:?}",
data_map.0.address()
);
let mut datamap = self.restore_data_map_from_chunk(data_map).await?;
let chunk_count = datamap.infos().len();
if chunk_count > *crate::client::config::MAX_IN_MEMORY_DOWNLOAD_SIZE {
warn!(
"Data map {:?} has {chunk_count} chunks, which exceeds the maximum allowed in-memory download size of {} chunks",
data_map.0.address(),
*crate::client::config::MAX_IN_MEMORY_DOWNLOAD_SIZE
);
return Err(GetError::TooLargeForMemory(datamap));
}
datamap.child = None;
let data = self.fetch_from_data_map(&datamap).await?;
debug!(
"Successfully fetched private data ({} chunks) in-memory",
chunk_count
);
Ok(data)
}
pub async fn data_stream(&self, data_map: &DataMapChunk) -> Result<DataStream, GetError> {
info!(
"Starting streaming fetch of private data from datamap {:?}",
data_map.0.address()
);
let datamap = self.restore_data_map_from_chunk(data_map).await?;
let chunk_count = datamap.infos().len();
debug!(
"Starting streaming fetch of private data ({} chunks)",
chunk_count
);
DataStream::new(self.clone(), datamap)
}
pub async fn data_put(
&self,
data: Bytes,
payment_option: PaymentOption,
) -> Result<(AttoTokens, DataMapChunk), PutError> {
let now = Instant::now();
let (chunk_stream, data_map_chunk) = EncryptionStream::new_in_memory(data, false)?;
debug!("Encryption took: {:.2?}", now.elapsed());
let mut chunk_streams = vec![chunk_stream];
self.pay_and_upload(payment_option, &mut chunk_streams)
.await
.map(|total_cost| (total_cost, data_map_chunk))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::client::data_types::chunk::Chunk;
#[test]
fn test_hex() {
let data_map = DataMapChunk(Chunk::new(Bytes::from_static(b"hello")));
let hex = data_map.to_hex();
let data_map2 = DataMapChunk::from_hex(&hex).expect("Failed to decode hex");
assert_eq!(data_map, data_map2);
}
}