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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use std::fs::File;
#[allow(unused_imports)]
use std::io::ErrorKind;
use std::io::Result;
use std::path::Path;
use std::sync::Arc;
use derivative::Derivative;
use crate::plain::Cache as PlainCache;
use crate::sharded::Cache as ShardedCache;
use crate::Key;
type ConsistencyChecker = Arc<
dyn Fn(&mut File, &mut File) -> Result<()>
+ Sync
+ Send
+ std::panic::RefUnwindSafe
+ std::panic::UnwindSafe,
>;
trait ReadSide:
std::fmt::Debug + Sync + Send + std::panic::RefUnwindSafe + std::panic::UnwindSafe
{
fn get(&self, key: Key) -> Result<Option<File>>;
fn touch(&self, key: Key) -> Result<bool>;
}
impl ReadSide for PlainCache {
fn get(&self, key: Key) -> Result<Option<File>> {
PlainCache::get(self, key.name)
}
fn touch(&self, key: Key) -> Result<bool> {
PlainCache::touch(self, key.name)
}
}
impl ReadSide for ShardedCache {
fn get(&self, key: Key) -> Result<Option<File>> {
ShardedCache::get(self, key)
}
fn touch(&self, key: Key) -> Result<bool> {
ShardedCache::touch(self, key)
}
}
#[derive(Default, Derivative)]
#[derivative(Debug)]
pub struct ReadOnlyCacheBuilder {
stack: Vec<Box<dyn ReadSide>>,
#[derivative(Debug = "ignore")]
consistency_checker: Option<ConsistencyChecker>,
}
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct ReadOnlyCache {
stack: Arc<[Box<dyn ReadSide>]>,
#[derivative(Debug = "ignore")]
consistency_checker: Option<ConsistencyChecker>,
}
impl ReadOnlyCacheBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn consistency_checker(
self,
checker: impl Fn(&mut File, &mut File) -> Result<()>
+ Sync
+ Send
+ std::panic::RefUnwindSafe
+ std::panic::UnwindSafe
+ Sized
+ 'static,
) -> Self {
self.arc_consistency_checker(Some(Arc::new(checker)))
}
pub fn clear_consistency_checker(self) -> Self {
self.arc_consistency_checker(None)
}
#[allow(clippy::type_complexity)]
pub fn arc_consistency_checker(
mut self,
checker: Option<
Arc<
dyn Fn(&mut File, &mut File) -> Result<()>
+ Sync
+ Send
+ std::panic::RefUnwindSafe
+ std::panic::UnwindSafe,
>,
>,
) -> Self {
self.consistency_checker = checker;
self
}
pub fn cache(self, path: impl AsRef<Path>, num_shards: usize) -> Self {
if num_shards <= 1 {
self.plain(path)
} else {
self.sharded(path, num_shards)
}
}
pub fn plain(mut self, path: impl AsRef<Path>) -> Self {
self.stack.push(Box::new(PlainCache::new(
path.as_ref().to_owned(),
usize::MAX,
)));
self
}
pub fn sharded(mut self, path: impl AsRef<Path>, num_shards: usize) -> Self {
self.stack.push(Box::new(ShardedCache::new(
path.as_ref().to_owned(),
num_shards,
usize::MAX,
)));
self
}
pub fn build(self) -> ReadOnlyCache {
ReadOnlyCache::new(self.stack, self.consistency_checker)
}
}
impl Default for ReadOnlyCache {
fn default() -> ReadOnlyCache {
ReadOnlyCache::new(Default::default(), None)
}
}
impl ReadOnlyCache {
fn new(
stack: Vec<Box<dyn ReadSide>>,
consistency_checker: Option<ConsistencyChecker>,
) -> ReadOnlyCache {
ReadOnlyCache {
stack: stack.into_boxed_slice().into(),
consistency_checker,
}
}
pub fn get<'a>(&self, key: impl Into<Key<'a>>) -> Result<Option<File>> {
fn doit(
stack: &[Box<dyn ReadSide>],
checker: &Option<ConsistencyChecker>,
key: Key,
) -> Result<Option<File>> {
use std::io::Seek;
use std::io::SeekFrom;
let mut ret = None;
for cache in stack.iter() {
let mut hit = match cache.get(key)? {
Some(hit) => hit,
None => continue,
};
match checker {
None => return Ok(Some(hit)),
Some(checker) => match ret.as_mut() {
None => ret = Some(hit),
Some(prev) => {
checker(prev, &mut hit)?;
prev.seek(SeekFrom::Start(0))?;
}
},
}
}
Ok(ret)
}
if self.stack.is_empty() {
return Ok(None);
}
doit(&*self.stack, &self.consistency_checker, key.into())
}
pub fn touch<'a>(&self, key: impl Into<Key<'a>>) -> Result<bool> {
fn doit(stack: &[Box<dyn ReadSide>], key: Key) -> Result<bool> {
for cache in stack.iter() {
if cache.touch(key)? {
return Ok(true);
}
}
Ok(false)
}
if self.stack.is_empty() {
return Ok(false);
}
doit(&*self.stack, key.into())
}
}
#[cfg(test)]
mod test {
use std::fs::File;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use crate::plain::Cache as PlainCache;
use crate::sharded::Cache as ShardedCache;
use crate::Key;
use crate::ReadOnlyCache;
use crate::ReadOnlyCacheBuilder;
struct TestKey {
key: String,
}
impl TestKey {
fn new(key: &str) -> TestKey {
TestKey {
key: key.to_string(),
}
}
}
impl<'a> From<&'a TestKey> for Key<'a> {
fn from(x: &'a TestKey) -> Key<'a> {
Key::new(&x.key, 0, 1)
}
}
fn byte_equality_checker(
counter: Arc<AtomicU64>,
) -> impl 'static + Fn(&mut File, &mut File) -> std::io::Result<()> {
use std::io::Read;
move |x: &mut File, y: &mut File| {
let mut x_contents = Vec::new();
let mut y_contents = Vec::new();
counter.fetch_add(1, Ordering::Relaxed);
x.read_to_end(&mut x_contents)?;
y.read_to_end(&mut y_contents)?;
if x_contents == y_contents {
Ok(())
} else {
Err(std::io::Error::new(std::io::ErrorKind::Other, "mismatch"))
}
}
}
#[test]
fn empty() {
let ro: ReadOnlyCache = Default::default();
assert!(matches!(ro.get(Key::new("foo", 1, 2)), Ok(None)));
assert!(matches!(ro.touch(Key::new("foo", 1, 2)), Ok(false)));
}
#[test]
fn consistency_checker_success() {
use std::io::Read;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(2))
.create("first/1", FileType::RandomFile(10))
.create("second/2", FileType::RandomFile(10));
let counter = Arc::new(AtomicU64::new(0));
let ro = ReadOnlyCacheBuilder::new()
.plain(temp.path("first"))
.plain(temp.path("second"))
.consistency_checker(byte_equality_checker(counter.clone()))
.build();
let mut hit = ro
.get(&TestKey::new("0"))
.expect("must succeed")
.expect("must exist");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let mut contents = Vec::new();
hit.read_to_end(&mut contents).expect("read should succeed");
assert_eq!(contents, "00".as_bytes());
let _ = ro
.get(&TestKey::new("1"))
.expect("must succeed")
.expect("must exist");
assert_eq!(counter.load(Ordering::Relaxed), 1);
let _ = ro
.get(&TestKey::new("2"))
.expect("must succeed")
.expect("must exist");
assert_eq!(counter.load(Ordering::Relaxed), 1);
}
#[test]
fn consistency_checker_failure() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(3));
let counter = Arc::new(AtomicU64::new(0));
let ro = ReadOnlyCacheBuilder::new()
.plain(temp.path("first"))
.plain(temp.path("second"))
.consistency_checker(byte_equality_checker(counter))
.build();
assert!(ro.get(&TestKey::new("0")).is_err());
}
#[test]
fn consistency_checker_silent_failure() {
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("first", FileType::Dir)
.create("second", FileType::Dir)
.create("first/0", FileType::ZeroFile(2))
.create("second/0", FileType::ZeroFile(3));
let counter = Arc::new(AtomicU64::new(0));
let ro = ReadOnlyCacheBuilder::new()
.plain(temp.path("first"))
.plain(temp.path("second"))
.consistency_checker(byte_equality_checker(counter.clone()))
.clear_consistency_checker()
.build();
let _ = ro
.get(&TestKey::new("0"))
.expect("must succeed")
.expect("must exist");
assert_eq!(counter.load(Ordering::Relaxed), 0);
}
#[test]
fn smoke_test() {
use std::io::{Read, Write};
use tempfile::NamedTempFile;
use test_dir::{DirBuilder, FileType, TestDir};
let temp = TestDir::temp()
.create("sharded", FileType::Dir)
.create("plain", FileType::Dir);
{
let cache = ShardedCache::new(temp.path("sharded"), 10, 20);
let tmp = NamedTempFile::new_in(cache.temp_dir(None).expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"sharded")
.expect("write must succeed");
cache
.put(Key::new("a", 0, 1), tmp.path())
.expect("put must succeed");
let tmp2 = NamedTempFile::new_in(cache.temp_dir(None).expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp2.as_file()
.write_all(b"sharded2")
.expect("write must succeed");
cache
.put(Key::new("b", 0, 1), tmp2.path())
.expect("put must succeed");
}
{
let cache = PlainCache::new(temp.path("plain"), 10);
let tmp = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp.as_file()
.write_all(b"plain")
.expect("write must succeed");
cache.put("b", tmp.path()).expect("put must succeed");
let tmp2 = NamedTempFile::new_in(cache.temp_dir().expect("temp_dir must succeed"))
.expect("new temp file must succeed");
tmp2.as_file()
.write_all(b"plain2")
.expect("write must succeed");
cache.put("c", tmp2.path()).expect("put must succeed");
}
{
let ro = ReadOnlyCacheBuilder::new()
.sharded(temp.path("sharded"), 10)
.plain(temp.path("plain"))
.build();
assert!(matches!(ro.get(&TestKey::new("Missing")), Ok(None)));
assert!(matches!(ro.touch(&TestKey::new("Missing")), Ok(false)));
assert!(matches!(ro.touch(&TestKey::new("a")), Ok(true)));
{
let mut a_file = ro
.get(&TestKey::new("a"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
a_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"sharded");
}
{
let mut b_file = ro
.get(&TestKey::new("b"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
b_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"sharded2");
}
{
let mut c_file = ro
.get(&TestKey::new("c"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
c_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"plain2");
}
}
{
let ro = ReadOnlyCacheBuilder::new()
.cache(temp.path("plain"), 1)
.cache(temp.path("sharded"), 10)
.build();
{
let mut a_file = ro
.get(&TestKey::new("a"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
a_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"sharded");
}
{
let mut b_file = ro
.get(&TestKey::new("b"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
b_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"plain");
}
{
let mut c_file = ro
.get(&TestKey::new("c"))
.expect("must succeed")
.expect("must exist");
let mut dst = Vec::new();
c_file.read_to_end(&mut dst).expect("read must succeed");
assert_eq!(&dst, b"plain2");
}
}
}
}