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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use crate::repository::backend::common::{IndexTransaction, LockedFile};
use crate::repository::backend::{self, BackendError, Result, SegmentDescriptor};
use crate::repository::ChunkID;
use async_trait::async_trait;
use futures::channel::oneshot;
use serde_cbor as cbor;
use std::collections::{HashMap, HashSet};
use std::fs::{create_dir, read_dir, File};
use std::io::{BufWriter, Seek, SeekFrom};
use std::path::Path;
use std::thread;
#[derive(Debug)]
struct InternalIndex {
state: HashMap<ChunkID, SegmentDescriptor>,
file: LockedFile,
changes: Vec<IndexTransaction>,
}
impl InternalIndex {
fn open(repository_path: impl AsRef<Path>) -> Result<InternalIndex> {
let index_path = repository_path.as_ref().join("index");
if Path::exists(&index_path) {
if Path::is_file(&index_path) {
return Err(BackendError::IndexError(format!(
"Failed to load index, {:?} is a file, not a directory",
index_path
)));
}
} else {
create_dir(&index_path)?;
}
let mut state: HashMap<ChunkID, SegmentDescriptor> = HashMap::new();
let mut items = read_dir(&index_path)?
.filter_map(std::result::Result::ok)
.filter(|x| x.path().is_file())
.filter_map(|x| {
x.path()
.file_name()?
.to_str()
.and_then(|y| std::result::Result::ok(y.parse::<usize>()))
.map(|z| (z, x))
})
.collect::<Vec<_>>();
items.sort_by(|a, b| a.0.cmp(&b.0));
for (_, file) in &items {
let mut file = File::open(file.path())?;
let de = cbor::Deserializer::from_reader(&mut file);
let mut de = de.into_iter::<IndexTransaction>();
while let Some(tx) = de.next().and_then(std::result::Result::ok) {
state.insert(tx.chunk_id, tx.descriptor);
}
}
for (_, file) in &items {
let locked_file = LockedFile::open_read_write(file.path())?;
if let Some(file) = locked_file {
return Ok(InternalIndex {
state,
file,
changes: Vec::new(),
});
}
}
let id = if items.is_empty() {
0
} else {
items[items.len() - 1].0 + 1
};
let path = index_path.join(id.to_string());
let file = LockedFile::open_read_write(path)?
.expect("Somehow, our newly created index file is locked.");
Ok(InternalIndex {
state,
file,
changes: Vec::new(),
})
}
fn drain_changes(&mut self) -> Result<()> {
let mut file = BufWriter::new(&mut self.file);
file.seek(SeekFrom::End(0))?;
for tx in self.changes.drain(0..self.changes.len()) {
cbor::ser::to_writer(&mut file, &tx)?;
}
Ok(())
}
}
#[derive(Debug)]
enum IndexCommand {
Lookup(ChunkID, oneshot::Sender<Option<SegmentDescriptor>>),
Set(ChunkID, SegmentDescriptor, oneshot::Sender<Result<()>>),
KnownChunks(oneshot::Sender<HashSet<ChunkID>>),
Commit(oneshot::Sender<Result<()>>),
Count(oneshot::Sender<usize>),
Close(oneshot::Sender<()>),
}
#[derive(Clone)]
pub struct Index {
input: flume::Sender<IndexCommand>,
path: String,
}
impl Index {
pub fn open(repository_path: impl AsRef<Path>, queue_depth: usize) -> Result<Index> {
let mut index = InternalIndex::open(&repository_path)?;
let (input, output) = flume::bounded(queue_depth);
thread::spawn(move || {
let mut final_ret = None;
while let Ok(command) = output.recv() {
match command {
IndexCommand::Lookup(id, ret) => {
ret.send(index.state.get(&id).copied()).unwrap();
}
IndexCommand::Set(id, descriptor, ret) => {
index.state.insert(id, descriptor);
let transaction = IndexTransaction {
chunk_id: id,
descriptor,
};
index.changes.push(transaction);
ret.send(Ok(())).unwrap();
}
IndexCommand::KnownChunks(ret) => {
ret.send(index.state.keys().copied().collect::<HashSet<_>>())
.unwrap();
}
IndexCommand::Count(ret) => {
ret.send(index.state.len()).unwrap();
}
IndexCommand::Commit(ret) => {
ret.send(index.drain_changes()).unwrap();
}
IndexCommand::Close(ret) => {
final_ret = Some(ret);
break;
}
}
}
std::mem::drop(index);
std::mem::drop(output);
if let Some(ret) = final_ret {
ret.send(()).unwrap();
};
});
Ok(Index {
input,
path: repository_path.as_ref().to_str().unwrap().to_string(),
})
}
pub async fn close(&mut self) {
let (tx, rx) = oneshot::channel();
self.input
.send_async(IndexCommand::Close(tx))
.await
.expect("Called close on an already closed repository.");
rx.await
.expect("Called close on an already closed repository.");
}
}
impl std::fmt::Debug for Index {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Index: {:?}", self.path)
}
}
#[async_trait]
impl backend::Index for Index {
async fn lookup_chunk(&mut self, id: ChunkID) -> Option<SegmentDescriptor> {
let (input, output) = oneshot::channel();
self.input
.send_async(IndexCommand::Lookup(id, input))
.await
.expect("Unable to communicate with index task.");
output
.await
.expect("Unable to communicate with index task.")
}
async fn set_chunk(&mut self, id: ChunkID, location: SegmentDescriptor) -> Result<()> {
let (input, output) = oneshot::channel();
self.input
.send_async(IndexCommand::Set(id, location, input))
.await
.map_err(|_| BackendError::ChannelDroppedSend)?;
output.await?
}
async fn known_chunks(&mut self) -> HashSet<ChunkID> {
let (input, output) = oneshot::channel();
self.input
.send_async(IndexCommand::KnownChunks(input))
.await
.expect("Unable to communicate with index task.");
output
.await
.expect("Unable to communicate with index task.")
}
async fn commit_index(&mut self) -> Result<()> {
let (input, output) = oneshot::channel();
self.input
.send_async(IndexCommand::Commit(input))
.await
.map_err(|_| BackendError::ChannelDroppedSend)?;
output.await?
}
async fn count_chunk(&mut self) -> usize {
let (input, output) = oneshot::channel();
self.input
.send_async(IndexCommand::Count(input))
.await
.expect("Unable to communicate with index task.");
output
.await
.expect("Unable to communicate with index task.")
}
}
#[cfg(test)]
mod tests {
use super::*;
use backend::Index as OtherIndex;
use rand;
use rand::prelude::*;
use std::path::PathBuf;
use tempfile::{tempdir, TempDir};
use walkdir::WalkDir;
fn setup() -> (TempDir, PathBuf) {
let tempdir = tempdir().unwrap();
let path = tempdir.path().to_path_buf();
(tempdir, path)
}
#[test]
fn creation_works() {
smol::block_on(async {
let (tempdir, path) = setup();
let index = Index::open(&path, 4).expect("Index creation failed");
for entry in WalkDir::new(&path) {
let entry = entry.unwrap();
println!("{}", entry.path().display());
}
let index_dir = path.join("index");
assert!(index_dir.exists());
assert!(index_dir.is_dir());
let index_file = index_dir.join("0");
assert!(index_file.exists());
assert!(index_file.is_file());
let index_lock = index_dir.join("0.lock");
assert!(index_lock.exists());
assert!(index_lock.is_file());
});
}
#[test]
fn double_creation_works() {
smol::block_on(async {
let (tempdir, path) = setup();
let index1 = Index::open(&path, 4).expect("Index 1 creation failed");
let index2 = Index::open(&path, 4).expect("Index 2 creation failed");
for entry in WalkDir::new(&path) {
let entry = entry.unwrap();
println!("{}", entry.path().display());
}
let index_dir = path.join("index");
let if1 = index_dir.join("0");
let if2 = index_dir.join("1");
let il1 = index_dir.join("0.lock");
let il2 = index_dir.join("1.lock");
assert!(if1.exists() && if1.is_file());
assert!(if2.exists() && if2.is_file());
assert!(il1.exists() && il1.is_file());
assert!(il2.exists() && il2.is_file());
});
}
#[test]
fn unlock_on_drop() {
smol::block_on(async {
let (tempdir, path) = setup();
let mut index = Index::open(&path, 4).expect("Index creation failed");
index.close().await;
let index_dir = path.join("index");
let index_file = index_dir.join("0");
let index_lock = index_dir.join("0.lock");
assert!(index_file.exists() && index_file.is_file());
assert!(!index_lock.exists());
});
}
#[test]
fn write_drop_read() {
smol::block_on(async {
let (tempdir, path) = setup();
let mut txs = HashMap::new();
for _ in 0..10 {
let mut raw_id = [0_u8; 32];
rand::thread_rng().fill_bytes(&mut raw_id);
let segment_id: u64 = rand::thread_rng().gen();
let start: u64 = rand::thread_rng().gen();
let chunk_id = ChunkID::new(&raw_id);
let descriptor = SegmentDescriptor { segment_id, start };
txs.insert(chunk_id, descriptor);
}
let mut index = Index::open(&path, 4).expect("Index creation failed");
for (id, desc) in &txs {
index
.set_chunk(*id, *desc)
.await
.expect("Adding transaction failed");
}
index.commit_index().await.expect("commiting index failed");
let count = index.count_chunk().await;
assert_eq!(count, txs.len());
index.close().await;
let mut index = Index::open(&path, 4).expect("Index recreation failed");
for entry in WalkDir::new(&path) {
let entry = entry.unwrap();
println!("{}", entry.path().display());
}
let count = index.count_chunk().await;
assert_eq!(count, txs.len());
for (id, desc) in txs {
let location = index.lookup_chunk(id).await.expect("Tx retrieve failed");
assert_eq!(desc, location);
}
});
}
}