1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::repository::backend::Manifest as ManifestTrait;
pub use crate::repository::backend::{Backend, BackendClone, Index, SegmentDescriptor};
use crate::repository::pipeline::Pipeline;
pub use asuran_core::repository::chunk::{Chunk, ChunkID, ChunkSettings};
pub use asuran_core::repository::compression::Compression;
pub use asuran_core::repository::encryption::Encryption;
pub use asuran_core::repository::hmac::HMAC;
pub use asuran_core::repository::key::{EncryptedKey, Key};
use semver::Version;
use thiserror::Error;
use tracing::{debug, info, instrument, span, trace, Level};
use uuid::Uuid;
use std::collections::HashSet;
pub mod backend;
pub mod pipeline;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum RepositoryError {
#[error("Chunk Not in Repository")]
ChunkNotFound,
#[error("Chunker Error")]
ChunkerError(#[from] asuran_core::repository::chunk::ChunkError),
#[error("Backend Error")]
BackendError(#[from] backend::BackendError),
}
type Result<T> = std::result::Result<T, RepositoryError>;
#[derive(Clone)]
pub struct Repository<T> {
backend: T,
compression: Compression,
hmac: HMAC,
encryption: Encryption,
key: Key,
pipeline: Pipeline,
pub queue_depth: usize,
}
impl<T: BackendClone + 'static> Repository<T> {
#[instrument(skip(key))]
pub fn new(
backend: T,
compression: Compression,
hmac: HMAC,
encryption: Encryption,
key: Key,
pipeline_tasks: usize,
) -> Repository<T> {
info!("Creating a repository with backend {:?}", backend);
let pipeline = Pipeline::new(pipeline_tasks);
Repository {
backend,
compression,
hmac,
encryption,
key,
pipeline,
queue_depth: pipeline_tasks,
}
}
#[instrument(skip(key))]
pub fn with(
backend: T,
settings: ChunkSettings,
key: Key,
pipeline_tasks: usize,
) -> Repository<T> {
info!(
"Creating a repository with backend {:?} and chunk settings {:?}",
backend, settings
);
let pipeline = Pipeline::new(pipeline_tasks);
Repository {
backend,
key,
pipeline,
compression: settings.compression,
hmac: settings.hmac,
encryption: settings.encryption,
queue_depth: pipeline_tasks,
}
}
#[instrument(skip(self))]
pub async fn commit_index(&self) {
debug!("Commiting Index");
self.backend
.get_index()
.commit_index()
.await
.expect("Unable to commit index");
}
pub async fn write_raw(&mut self, chunk: Chunk) -> Result<(ChunkID, bool)> {
let id = chunk.get_id();
let span = span!(Level::DEBUG, "Writing Chunk", ?id);
let _guard = span.enter();
debug!("Writing chunk with id {:?}", id);
if self.has_chunk(id).await && id != ChunkID::manifest_id() {
trace!("Chunk already existed, doing nothing.");
Ok((id, true))
} else {
trace!("Chunk did not exist, continuning");
let backend = &mut self.backend;
let location = backend.write_chunk(chunk).await?;
self.backend.get_index().set_chunk(id, location).await?;
Ok((id, false))
}
}
#[instrument(skip(self, data))]
pub async fn write_chunk(&mut self, data: Vec<u8>) -> Result<(ChunkID, bool)> {
let chunk = self
.pipeline
.process(
data,
self.compression,
self.encryption,
self.hmac,
self.key.clone(),
)
.await;
self.write_raw(chunk).await
}
#[instrument(skip(self, data))]
pub async fn write_chunk_with_id(
&mut self,
data: Vec<u8>,
id: ChunkID,
) -> Result<(ChunkID, bool)> {
let mut chunk = self
.pipeline
.process(
data,
self.compression,
self.encryption,
self.hmac,
self.key.clone(),
)
.await;
let mac = chunk.mac();
let encryption = chunk.encryption();
let data = (chunk.split().1).0;
chunk = Chunk::from_parts(data, self.compression, encryption, self.hmac, mac, id);
self.write_raw(chunk).await
}
#[instrument(skip(self))]
pub async fn has_chunk(&self, id: ChunkID) -> bool {
self.backend.get_index().lookup_chunk(id).await.is_some()
}
#[instrument(skip(self))]
pub async fn read_chunk(&mut self, id: ChunkID) -> Result<Vec<u8>> {
if self.has_chunk(id).await {
let mut index = self.backend.get_index();
let location = index.lookup_chunk(id).await.unwrap_or_else(|| {
panic!("Index lied to us about having the chunk with ID {:?}", id)
});
let chunk = self.backend.read_chunk(location).await?;
let data = chunk.unpack(&self.key)?;
Ok(data)
} else {
Err(RepositoryError::ChunkNotFound)
}
}
#[instrument(skip(self))]
pub async fn count_chunk(&self) -> usize {
self.backend.get_index().count_chunk().await
}
#[instrument(skip(self))]
pub fn chunk_settings(&self) -> ChunkSettings {
ChunkSettings {
encryption: self.encryption,
compression: self.compression,
hmac: self.hmac,
}
}
#[instrument(skip(self))]
pub fn key(&self) -> &Key {
&self.key
}
#[instrument(skip(self))]
pub fn backend_manifest(&self) -> T::Manifest {
self.backend.get_manifest()
}
#[instrument(skip(self))]
pub async fn close(mut self) {
self.backend.close().await;
}
pub async fn seen_versions(&self) -> HashSet<(Version, Uuid)> {
self.backend_manifest().seen_versions().await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::repository::backend::common::sync_backend::BackendHandle;
use crate::repository::backend::mem::*;
use rand::prelude::*;
fn get_repo_mem(key: Key) -> Repository<BackendHandle<Mem>> {
let settings = ChunkSettings {
compression: Compression::ZStd { level: 1 },
hmac: HMAC::Blake2b,
encryption: Encryption::new_aes256ctr(),
};
let backend = Mem::new(settings, key.clone(), 4);
Repository::with(backend, settings, key, 2)
}
#[test]
fn repository_add_read() {
smol::block_on(async {
let key = Key::random(32);
let size = 7 * 10_u64.pow(3);
let mut data1 = vec![0_u8; size as usize];
thread_rng().fill_bytes(&mut data1);
let mut data2 = vec![0_u8; size as usize];
thread_rng().fill_bytes(&mut data2);
let mut data3 = vec![0_u8; size as usize];
thread_rng().fill_bytes(&mut data3);
let mut repo = get_repo_mem(key);
println!("Adding Chunks");
let key1 = repo.write_chunk(data1.clone()).await.unwrap().0;
let key2 = repo.write_chunk(data2.clone()).await.unwrap().0;
let key3 = repo.write_chunk(data3.clone()).await.unwrap().0;
println!("Reading Chunks");
let out1 = repo.read_chunk(key1).await.unwrap();
let out2 = repo.read_chunk(key2).await.unwrap();
let out3 = repo.read_chunk(key3).await.unwrap();
assert_eq!(data1, out1);
assert_eq!(data2, out2);
assert_eq!(data3, out3);
});
}
#[test]
fn double_add() {
smol::block_on(async {
let mut repo = get_repo_mem(Key::random(32));
assert_eq!(repo.count_chunk().await, 0);
let data = [1_u8; 8192];
let (key_1, unique_1) = repo.write_chunk(data.to_vec()).await.unwrap();
assert_eq!(unique_1, false);
assert_eq!(repo.count_chunk().await, 1);
let (key_2, unique_2) = repo.write_chunk(data.to_vec()).await.unwrap();
assert_eq!(repo.count_chunk().await, 1);
assert_eq!(unique_2, true);
assert_eq!(key_1, key_2);
std::mem::drop(repo);
});
}
#[test]
fn chunk_with_id() {
smol::block_on(async {
let mut repo = get_repo_mem(Key::random(32));
let size = 7 * 10_u64.pow(3);
let mut data = vec![0_u8; size as usize];
thread_rng().fill_bytes(&mut data);
let id = ChunkID::manifest_id();
repo.write_chunk_with_id(data.clone(), id)
.await
.expect("Unable to write with id");
let data_restore = repo
.read_chunk(id)
.await
.expect("Unable to read chunk back out");
assert_eq!(data, data_restore);
});
}
}