2019-07-05 08:42:46 +00:00
|
|
|
use std::collections::HashMap;
|
2019-08-26 11:40:24 +00:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
use failure::*;
|
2019-07-03 12:39:13 +00:00
|
|
|
|
|
|
|
use super::BackupReader;
|
2019-10-06 08:31:06 +00:00
|
|
|
use crate::backup::{ReadChunk, DataBlob, CryptConfig};
|
2019-07-03 12:39:13 +00:00
|
|
|
|
|
|
|
/// Read chunks from remote host using ``BackupReader``
|
|
|
|
pub struct RemoteChunkReader {
|
|
|
|
client: Arc<BackupReader>,
|
|
|
|
crypt_config: Option<Arc<CryptConfig>>,
|
2019-07-05 08:42:46 +00:00
|
|
|
cache_hint: HashMap<[u8; 32], usize>,
|
|
|
|
cache: HashMap<[u8; 32], Vec<u8>>,
|
2019-07-03 12:39:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl RemoteChunkReader {
|
|
|
|
|
2019-07-05 08:42:46 +00:00
|
|
|
/// Create a new instance.
|
|
|
|
///
|
|
|
|
/// Chunks listed in ``cache_hint`` are cached and kept in RAM.
|
|
|
|
pub fn new(
|
|
|
|
client: Arc<BackupReader>,
|
|
|
|
crypt_config: Option<Arc<CryptConfig>>,
|
|
|
|
cache_hint: HashMap<[u8; 32], usize>,
|
|
|
|
) -> Self {
|
|
|
|
|
|
|
|
Self { client, crypt_config, cache_hint, cache: HashMap::new() }
|
2019-07-03 12:39:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ReadChunk for RemoteChunkReader {
|
|
|
|
|
|
|
|
fn read_chunk(&mut self, digest:&[u8; 32]) -> Result<Vec<u8>, Error> {
|
|
|
|
|
2019-10-05 09:45:20 +00:00
|
|
|
let mut chunk_data = Vec::with_capacity(4*1024*1024);
|
2019-07-03 12:39:13 +00:00
|
|
|
|
2019-07-05 08:42:46 +00:00
|
|
|
if let Some(raw_data) = self.cache.get(digest) {
|
|
|
|
return Ok(raw_data.to_vec());
|
|
|
|
}
|
|
|
|
|
|
|
|
let use_cache = self.cache_hint.contains_key(digest);
|
|
|
|
|
2019-10-05 09:45:20 +00:00
|
|
|
futures::executor::block_on(self.client.download_chunk(&digest, &mut chunk_data))?;
|
2019-07-03 12:39:13 +00:00
|
|
|
|
2019-10-06 08:31:06 +00:00
|
|
|
let chunk = DataBlob::from_raw(chunk_data)?;
|
2019-07-03 12:39:13 +00:00
|
|
|
chunk.verify_crc()?;
|
|
|
|
|
2019-10-07 09:36:39 +00:00
|
|
|
let raw_data = chunk.decode(self.crypt_config.as_ref().map(Arc::as_ref))?;
|
2019-10-06 08:31:06 +00:00
|
|
|
|
|
|
|
// fixme: verify chunk digest
|
2019-07-03 12:39:13 +00:00
|
|
|
|
2019-07-05 08:42:46 +00:00
|
|
|
if use_cache {
|
|
|
|
self.cache.insert(*digest, raw_data.to_vec());
|
|
|
|
}
|
|
|
|
|
2019-07-03 12:39:13 +00:00
|
|
|
Ok(raw_data)
|
|
|
|
}
|
|
|
|
}
|