64818938 Andy McCall 1 month ago ↶
1
2
3
4
d02e545d Andy McCall 1 month ago ↶
5
64818938 Andy McCall 1 month ago ↶
6
7
8
9
10
11
12
13
14
15
d02e545d Andy McCall 1 month ago ↶
16
17
18
19
64818938 Andy McCall 1 month ago ↶
20
21
22
23
24
25
26
767ac6cd Andy McCall 17 days ago
27
28
ef7d4ea6 Andy McCall 16 days ago ↶
29
30
31
32
33
ff0af1ee unknown 1 month ago
34
5b9c6ad4 Andy McCall 1 month ago ↶
35
use crate :: attest:: Attest;
ff0af1ee unknown 1 month ago
36
use crate :: hash:: { hash_object, header, ObjectRef, ObjectType} ;
1983686f Andy McCall 1 month ago ↶
37
use crate :: identity:: { Identity, Signature} ;
6f8aeb99 Andy McCall 1 month ago ↶
38
use crate :: objects:: { Blob, Change, ObjectError, StateObject} ;
fc1a466a Andy McCall 1 month ago ↶
39
use crate :: receipt:: Receipt;
64818938 Andy McCall 1 month ago ↶
40
use crate :: strata:: { self , Error as BackendError, LocalStore, MemoryStore} ;
ff0af1ee unknown 1 month ago
41
use rand:: RngCore;
d02e545d Andy McCall 1 month ago ↶
42
use std:: cell:: RefCell;
ff0af1ee unknown 1 month ago
43
use std:: fs;
64818938 Andy McCall 1 month ago ↶
44
use std:: io:: { self , Write} ;
ff0af1ee unknown 1 month ago
45
use std:: path:: { Path, PathBuf} ;
64818938 Andy McCall 1 month ago ↶
46
use std:: sync:: Arc;
ff0af1ee unknown 1 month ago
47
d02e545d Andy McCall 1 month ago ↶
48
const PACK_MAGIC : & [ u8 ; 8 ] = b " OXYPACK1" ;
49
const IDX_MAGIC : & [ u8 ; 8 ] = b " OXYIDX01" ;
50
const IDX_ENTRY : usize = 32 + 8 + 4 + 4 + 1 + 1 ;
51
const FLAG_ZSTD : u8 = 1 ;
a17fc622 Andy McCall 1 month ago ↶
52
53
54
55
const FLAG_DICT : u8 = 2 ;
56
57
58
const DICT_BYTES : usize = 110 < < 10 ;
59
const DICT_MIN_OBJECTS : usize = 1000 ;
60
61
const DICT_OBJECT_MAX : usize = 64 < < 10 ;
d02e545d Andy McCall 1 month ago ↶
62
const ZSTD_LEVEL : i32 = 3 ;
da652d63 Andy McCall 1 month ago ↶
63
64
pub const REPACK_ZSTD_LEVEL : i32 = 9 ;
2b872d07 Andy McCall 1 month ago ↶
65
66
67
const MAX_OBJECT_LEN : u32 = 1 < < 30 ;
767ac6cd Andy McCall 17 days ago
68
69
70
71
const NO_DICT : & str = " packed with a dictionary the pack lacks" ;
d02e545d Andy McCall 1 month ago ↶
72
767ac6cd Andy McCall 17 days ago
73
74
75
76
77
78
79
80
81
const RETIRED_KEY : & str = " pack-retired" ;
82
83
84
85
86
pub const RETIRED_FOR : std:: time:: Duration = std:: time:: Duration:: from_secs( 60 * 60 ) ;
87
88
const RETIRED_TRIES : usize = 32 ;
89
90
91
92
93
const HAS_RELIST_AFTER : std:: time:: Duration = std:: time:: Duration:: from_secs( 1 ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
94
95
96
97
98
99
100
101
pub const JOURNAL_KEY : & str = " pack-entries" ;
102
103
const LIST_SUFFIX : & str = " .entries" ;
104
105
const PART_SUFFIX : & str = " .entries-part" ;
106
107
const LIST_MAGIC : & str = " oxy-entries 1" ;
108
109
110
const LEGACY_FOLDED_KEY : & str = " pack-legacy-folded" ;
111
112
113
const JOURNAL_FOLD_AT : usize = 1000 ;
771661aa Andy McCall 16 days ago ↶
114
115
116
117
118
pub const ENTRIES_FRESH : std:: time:: Duration = std:: time:: Duration:: from_secs( 30 ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
119
120
121
const ENTRY_INDEXES : [ ( & str , & str ) ; 6 ] = [
122
( " sig" , " sigs" ) ,
123
( " seal" , " seals" ) ,
124
( " receipt" , " receipts" ) ,
125
( " approval" , " approvals" ) ,
126
( " cert" , " certs" ) ,
127
( " accepted" , " accepted-lists" ) ,
128
] ;
767ac6cd Andy McCall 17 days ago
129
130
131
type Listed = Vec< ( String, u64 , Option< u64 > ) > ;
132
133
134
fn parse_retired ( bytes : & [u8 ]) -> std:: collections:: BTreeMap< String, u64 > {
135
String :: from_utf8_lossy( bytes)
136
.lines ( )
137
.filter_map ( | l | {
138
let ( t, k) = l.split_once ( ' ' ) ? ;
139
Some ( ( k.to_string ( ) , t.parse ( ) .ok ( ) ? ) )
140
} )
141
.collect ( )
142
}
143
144
fn encode_retired ( m : & std:: collections:: BTreeMap< String, u64 > ) -> Vec< u8 > {
145
m.iter ( )
146
.map ( | ( k , t ) | format! ( " {t} {k} \n " ) )
147
.collect:: < String> ( )
148
.into_bytes ( )
149
}
150
151
152
# [ derive ( Debug, Clone, Default, PartialEq, Eq ) ]
153
pub struct RetiredReport {
154
155
pub packs : usize ,
156
157
pub loose : usize ,
158
159
160
pub kept : usize ,
161
}
162
afaba5f1 Andy McCall 1 month ago ↶
163
164
pub type Object = ( ObjectType, Vec< u8 > ) ;
165
9ae4d15a Andy McCall 1 month ago ↶
166
167
168
pub type Progress < 'a > = & 'a mut dyn FnMut ( & str ) ;
64818938 Andy McCall 1 month ago ↶
169
170
171
pub type Backend = dyn strata:: Store;
9ae4d15a Andy McCall 1 month ago ↶
172
173
fn silent ( ) -> impl FnMut( & str ) {
174
| _ | { }
64818938 Andy McCall 1 month ago ↶
175
}
176
177
178
179
fn backend_err ( e : BackendError) -> StoreError {
180
match e {
181
BackendError:: Io( e) => StoreError:: Io( e) ,
182
other => StoreError:: Io( io:: Error:: other( other.to_string ( ) ) ) ,
183
}
184
}
185
186
187
fn put_new_or_existing ( backend : & Backend, key : & str , bytes : & [u8 ]) -> Result< ( ) > {
188
match backend.put_new ( key, bytes) {
189
Ok ( ( ) ) | Err ( BackendError:: Exists( _ ) ) => Ok ( ( ) ) ,
190
Err ( e) => Err ( backend_err ( e) ) ,
191
}
192
}
193
194
195
fn get_optional ( backend : & Backend, key : & str ) -> Result< Option< Vec< u8 > > > {
196
match backend.get ( key) {
197
Ok ( b) => Ok ( Some ( b) ) ,
198
Err ( BackendError:: NotFound( _ ) ) => Ok ( None ) ,
199
Err ( e) => Err ( backend_err ( e) ) ,
200
}
201
}
202
203
fn delete ( backend : & Backend, key : & str ) -> Result< ( ) > {
204
backend.delete ( key) .map_err ( backend_err)
205
}
206
207
208
fn loose_key ( r : & ObjectRef) -> String {
209
let h = r.to_hex ( ) ;
210
format! ( " loose/{} /{} " , & h[ .. 2 ] , & h[ 2 .. ] )
211
}
212
213
214
fn loose_ref ( key : & str ) -> Option< ObjectRef> {
215
let rest = key.strip_prefix ( " loose/" ) ? ;
216
let ( hh, tail) = rest.split_once ( ' /' ) ? ;
217
if hh.len ( ) ! = 2 | | tail.contains ( ' /' ) {
218
return None ;
219
}
220
ObjectRef:: from_hex( & format! ( " {hh} {tail} " ) )
221
}
222
223
224
fn fanout_prefix ( index : & str , r : & ObjectRef) -> String {
225
let h = r.to_hex ( ) ;
226
format! ( " {index} /{} /{} /" , & h[ .. 2 ] , & h[ 2 .. ] )
ef7d4ea6 Andy McCall 16 days ago ↶
227
}
228
229
230
fn is_entry_list ( key : & str ) -> bool {
231
key.starts_with ( " pack-" ) & & ( key.ends_with ( LIST_SUFFIX ) | | key.ends_with ( PART_SUFFIX ) )
232
}
233
234
235
236
fn encode_entry_list < 'a > ( keys : impl Iterator< Item = & 'a String> ) -> Result< Vec< u8 > > {
237
let mut text = String :: from( LIST_MAGIC ) ;
238
text.push ( ' \n ' ) ;
239
for k in keys {
240
text.push_str ( k) ;
241
text.push ( ' \n ' ) ;
242
}
243
Ok ( zstd:: bulk:: compress( text.as_bytes ( ) , ZSTD_LEVEL ) ? )
244
}
245
246
247
fn decode_entry_list ( key : & str , bytes : & [u8 ]) -> Result< Vec< String> > {
248
let bad = | why : & str | StoreError:: Io( io:: Error:: other( format! ( " {key} : {why} " ) ) ) ;
249
let text = zstd:: stream:: decode_all( bytes) .map_err ( | _| bad ( " not zstd" ) ) ? ;
250
let text = String :: from_utf8( text) .map_err ( | _| bad ( " not UTF-8" ) ) ? ;
251
let mut lines = text.lines ( ) ;
252
if lines.next ( ) ! = Some ( LIST_MAGIC ) {
253
return Err ( bad ( " not an entry list" ) ) ;
254
}
255
Ok ( lines
256
.filter ( | l | ! l.is_empty ( ) )
257
.map ( str :: to_string)
258
.collect ( ) )
64818938 Andy McCall 1 month ago ↶
259
}
260
ef7d4ea6 Andy McCall 16 days ago ↶
261
262
263
fn expire_folded ( m : & mut std:: collections:: BTreeMap< String, u64 > , now : u64 ) {
264
let hour = RETIRED_FOR .as_millis ( ) as u64 ;
265
m.retain ( | _, t | * t = = 0 | | now.saturating_sub ( * t) < hour) ;
266
}
267
64818938 Andy McCall 1 month ago ↶
268
269
fn legacy_key ( index : & str , r : & ObjectRef) -> String {
270
let h = r.to_hex ( ) ;
271
format! ( " {index} /{} /{} " , & h[ .. 2 ] , & h[ 2 .. ] )
9ae4d15a Andy McCall 1 month ago ↶
272
}
273
64818938 Andy McCall 1 month ago ↶
274
fn now_ms ( ) -> u64 {
275
std:: time:: SystemTime:: now( )
276
.duration_since ( std:: time:: UNIX_EPOCH )
277
.map ( | d | d.as_millis ( ) as u64 )
278
.unwrap_or ( 0 )
279
}
280
d02e545d Andy McCall 1 month ago ↶
281
# [ derive ( Clone, Copy, Debug ) ]
282
struct PackEntry {
283
offset : u64 ,
284
stored_len : u32 ,
285
raw_len : u32 ,
286
ty : ObjectType,
287
flags : u8 ,
288
}
289
290
291
struct PackIndex {
64818938 Andy McCall 1 month ago ↶
292
293
key : String,
d02e545d Andy McCall 1 month ago ↶
294
refs : Vec< ObjectRef> ,
295
entries : Vec< PackEntry> ,
a17fc622 Andy McCall 1 month ago ↶
296
64818938 Andy McCall 1 month ago ↶
297
dict : Option< Arc< zstd:: dict:: DecoderDictionary< 'static > > > ,
d02e545d Andy McCall 1 month ago ↶
298
}
299
a17fc622 Andy McCall 1 month ago ↶
300
impl std:: fmt:: Debug for PackIndex {
301
fn fmt ( & self , f : & mut std:: fmt:: Formatter< '_ > ) -> std:: fmt:: Result {
302
f.debug_struct ( " PackIndex" )
64818938 Andy McCall 1 month ago ↶
303
.field ( " key" , & self .key)
a17fc622 Andy McCall 1 month ago ↶
304
.field ( " objects" , & self .refs.len ( ) )
305
.field ( " dict" , & self .dict.is_some ( ) )
306
.finish ( )
64818938 Andy McCall 1 month ago ↶
307
}
308
}
309
310
311
fn decode_entry (
312
r : & ObjectRef,
313
e : PackEntry,
314
stored : Vec< u8 > ,
315
dict : Option< & Arc< zstd:: dict:: DecoderDictionary< 'static > > > ,
316
) -> Result< Object> {
317
let body = if e.flags & FLAG_DICT ! = 0 {
767ac6cd Andy McCall 17 days ago
318
let dict = dict.ok_or_else ( | | StoreError:: Corrupt( * r, NO_DICT .into ( ) ) ) ? ;
64818938 Andy McCall 1 month ago ↶
319
zstd:: bulk:: Decompressor:: with_prepared_dictionary( dict)
320
.and_then ( | mut d | d.decompress ( & stored, e.raw_len as usize ) )
321
.map_err ( | err | StoreError:: Corrupt( * r, format! ( " zstd: {err} " ) ) ) ?
322
} else if e.flags & FLAG_ZSTD ! = 0 {
323
zstd:: bulk:: decompress( & stored, e.raw_len as usize )
324
.map_err ( | err | StoreError:: Corrupt( * r, format! ( " zstd: {err} " ) ) ) ?
325
} else {
326
stored
327
} ;
328
if body.len ( ) ! = e.raw_len as usize | | hash_object ( e.ty, & body) ! = * r {
329
return Err ( StoreError:: Corrupt(
330
* r,
331
" packed object does not match its reference" .into ( ) ,
332
) ) ;
a17fc622 Andy McCall 1 month ago ↶
333
}
64818938 Andy McCall 1 month ago ↶
334
Ok ( ( e.ty, body) )
a17fc622 Andy McCall 1 month ago ↶
335
}
336
d02e545d Andy McCall 1 month ago ↶
337
impl PackIndex {
7e0e8e5a Andy McCall 18 days ago ↶
338
767ac6cd Andy McCall 17 days ago
339
340
341
fn load (
342
backend : & Backend,
343
idx_key : & str ,
344
pack_key : & str ,
345
pack_len : u64 ,
346
) -> Result< Option< PackIndex> > {
347
let data = match backend.get ( idx_key) {
348
Ok ( d) => d,
349
Err ( BackendError:: NotFound( _ ) ) => return Ok ( None ) ,
350
Err ( e) => return Err ( backend_err ( e) ) ,
351
} ;
64818938 Andy McCall 1 month ago ↶
352
let bad = | m : & str | StoreError:: Corrupt( ObjectRef:: ZERO , format! ( " {idx_key} : {m} " ) ) ;
d02e545d Andy McCall 1 month ago ↶
353
if data.len ( ) < 12 | | & data[ .. 8 ] ! = IDX_MAGIC {
354
return Err ( bad ( " bad index header" ) ) ;
355
}
356
let count = u32 :: from_le_bytes( data[ 8 .. 12 ] .try_into ( ) .unwrap ( ) ) as usize ;
357
if data.len ( ) ! = 12 + count * IDX_ENTRY {
358
return Err ( bad ( " index length mismatch" ) ) ;
359
}
360
let mut refs = Vec :: with_capacity( count) ;
361
let mut entries = Vec :: with_capacity( count) ;
362
for i in 0 .. count {
363
let e = & data[ 12 + i * IDX_ENTRY .. 12 + ( i + 1 ) * IDX_ENTRY ] ;
364
let r = ObjectRef:: from_slice( & e[ .. 32 ] ) .unwrap ( ) ;
365
if let Some ( prev) = refs.last ( ) {
366
if r < = * prev {
367
return Err ( bad ( " index not sorted" ) ) ;
368
}
369
}
370
refs.push ( r) ;
2b872d07 Andy McCall 1 month ago ↶
371
let entry = PackEntry {
d02e545d Andy McCall 1 month ago ↶
372
offset: u64 :: from_le_bytes( e[ 32 .. 40 ] .try_into ( ) .unwrap ( ) ) ,
373
stored_len: u32 :: from_le_bytes( e[ 40 .. 44 ] .try_into ( ) .unwrap ( ) ) ,
374
raw_len: u32 :: from_le_bytes( e[ 44 .. 48 ] .try_into ( ) .unwrap ( ) ) ,
75167672 Andy McCall 1 month ago
375
ty: ObjectType:: ALL
376
.get ( e[ 48 ] as usize )
377
.copied ( )
378
.ok_or_else ( | | bad ( " unknown object type" ) ) ? ,
d02e545d Andy McCall 1 month ago ↶
379
flags: e[ 49 ] ,
2b872d07 Andy McCall 1 month ago ↶
380
} ;
a9f686ed Andy McCall 1 month ago ↶
381
if entry.stored_len > MAX_OBJECT_LEN | | entry.raw_len > MAX_OBJECT_LEN {
382
return Err ( StoreError:: Corrupt(
383
r,
384
format! (
64818938 Andy McCall 1 month ago ↶
385
" {idx_key} : the index claims an object of {} bytes ({} stored), more than the {MAX_OBJECT_LEN} an object may be" ,
386
entry.raw_len, entry.stored_len
a9f686ed Andy McCall 1 month ago ↶
387
) ,
388
) ) ;
389
}
390
if entry.offset.saturating_add ( entry.stored_len as u64 ) > pack_len {
2b872d07 Andy McCall 1 month ago ↶
391
return Err ( bad ( " index entry points outside the pack" ) ) ;
392
}
393
entries.push ( entry) ;
d02e545d Andy McCall 1 month ago ↶
394
}
64818938 Andy McCall 1 month ago ↶
395
let dict_key = format! ( " {} .dict" , pack_key.trim_end_matches ( " .pack" ) ) ;
396
let dict = get_optional ( backend, & dict_key) ?
397
.map ( | d | Arc:: new( zstd:: dict:: DecoderDictionary:: copy( & d) ) ) ;
767ac6cd Andy McCall 17 days ago
398
Ok ( Some ( PackIndex {
64818938 Andy McCall 1 month ago ↶
399
key: pack_key.to_string ( ) ,
75167672 Andy McCall 1 month ago
400
refs,
401
entries,
a17fc622 Andy McCall 1 month ago ↶
402
dict,
767ac6cd Andy McCall 17 days ago
403
} ) )
d02e545d Andy McCall 1 month ago ↶
404
}
405
406
fn find ( & self , r : & ObjectRef) -> Option< PackEntry> {
407
self .refs.binary_search ( r) .ok ( ) .map ( | i | self .entries[ i] )
408
}
409
64818938 Andy McCall 1 month ago ↶
410
411
fn fetch ( & self , backend : & Backend, r : & ObjectRef, e : PackEntry) -> Result< Object> {
412
let stored = backend
413
.get_range ( & self .key, e.offset.. e.offset + e.stored_len as u64 )
414
.map_err ( | err | match err {
415
BackendError:: NotFound( _ ) => StoreError:: NotFound( * r) ,
416
other => backend_err ( other) ,
a17fc622 Andy McCall 1 month ago ↶
417
} ) ? ;
64818938 Andy McCall 1 month ago ↶
418
decode_entry ( r, e, stored, self .dict.as_ref ( ) )
d02e545d Andy McCall 1 month ago ↶
419
}
420
}
421
422
fn type_index ( ty : ObjectType) -> u8 {
423
ObjectType:: ALL .iter ( ) .position ( | t | * t = = ty) .unwrap ( ) as u8
424
}
425
426
427
# [ derive ( Debug, Clone, Default, PartialEq, Eq ) ]
428
pub struct PackReport {
429
pub objects : usize ,
430
pub raw_bytes : u64 ,
431
pub packed_bytes : u64 ,
432
}
433
135212de Andy McCall 1 month ago ↶
434
435
pub const MAX_PACKS : usize = 16 ;
436
ba160f60 Andy McCall 1 month ago ↶
437
438
# [ derive ( Debug, Clone, Default, PartialEq, Eq ) ]
439
pub struct PruneReport {
440
pub objects : usize ,
441
pub bytes : u64 ,
442
443
pub deferred : usize ,
444
}
445
ff0af1ee unknown 1 month ago
446
# [ derive ( Debug, thiserror::Error ) ]
447
pub enum StoreError {
448
# [ error ( " io: {0}" ) ]
449
Io( # [ from ] io:: Error) ,
450
# [ error ( " corrupt object {0}: {1}" ) ]
451
Corrupt( ObjectRef, String ) ,
452
# [ error ( " object {0}" ) ]
453
Object( # [ from ] ObjectError) ,
454
# [ error ( " object {0} is a {1}, expected {2}" ) ]
455
WrongType( ObjectRef, & 'static str , & 'static str ) ,
456
# [ error ( " object {0} not found" ) ]
457
NotFound( ObjectRef) ,
6f8aeb99 Andy McCall 1 month ago ↶
458
# [ error ( " a {kind} object of {size} bytes is larger than the {limit} bytes an object may be; nothing was stored. A change this large adds or touches too many files at once: commit it in parts (a directory at a time)" ) ]
a9f686ed Andy McCall 1 month ago ↶
459
TooLarge {
460
kind: & 'static str ,
461
size: usize ,
462
limit: u32 ,
463
} ,
ff0af1ee unknown 1 month ago
464
}
465
466
pub type Result < T> = std:: result:: Result< T, StoreError> ;
467
468
pub struct Store {
64818938 Andy McCall 1 month ago ↶
469
backend : Arc< Backend> ,
470
471
472
scratch : PathBuf,
473
474
local : bool ,
767ac6cd Andy McCall 17 days ago
475
packs : RefCell< Vec< Arc< PackIndex> > > ,
476
477
478
packs_listed : RefCell< Listed> ,
479
480
481
has_relisted : std:: cell:: Cell< Option< std:: time:: Instant> > ,
8f10a07a Andy McCall 1 month ago ↶
482
483
484
pending : RefCell< Option< Pending> > ,
485
batch_depth : std:: cell:: Cell< u32 > ,
ce14f0d6 Andy McCall 1 month ago ↶
486
487
metas : RefCell< Option< crate:: fasthash:: FastMap< ObjectRef, crate:: state:: ChangeMeta> > > ,
ef7d4ea6 Andy McCall 16 days ago ↶
488
489
490
entry_lists : RefCell< Vec< String> > ,
491
492
folded : std:: cell:: Cell< bool > ,
493
494
legacy_folded : std:: cell:: Cell< bool > ,
495
496
497
entries : RefCell< Option< std:: collections:: BTreeSet< String> > > ,
771661aa Andy McCall 16 days ago ↶
498
499
entries_read : std:: cell:: Cell< Option< std:: time:: Instant> > ,
500
501
502
lists_read : RefCell< std:: collections:: HashMap< String, Arc< Vec< String> > > > ,
ef7d4ea6 Andy McCall 16 days ago ↶
503
504
505
journal_queue : RefCell< Vec< String> > ,
8f10a07a Andy McCall 1 month ago ↶
506
}
507
64818938 Andy McCall 1 month ago ↶
508
impl std:: fmt:: Debug for Store {
509
fn fmt ( & self , f : & mut std:: fmt:: Formatter< '_ > ) -> std:: fmt:: Result {
510
f.debug_struct ( " Store" )
511
.field ( " backend" , & self .backend.describe ( ) )
512
.field ( " scratch" , & self .scratch)
513
.field ( " packs" , & self .packs.borrow ( ) .len ( ) )
514
.finish ( )
515
}
516
}
517
8f10a07a Andy McCall 1 month ago ↶
518
519
520
521
# [ derive ( Debug ) ]
522
struct Pending {
523
buffered : Vec< ( ObjectType, Vec< u8 > ) > ,
524
buffered_bytes : usize ,
525
lookup : std:: collections:: HashMap< ObjectRef, PendingEntry> ,
526
pack : Option< PendingPack> ,
527
report : PackReport,
ff0af1ee unknown 1 month ago
528
}
529
8f10a07a Andy McCall 1 month ago ↶
530
# [ derive ( Debug, Clone, Copy ) ]
531
enum PendingEntry {
532
Buffered( usize ) ,
533
Packed( PackEntry) ,
534
}
535
536
# [ derive ( Debug ) ]
537
struct PendingPack {
538
id : String,
539
tmp_path : PathBuf,
540
writer : io:: BufWriter< fs:: File> ,
541
offset : u64 ,
542
index : Vec< ( ObjectRef, PackEntry) > ,
543
}
544
545
const SPILL_OBJECTS : usize = 256 ;
546
const SPILL_BYTES : usize = 8 < < 20 ;
547
548
549
pub struct Batch < 'a > {
550
store : & 'a Store,
551
done : bool ,
552
}
553
554
impl Batch < '_ > {
555
pub fn finish ( mut self ) -> Result< ( ) > {
556
self .done = true ;
557
self .store.finish_batch ( )
558
}
559
}
560
561
impl Drop for Batch < '_ > {
562
fn drop ( & mut self ) {
563
if ! self .done {
564
let _ = self .store.finish_batch ( ) ;
565
}
566
}
567
}
568
192fad1e Andy McCall 1 month ago ↶
569
570
fn write_pack_entry (
571
pack : & mut PendingPack,
572
r : & ObjectRef,
573
ty : ObjectType,
574
raw_len : usize ,
575
flags : u8 ,
576
stored : & [u8 ],
577
report : & mut PackReport,
578
) -> Result< PackEntry> {
579
let header_len = 1 + 1 + 4 + 4 + 32 ;
580
pack.writer.write_all ( & [ type_index ( ty) , flags] ) ? ;
581
pack.writer
582
.write_all ( & ( stored.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
583
pack.writer.write_all ( & ( raw_len as u32 ) .to_le_bytes ( ) ) ? ;
584
pack.writer.write_all ( & r.0 ) ? ;
585
pack.writer.write_all ( stored) ? ;
586
let entry = PackEntry {
587
offset: pack.offset + header_len,
588
stored_len: stored.len ( ) as u32 ,
589
raw_len: raw_len as u32 ,
590
ty,
591
flags,
592
} ;
593
pack.offset + = header_len + stored.len ( ) as u64 ;
594
pack.index.push ( ( * r, entry) ) ;
595
report.objects + = 1 ;
596
report.raw_bytes + = raw_len as u64 ;
597
report.packed_bytes + = stored.len ( ) as u64 ;
598
Ok ( entry)
64818938 Andy McCall 1 month ago ↶
599
}
600
601
602
fn fresh_id ( ) -> String {
603
let mut nonce = [ 0 u8 ; 8 ] ;
604
rand:: rngs:: OsRng.fill_bytes ( & mut nonce) ;
605
hex:: encode( nonce)
606
}
607
608
609
610
611
612
fn memory_backend_for ( dir : & Path) -> Option< Arc< Backend> > {
613
use std:: collections:: HashMap;
614
use std:: sync:: { Mutex, OnceLock} ;
615
if std:: env:: var_os( " OXY_STORE_BACKEND" ) .as_deref ( ) ! = Some ( std:: ffi:: OsStr:: new( " memory" ) ) {
616
return None ;
617
}
618
static STORES : OnceLock< Mutex< HashMap< PathBuf, Arc< MemoryStore> > > > = OnceLock:: new( ) ;
619
let key = dir.canonicalize ( ) .unwrap_or_else ( | _| dir.to_path_buf ( ) ) ;
620
let mut map = STORES
621
.get_or_init ( Default :: default)
622
.lock ( )
623
.unwrap_or_else ( | p | p.into_inner ( ) ) ;
624
let store = map
625
.entry ( key)
626
.or_insert_with ( | | Arc:: new( MemoryStore:: new( ) ) )
627
.clone ( ) ;
628
Some ( store)
192fad1e Andy McCall 1 month ago ↶
629
}
630
dd21fd82 Andy McCall 1 month ago ↶
631
# [ cfg ( test ) ]
632
thread_local! {
633
634
635
636
pub ( crate ) static TEST_BACKEND : RefCell< Option< Arc< Backend> > > = const { RefCell:: new( None ) } ;
637
}
638
ff0af1ee unknown 1 month ago
639
impl Store {
64818938 Andy McCall 1 month ago ↶
640
ff0af1ee unknown 1 month ago
641
pub fn open ( dir : impl Into< PathBuf> ) -> io:: Result< Store> {
642
let dir = dir.into ( ) ;
643
fs:: create_dir_all( dir.join ( " loose" ) ) ? ;
dd21fd82 Andy McCall 1 month ago ↶
644
# [ cfg ( test ) ]
645
if let Some ( backend) = TEST_BACKEND .with ( | t | t.borrow ( ) .clone ( ) ) {
646
return Store:: open_on( backend, dir) ;
647
}
64818938 Andy McCall 1 month ago ↶
648
if let Some ( backend) = memory_backend_for ( & dir) {
649
return Store:: open_on( backend, dir) ;
650
}
651
let backend: Arc< Backend> =
652
Arc:: new( LocalStore:: open( & dir) .map_err ( | e | io:: Error:: other( e.to_string ( ) ) ) ? ) ;
653
let mut store = Store:: open_on( backend, dir) ? ;
654
store.local = true ;
655
Ok ( store)
656
}
657
658
659
660
pub fn open_on ( backend : Arc< Backend> , scratch : impl Into< PathBuf> ) -> io:: Result< Store> {
661
let scratch = scratch.into ( ) ;
662
fs:: create_dir_all( & scratch) ? ;
75167672 Andy McCall 1 month ago
663
let store = Store {
64818938 Andy McCall 1 month ago ↶
664
backend,
665
scratch,
666
local: false ,
75167672 Andy McCall 1 month ago
667
packs: RefCell:: new( Vec :: new( ) ) ,
767ac6cd Andy McCall 17 days ago
668
packs_listed: RefCell:: new( Vec :: new( ) ) ,
669
has_relisted: std:: cell:: Cell:: new( None ) ,
75167672 Andy McCall 1 month ago
670
pending: RefCell:: new( None ) ,
671
batch_depth: std:: cell:: Cell:: new( 0 ) ,
ce14f0d6 Andy McCall 1 month ago ↶
672
metas: RefCell:: new( None ) ,
ef7d4ea6 Andy McCall 16 days ago ↶
673
entry_lists: RefCell:: new( Vec :: new( ) ) ,
674
folded: std:: cell:: Cell:: new( false ) ,
675
legacy_folded: std:: cell:: Cell:: new( false ) ,
676
entries: RefCell:: new( None ) ,
771661aa Andy McCall 16 days ago ↶
677
entries_read: std:: cell:: Cell:: new( None ) ,
678
lists_read: RefCell:: new( Default :: default( ) ) ,
ef7d4ea6 Andy McCall 16 days ago ↶
679
journal_queue: RefCell:: new( Vec :: new( ) ) ,
75167672 Andy McCall 1 month ago
680
} ;
681
store
682
.reload_packs ( )
683
.map_err ( | e | io:: Error:: other( e.to_string ( ) ) ) ? ;
d02e545d Andy McCall 1 month ago ↶
684
Ok ( store)
64818938 Andy McCall 1 month ago ↶
685
}
686
687
688
pub fn backend ( & self ) -> & Arc< Backend> {
689
& self .backend
d02e545d Andy McCall 1 month ago ↶
690
}
691
64818938 Andy McCall 1 month ago ↶
692
693
694
pub fn is_local ( & self ) -> bool {
695
self .local
767ac6cd Andy McCall 17 days ago
696
}
697
698
699
700
701
pub fn refresh ( & self ) -> Result< ( ) > {
ef7d4ea6 Andy McCall 16 days ago ↶
702
* self .entries.borrow_mut ( ) = None ;
767ac6cd Andy McCall 17 days ago
703
self .reload_packs ( )
704
}
705
706
707
fn list_packs ( & self ) -> Result< ( Vec< strata:: Entry> , Listed) > {
708
let listed = self .backend.list ( " pack-" ) .map_err ( backend_err) ? ;
709
let sig = listed
710
.iter ( )
711
.map ( | e | ( e.key.clone ( ) , e.size, e.modified_ms) )
712
.collect ( ) ;
713
Ok ( ( listed, sig) )
64818938 Andy McCall 1 month ago ↶
714
}
715
767ac6cd Andy McCall 17 days ago
716
717
718
719
d02e545d Andy McCall 1 month ago ↶
720
fn reload_packs ( & self ) -> Result< ( ) > {
767ac6cd Andy McCall 17 days ago
721
let ( listed, sig) = self .list_packs ( ) ? ;
722
self .load_listed ( listed, sig)
723
}
724
725
fn load_listed ( & self , mut listed : Vec< strata:: Entry> , mut sig : Listed) -> Result< ( ) > {
726
let had: std:: collections:: HashMap< String, Arc< PackIndex> > = self
727
.packs
728
.borrow ( )
729
.iter ( )
730
.map ( | p | ( p.key.clone ( ) , p.clone ( ) ) )
731
.collect ( ) ;
732
let mut loaded: std:: collections:: HashMap< String, Arc< PackIndex> > = Default :: default( ) ;
733
for attempt in 0 .. 2 {
734
let retired = self .retired_in ( & listed) ? ;
735
let mut idx_keys: Vec< & str > = listed
736
.iter ( )
737
.map ( | e | e.key.as_str ( ) )
738
.filter ( | k | k.ends_with ( " .idx" ) )
739
.collect ( ) ;
740
idx_keys.sort ( ) ;
741
let mut packs = Vec :: new( ) ;
742
let mut vanished = false ;
743
for idx in idx_keys {
744
let pack = format! ( " {} .pack" , idx.trim_end_matches ( " .idx" ) ) ;
745
if retired.contains_key ( & pack) {
746
continue ;
747
}
748
let Some ( p) = listed.iter ( ) .find ( | e | e.key = = pack ) else {
749
continue ;
750
} ;
751
if let Some ( kept) = had.get ( & pack) .or_else ( | | loaded.get ( & pack) ) {
752
packs.push ( kept.clone ( ) ) ;
753
continue ;
754
}
755
match PackIndex:: load( self .backend.as_ref ( ) , idx, & pack, p.size) ? {
756
Some ( index) => {
757
let index = Arc:: new( index) ;
758
loaded.insert ( pack, index.clone ( ) ) ;
759
packs.push ( index) ;
760
}
761
None => vanished = true ,
762
}
763
}
764
if vanished & & attempt = = 0 {
765
( listed, sig) = self .list_packs ( ) ? ;
766
continue ;
767
}
ef7d4ea6 Andy McCall 16 days ago ↶
768
let lists: Vec< String> = listed
769
.iter ( )
770
.map ( | e | e.key.as_str ( ) )
771
.filter ( | k | is_entry_list ( k) & & ! retired.contains_key ( * k) )
772
.map ( str :: to_string)
773
.collect ( ) ;
774
self .folded
775
.set ( lists.iter ( ) .any ( | k | k.ends_with ( LIST_SUFFIX ) ) ) ;
776
self .legacy_folded
777
.set ( listed.iter ( ) .any ( | e | e.key = = LEGACY_FOLDED_KEY ) ) ;
778
* self .entry_lists.borrow_mut ( ) = lists;
779
if * self .packs_listed.borrow ( ) ! = sig {
780
* self .entries.borrow_mut ( ) = None ;
781
}
767ac6cd Andy McCall 17 days ago
782
* self .packs.borrow_mut ( ) = packs;
783
* self .packs_listed.borrow_mut ( ) = sig;
784
return Ok ( ( ) ) ;
785
}
786
unreachable! ( " the second round always returns" )
787
}
788
789
790
791
792
793
fn reload_if_changed ( & self ) -> Result< bool > {
794
let ( listed, sig) = self .list_packs ( ) ? ;
795
if * self .packs_listed.borrow ( ) = = sig {
796
return Ok ( false ) ;
797
}
798
self .load_listed ( listed, sig) ? ;
799
Ok ( true )
800
}
801
802
803
804
fn retired_in (
805
& self ,
806
listed : & [strata:: Entry],
807
) -> Result< std:: collections:: BTreeMap< String, u64 > > {
808
match listed.iter ( ) .find ( | e | e.key = = RETIRED_KEY ) {
809
Some ( e) if e.size > 0 => Ok ( self .read_retired ( ) ? .0 ) ,
810
_ => Ok ( Default :: default( ) ) ,
811
}
812
}
813
814
815
fn read_retired (
ef7d4ea6 Andy McCall 16 days ago ↶
816
& self ,
817
) -> Result< (
818
std:: collections:: BTreeMap< String, u64 > ,
819
Option< strata:: Version> ,
820
) > {
821
self .read_record ( RETIRED_KEY )
822
}
823
824
825
826
fn read_record (
767ac6cd Andy McCall 17 days ago
827
& self ,
ef7d4ea6 Andy McCall 16 days ago ↶
828
key : & str ,
767ac6cd Andy McCall 17 days ago
829
) -> Result< (
830
std:: collections:: BTreeMap< String, u64 > ,
831
Option< strata:: Version> ,
832
) > {
ef7d4ea6 Andy McCall 16 days ago ↶
833
match self .backend.read_ref ( key) .map_err ( backend_err) ? {
767ac6cd Andy McCall 17 days ago
834
Some ( ( bytes, v) ) => Ok ( ( parse_retired ( & bytes) , Some ( v) ) ) ,
835
None => Ok ( ( Default :: default( ) , None ) ) ,
836
}
837
}
838
839
840
841
842
fn update_retired (
ef7d4ea6 Andy McCall 16 days ago ↶
843
& self ,
844
edit : impl FnMut( &mut std ::collections ::BTreeMap <String , u64 > ) ,
845
) -> Result< ( ) > {
846
self .update_record ( RETIRED_KEY , " the record of retired packs" , edit)
847
}
848
849
850
851
852
fn update_record (
767ac6cd Andy McCall 17 days ago
853
& self ,
ef7d4ea6 Andy McCall 16 days ago ↶
854
key : & str ,
855
what : & str ,
767ac6cd Andy McCall 17 days ago
856
mut edit : impl FnMut( &mut std ::collections ::BTreeMap <String , u64 > ) ,
857
) -> Result< ( ) > {
858
for _ in 0 .. RETIRED_TRIES {
ef7d4ea6 Andy McCall 16 days ago ↶
859
let ( mut m, version) = self .read_record ( key) ? ;
767ac6cd Andy McCall 17 days ago
860
let before = m.clone ( ) ;
861
edit ( & mut m) ;
ef7d4ea6 Andy McCall 16 days ago ↶
862
863
if m = = before & & ( version.is_some ( ) | | m.is_empty ( ) ) {
767ac6cd Andy McCall 17 days ago
864
return Ok ( ( ) ) ;
865
}
866
match self
867
.backend
ef7d4ea6 Andy McCall 16 days ago ↶
868
.write_ref ( key, & encode_retired ( & m) , version.as_ref ( ) )
767ac6cd Andy McCall 17 days ago
869
{
870
Ok ( _ ) => return Ok ( ( ) ) ,
871
Err ( BackendError:: Conflict( _ ) ) => continue ,
872
Err ( e) => return Err ( backend_err ( e) ) ,
873
}
874
}
ef7d4ea6 Andy McCall 16 days ago ↶
875
Err ( StoreError:: Io( io:: Error:: other( format! (
876
" other writers kept changing {what} ; run the command again"
877
) ) ) )
767ac6cd Andy McCall 17 days ago
878
}
879
880
881
882
883
884
fn retire ( & self , keys : & [String]) -> Result< ( ) > {
885
if keys.is_empty ( ) {
886
return Ok ( ( ) ) ;
887
}
888
let now = now_ms ( ) ;
889
self .update_retired ( | m | {
890
for k in keys {
891
m.entry ( k.clone ( ) ) .or_insert ( now) ;
892
}
893
} )
894
}
895
896
897
898
899
900
901
pub fn expire_retired (
902
& self ,
903
older_than : std:: time:: Duration,
904
progress : Progress,
905
) -> Result< RetiredReport> {
906
let ( listed, _ ) = self .list_packs ( ) ? ;
907
let retired = self .retired_in ( & listed) ? ;
908
let mut report = RetiredReport:: default( ) ;
909
if retired.is_empty ( ) {
910
return Ok ( report) ;
911
}
912
let now = now_ms ( ) ;
913
let older_than = older_than.as_millis ( ) as u64 ;
914
let due: Vec< ( String, u64 ) > = retired
64818938 Andy McCall 1 month ago ↶
915
.iter ( )
767ac6cd Andy McCall 17 days ago
916
.filter ( | ( _, t ) | now.saturating_sub ( * * t) > = older_than )
917
.map ( | ( k , t ) | ( k.clone ( ) , * t) )
d02e545d Andy McCall 1 month ago ↶
918
.collect ( ) ;
767ac6cd Andy McCall 17 days ago
919
report.kept = retired.len ( ) - due.len ( ) ;
920
if due.is_empty ( ) {
921
return Ok ( report) ;
922
}
923
progress ( & format! ( " deleting {} retired files" , due.len ( ) ) ) ;
924
925
self .reload_packs ( ) ? ;
926
for ( key, _ ) in & due {
927
if key.ends_with ( " .pack" ) {
928
self .remove_pack ( key) ? ;
929
report.packs + = 1 ;
ef7d4ea6 Andy McCall 16 days ago ↶
930
} else if is_entry_list ( key) {
931
932
delete ( self .backend.as_ref ( ) , key) ? ;
767ac6cd Andy McCall 17 days ago
933
} else if let Some ( r) = loose_ref ( key) {
934
if self .find_packed ( & r) .is_some ( ) {
935
delete ( self .backend.as_ref ( ) , key) ? ;
936
report.loose + = 1 ;
937
}
d02e545d Andy McCall 1 month ago ↶
938
}
939
}
767ac6cd Andy McCall 17 days ago
940
self .update_retired ( | m | {
941
for ( k, t) in & due {
942
if m.get ( k) = = Some ( t) {
943
m.remove ( k) ;
944
}
945
}
946
} ) ? ;
947
self .reload_packs ( ) ? ;
948
Ok ( report)
d02e545d Andy McCall 1 month ago ↶
949
}
950
767ac6cd Andy McCall 17 days ago
951
952
fn retired_loose ( & self ) -> Result< std:: collections:: HashSet< String> > {
953
let ( listed, _ ) = self .list_packs ( ) ? ;
954
Ok ( self
955
.retired_in ( & listed) ?
956
.into_keys ( )
957
.filter ( | k | k.starts_with ( " loose/" ) )
958
.collect ( ) )
959
}
960
d02e545d Andy McCall 1 month ago ↶
961
pub fn pack_count ( & self ) -> usize {
962
self .packs.borrow ( ) .len ( )
963
}
964
965
fn find_packed ( & self , r : & ObjectRef) -> Option< ( usize , PackEntry) > {
75167672 Andy McCall 1 month ago
966
self .packs
967
.borrow ( )
968
.iter ( )
969
.enumerate ( )
970
.find_map ( | ( i , p ) | p.find ( r) .map ( | e | ( i, e) ) )
d02e545d Andy McCall 1 month ago ↶
971
}
972
767ac6cd Andy McCall 17 days ago
973
974
64818938 Andy McCall 1 month ago ↶
975
fn loose_objects ( & self ) -> Result< Vec< ( ObjectRef, strata:: Entry) > > {
767ac6cd Andy McCall 17 days ago
976
let retired = self .retired_loose ( ) ? ;
977
let mut out = self .loose_objects_all ( ) ? ;
978
out.retain ( | ( _, e ) | ! retired.contains ( & e.key) ) ;
979
Ok ( out)
980
}
981
982
983
fn loose_objects_all ( & self ) -> Result< Vec< ( ObjectRef, strata:: Entry) > > {
64818938 Andy McCall 1 month ago ↶
984
let mut out: Vec< ( ObjectRef, strata:: Entry) > = self
985
.backend
986
.list ( " loose/" )
987
.map_err ( backend_err) ?
988
.into_iter ( )
989
.filter_map ( | e | loose_ref ( & e.key) .map ( | r | ( r, e) ) )
990
.collect ( ) ;
991
out.sort_by_key ( | ( r , _) | * r) ;
d02e545d Andy McCall 1 month ago ↶
992
Ok ( out)
993
}
994
995
pub fn loose_count ( & self ) -> io:: Result< usize > {
64818938 Andy McCall 1 month ago ↶
996
self .loose_objects ( )
997
.map ( | l | l.len ( ) )
998
.map_err ( | e | io:: Error:: other( e.to_string ( ) ) )
d02e545d Andy McCall 1 month ago ↶
999
}
1000
64818938 Andy McCall 1 month ago ↶
1001
1002
d02e545d Andy McCall 1 month ago ↶
1003
pub fn pack_loose ( & self ) -> Result< PackReport> {
1004
let loose = self .loose_objects ( ) ? ;
75167672 Andy McCall 1 month ago
1005
self .write_pack (
1006
& loose.iter ( ) .map ( | ( r , _) | * r) .collect:: < Vec< _ > > ( ) ,
64818938 Andy McCall 1 month ago ↶
1007
& loose.iter ( ) .map ( | ( _, e ) | e.key.clone ( ) ) .collect:: < Vec< _ > > ( ) ,
75167672 Andy McCall 1 month ago
1008
& [ ] ,
da652d63 Andy McCall 1 month ago ↶
1009
ZSTD_LEVEL ,
9ae4d15a Andy McCall 1 month ago ↶
1010
& mut silent ( ) ,
75167672 Andy McCall 1 month ago
1011
)
da652d63 Andy McCall 1 month ago ↶
1012
}
1013
1014
1015
1016
1017
pub fn repack_all ( & self , level : i32 ) -> Result< ( PackReport, usize ) > {
9ae4d15a Andy McCall 1 month ago ↶
1018
self .repack_all_with ( level, & mut silent ( ) )
1019
}
1020
1021
1022
pub fn repack_all_with ( & self , level : i32 , progress : Progress) -> Result< ( PackReport, usize ) > {
da652d63 Andy McCall 1 month ago ↶
1023
let loose = self .loose_objects ( ) ? ;
a67914bc Andy McCall 19 days ago ↶
1024
let ( mut refs, keys, trained) : ( Vec< ObjectRef> , Vec< String> , bool ) = {
da652d63 Andy McCall 1 month ago ↶
1025
let packs = self .packs.borrow ( ) ;
1026
(
1027
packs.iter ( ) .flat_map ( | p | p.refs.iter ( ) .copied ( ) ) .collect ( ) ,
64818938 Andy McCall 1 month ago ↶
1028
packs.iter ( ) .map ( | p | p.key.clone ( ) ) .collect ( ) ,
a67914bc Andy McCall 19 days ago ↶
1029
packs.first ( ) .is_some_and ( | p | p.dict.is_some ( ) ) ,
da652d63 Andy McCall 1 month ago ↶
1030
)
1031
} ;
a67914bc Andy McCall 19 days ago ↶
1032
1033
1034
1035
1036
if loose.is_empty ( ) & & keys.len ( ) < = 1 & & ( level = = ZSTD_LEVEL | | trained) {
da652d63 Andy McCall 1 month ago ↶
1037
return Ok ( ( PackReport:: default( ) , 0 ) ) ;
1038
}
1039
refs.extend ( loose.iter ( ) .map ( | ( r , _) | * r) ) ;
64818938 Andy McCall 1 month ago ↶
1040
let loose_keys: Vec< String> = loose.into_iter ( ) .map ( | ( _, e ) | e.key ) .collect ( ) ;
1041
let n = keys.len ( ) ;
1042
let report = self .write_pack ( & refs, & loose_keys, & keys, level, progress) ? ;
da652d63 Andy McCall 1 month ago ↶
1043
Ok ( ( report, n) )
ba160f60 Andy McCall 1 month ago ↶
1044
}
1045
135212de Andy McCall 1 month ago ↶
1046
1047
1048
pub fn merge_packs ( & self ) -> Result< usize > {
64818938 Andy McCall 1 month ago ↶
1049
let ( refs, keys) : ( Vec< ObjectRef> , Vec< String> ) = {
135212de Andy McCall 1 month ago ↶
1050
let packs = self .packs.borrow ( ) ;
1051
if packs.len ( ) < = MAX_PACKS {
1052
return Ok ( 0 ) ;
1053
}
75167672 Andy McCall 1 month ago
1054
(
1055
packs.iter ( ) .flat_map ( | p | p.refs.iter ( ) .copied ( ) ) .collect ( ) ,
64818938 Andy McCall 1 month ago ↶
1056
packs.iter ( ) .map ( | p | p.key.clone ( ) ) .collect ( ) ,
75167672 Andy McCall 1 month ago
1057
)
135212de Andy McCall 1 month ago ↶
1058
} ;
64818938 Andy McCall 1 month ago ↶
1059
let n = keys.len ( ) ;
1060
self .write_pack ( & refs, & [ ] , & keys, ZSTD_LEVEL , & mut silent ( ) ) ? ;
135212de Andy McCall 1 month ago ↶
1061
Ok ( n)
1062
}
1063
ba160f60 Andy McCall 1 month ago ↶
1064
1065
1066
64818938 Andy McCall 1 month ago ↶
1067
1068
75167672 Andy McCall 1 month ago
1069
pub fn prune (
9ae4d15a Andy McCall 1 month ago ↶
1070
& self ,
1071
keep : & std:: collections:: HashSet< ObjectRef> ,
1072
grace : std:: time:: Duration,
1073
) -> Result< PruneReport> {
1074
self .prune_with ( keep, grace, & mut silent ( ) )
1075
}
1076
1077
1078
pub fn prune_with (
75167672 Andy McCall 1 month ago
1079
& self ,
1080
keep : & std:: collections:: HashSet< ObjectRef> ,
1081
grace : std:: time:: Duration,
9ae4d15a Andy McCall 1 month ago ↶
1082
progress : Progress,
75167672 Andy McCall 1 month ago
1083
) -> Result< PruneReport> {
9ae4d15a Andy McCall 1 month ago ↶
1084
progress ( " pruning loose objects" ) ;
64818938 Andy McCall 1 month ago ↶
1085
let now = now_ms ( ) ;
1086
let grace_ms = grace.as_millis ( ) as u64 ;
1087
1088
let old_enough =
1089
| modified : Option< u64 > | modified.is_none_or ( | t | now.saturating_sub ( t) > = grace_ms ) ;
ba160f60 Andy McCall 1 month ago ↶
1090
let mut report = PruneReport:: default( ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
1091
let mut gone: Vec< String> = Vec :: new( ) ;
767ac6cd Andy McCall 17 days ago
1092
1093
1094
let retired = self .retired_loose ( ) ? ;
1095
let mut unretired: Vec< String> = Vec :: new( ) ;
1096
for ( r, entry) in self .loose_objects_all ( ) ? {
ba160f60 Andy McCall 1 month ago ↶
1097
if keep.contains ( & r) {
1098
continue ;
1099
}
767ac6cd Andy McCall 17 days ago
1100
if retired.contains ( & entry.key) {
1101
if old_enough ( entry.modified_ms) {
1102
delete ( self .backend.as_ref ( ) , & entry.key) ? ;
1103
unretired.push ( entry.key) ;
1104
}
1105
continue ;
1106
}
64818938 Andy McCall 1 month ago ↶
1107
if ! old_enough ( entry.modified_ms) {
ba160f60 Andy McCall 1 month ago ↶
1108
report.deferred + = 1 ;
1109
continue ;
1110
}
64818938 Andy McCall 1 month ago ↶
1111
report.bytes + = entry.size;
ba160f60 Andy McCall 1 month ago ↶
1112
report.objects + = 1 ;
64818938 Andy McCall 1 month ago ↶
1113
delete ( self .backend.as_ref ( ) , & entry.key) ? ;
ef7d4ea6 Andy McCall 16 days ago ↶
1114
self .remove_sidecars ( & r, & mut gone) ? ;
767ac6cd Andy McCall 17 days ago
1115
}
1116
if ! unretired.is_empty ( ) {
1117
self .update_retired ( | m | {
1118
for k in & unretired {
1119
m.remove ( k) ;
1120
}
1121
} ) ? ;
ba160f60 Andy McCall 1 month ago ↶
1122
}
1123
1124
let mut keep_refs: Vec< ObjectRef> = Vec :: new( ) ;
64818938 Andy McCall 1 month ago ↶
1125
let mut old_keys: Vec< String> = Vec :: new( ) ;
ba160f60 Andy McCall 1 month ago ↶
1126
let mut rewrite = false ;
9ae4d15a Andy McCall 1 month ago ↶
1127
progress ( " pruning packs" ) ;
ba160f60 Andy McCall 1 month ago ↶
1128
for p in self .packs.borrow ( ) .iter ( ) {
1129
let unreachable = p.refs.iter ( ) .filter ( | r | ! keep.contains ( r) ) .count ( ) ;
1130
if unreachable = = 0 {
1131
continue ;
1132
}
64818938 Andy McCall 1 month ago ↶
1133
let modified = self
1134
.backend
1135
.stat ( & p.key)
1136
.map_err ( backend_err) ?
1137
.and_then ( | e | e.modified_ms ) ;
1138
if ! old_enough ( modified) {
ba160f60 Andy McCall 1 month ago ↶
1139
report.deferred + = unreachable;
1140
continue ;
1141
}
1142
rewrite = true ;
64818938 Andy McCall 1 month ago ↶
1143
old_keys.push ( p.key.clone ( ) ) ;
ba160f60 Andy McCall 1 month ago ↶
1144
for ( r, e) in p.refs.iter ( ) .zip ( p.entries.iter ( ) ) {
1145
if keep.contains ( r) {
1146
keep_refs.push ( * r) ;
1147
} else {
1148
report.objects + = 1 ;
1149
report.bytes + = e.stored_len as u64 ;
1150
}
1151
}
1152
}
1153
if rewrite {
1154
let dropped: Vec< ObjectRef> = {
1155
let packs = self .packs.borrow ( ) ;
75167672 Andy McCall 1 month ago
1156
packs
1157
.iter ( )
64818938 Andy McCall 1 month ago ↶
1158
.filter ( | p | old_keys.contains ( & p.key) )
75167672 Andy McCall 1 month ago
1159
.flat_map ( | p | p.refs.iter ( ) .copied ( ) )
1160
.filter ( | r | ! keep.contains ( r) )
1161
.collect ( )
ba160f60 Andy McCall 1 month ago ↶
1162
} ;
64818938 Andy McCall 1 month ago ↶
1163
self .write_pack ( & keep_refs, & [ ] , & old_keys, ZSTD_LEVEL , progress) ? ;
ba160f60 Andy McCall 1 month ago ↶
1164
for r in dropped {
ef7d4ea6 Andy McCall 16 days ago ↶
1165
self .remove_sidecars ( & r, & mut gone) ? ;
ba160f60 Andy McCall 1 month ago ↶
1166
}
1167
}
ef7d4ea6 Andy McCall 16 days ago ↶
1168
self .journal_forget ( & gone) ? ;
ba160f60 Andy McCall 1 month ago ↶
1169
Ok ( report)
1170
}
1171
64818938 Andy McCall 1 month ago ↶
1172
1173
ef7d4ea6 Andy McCall 16 days ago ↶
1174
1175
fn remove_sidecars ( & self , r : & ObjectRef, gone : & mut Vec< String> ) -> Result< ( ) > {
64818938 Andy McCall 1 month ago ↶
1176
for index in [ " sigs" , " seals" , " receipts" ] {
1177
delete ( self .backend.as_ref ( ) , & legacy_key ( index, r) ) ? ;
1178
}
1179
for index in [ " sig" , " seal" , " receipt" ] {
1180
for e in self
1181
.backend
1182
.list ( & fanout_prefix ( index, r) )
1183
.map_err ( backend_err) ?
1184
{
1185
delete ( self .backend.as_ref ( ) , & e.key) ? ;
ef7d4ea6 Andy McCall 16 days ago ↶
1186
gone.push ( e.key) ;
ba160f60 Andy McCall 1 month ago ↶
1187
}
1188
}
1189
Ok ( ( ) )
1190
}
1191
ef7d4ea6 Andy McCall 16 days ago ↶
1192
1193
1194
fn journal_forget ( & self , gone : & [String]) -> Result< ( ) > {
1195
if self .local | | gone.is_empty ( ) {
1196
return Ok ( ( ) ) ;
1197
}
1198
if let Some ( set) = self .entries.borrow_mut ( ) .as_mut ( ) {
1199
for k in gone {
1200
set.remove ( k) ;
1201
}
1202
}
1203
self .update_record ( JOURNAL_KEY , " the journal of entries" , | m | {
1204
for k in gone {
1205
m.remove ( k) ;
1206
}
1207
} )
1208
}
1209
64818938 Andy McCall 1 month ago ↶
1210
1211
1212
75167672 Andy McCall 1 month ago
1213
fn finish_pack_files (
1214
& self ,
1215
id : & str ,
1216
tmp_pack : & Path,
1217
index : & [( ObjectRef , PackEntry ) ],
1218
) -> Result< ( ) > {
64818938 Andy McCall 1 month ago ↶
1219
let mut idx = Vec :: with_capacity( 12 + index.len ( ) * IDX_ENTRY ) ;
1220
idx.extend_from_slice ( IDX_MAGIC ) ;
1221
idx.extend_from_slice ( & ( index.len ( ) as u32 ) .to_le_bytes ( ) ) ;
1222
for ( r, e) in index {
1223
idx.extend_from_slice ( & r.0 ) ;
1224
idx.extend_from_slice ( & e.offset.to_le_bytes ( ) ) ;
1225
idx.extend_from_slice ( & e.stored_len.to_le_bytes ( ) ) ;
1226
idx.extend_from_slice ( & e.raw_len.to_le_bytes ( ) ) ;
1227
idx.extend_from_slice ( & [ type_index ( e.ty) , e.flags] ) ;
8f10a07a Andy McCall 1 month ago ↶
1228
}
64818938 Andy McCall 1 month ago ↶
1229
let put = self
1230
.backend
1231
.put_new_file ( & format! ( " pack-{id} .pack" ) , tmp_pack)
1232
.map_err ( backend_err) ;
1233
1234
1235
let _ = fs:: remove_file( tmp_pack) ;
1236
put? ;
1237
self .backend
1238
.put_new ( & format! ( " pack-{id} .idx" ) , & idx)
1239
.map_err ( backend_err) ? ;
8f10a07a Andy McCall 1 month ago ↶
1240
self .reload_packs ( )
64818938 Andy McCall 1 month ago ↶
1241
}
1242
767ac6cd Andy McCall 17 days ago
1243
1244
64818938 Andy McCall 1 month ago ↶
1245
fn remove_pack ( & self , pack_key : & str ) -> Result< ( ) > {
1246
let stem = pack_key.trim_end_matches ( " .pack" ) ;
767ac6cd Andy McCall 17 days ago
1247
delete ( self .backend.as_ref ( ) , & format! ( " {stem} .idx" ) ) ? ;
64818938 Andy McCall 1 month ago ↶
1248
delete ( self .backend.as_ref ( ) , pack_key) ? ;
1249
delete ( self .backend.as_ref ( ) , & format! ( " {stem} .dict" ) )
8f10a07a Andy McCall 1 month ago ↶
1250
}
1251
767ac6cd Andy McCall 17 days ago
1252
1253
1254
1255
75167672 Andy McCall 1 month ago
1256
fn write_pack (
1257
& self ,
1258
refs : & [ObjectRef],
64818938 Andy McCall 1 month ago ↶
1259
loose_keys : & [String],
1260
old_packs : & [String],
da652d63 Andy McCall 1 month ago ↶
1261
level : i32 ,
9ae4d15a Andy McCall 1 month ago ↶
1262
progress : Progress,
75167672 Andy McCall 1 month ago
1263
) -> Result< PackReport> {
ba160f60 Andy McCall 1 month ago ↶
1264
if refs.is_empty ( ) {
767ac6cd Andy McCall 17 days ago
1265
self .retire ( old_packs) ? ;
ba160f60 Andy McCall 1 month ago ↶
1266
self .reload_packs ( ) ? ;
d02e545d Andy McCall 1 month ago ↶
1267
return Ok ( PackReport:: default( ) ) ;
1268
}
ba160f60 Andy McCall 1 month ago ↶
1269
let mut refs: Vec< ObjectRef> = refs.to_vec ( ) ;
1270
refs.sort ( ) ;
1271
refs.dedup ( ) ;
64818938 Andy McCall 1 month ago ↶
1272
let id = fresh_id ( ) ;
1273
let tmp_pack = self .scratch.join ( format! ( " .tmp-{id} .pack" ) ) ;
d02e545d Andy McCall 1 month ago ↶
1274
let mut report = PackReport:: default( ) ;
ba160f60 Andy McCall 1 month ago ↶
1275
let mut index: Vec< ( ObjectRef, PackEntry) > = Vec :: with_capacity( refs.len ( ) ) ;
a17fc622 Andy McCall 1 month ago ↶
1276
1277
let dict = if level = = REPACK_ZSTD_LEVEL & & refs.len ( ) > = DICT_MIN_OBJECTS {
1278
let _t = crate :: timing:: phase( " pack: train a dictionary" ) ;
9ae4d15a Andy McCall 1 month ago ↶
1279
progress ( & format! ( " training a dictionary on {} objects" , refs.len ( ) ) ) ;
a17fc622 Andy McCall 1 month ago ↶
1280
self .train_dictionary ( & refs)
1281
} else {
1282
None
1283
} ;
1284
let encoder = dict
1285
.as_ref ( )
1286
.map ( | d | zstd:: dict:: EncoderDictionary:: copy( d, level) ) ;
64818938 Andy McCall 1 month ago ↶
1287
let nocompress = self .nocompress_set ( ) ? ;
d02e545d Andy McCall 1 month ago ↶
1288
{
1289
let mut f = io:: BufWriter:: new( fs:: File:: create( & tmp_pack) ? ) ;
1290
f.write_all ( PACK_MAGIC ) ? ;
1291
let mut offset = PACK_MAGIC .len ( ) as u64 ;
da652d63 Andy McCall 1 month ago ↶
1292
1293
1294
let mut batches = refs.chunks ( 1024 ) ;
1295
let mut compressed_batch = Vec :: new( ) ;
9ae4d15a Andy McCall 1 month ago ↶
1296
let total = refs.len ( ) ;
1297
let mut reported = usize :: MAX ;
da652d63 Andy McCall 1 month ago ↶
1298
loop {
1299
if compressed_batch.is_empty ( ) {
1300
let Some ( batch) = batches.next ( ) else { break } ;
9ae4d15a Andy McCall 1 month ago ↶
1301
1302
let tenth = report.objects * 10 / total.max ( 1 ) ;
1303
if tenth ! = reported {
1304
reported = tenth;
1305
progress ( & format! ( " packing {} of {total} objects" , report.objects) ) ;
1306
}
da652d63 Andy McCall 1 month ago ↶
1307
let mut read: Vec< ( ObjectRef, ObjectType, Vec< u8 > , bool ) > =
1308
Vec :: with_capacity( batch.len ( ) ) ;
1309
for r in batch {
1310
let ( ty, body) = self .get ( r) ? ;
64818938 Andy McCall 1 month ago ↶
1311
read.push ( ( * r, ty, body, nocompress.contains ( r) ) ) ;
75167672 Andy McCall 1 month ago
1312
}
da652d63 Andy McCall 1 month ago ↶
1313
use rayon:: prelude:: * ;
1314
compressed_batch = read
1315
.into_par_iter ( )
a17fc622 Andy McCall 1 month ago ↶
1316
.map_init (
1317
| | {
1318
encoder.as_ref ( ) .and_then ( | e | {
1319
zstd:: bulk:: Compressor:: with_prepared_dictionary( e) .ok ( )
1320
} )
1321
} ,
1322
| with_dict , ( r , ty , body , raw ) | {
1323
let packed = if raw {
1324
None
1325
} else {
1326
1327
1328
let dicted = with_dict
1329
.as_mut ( )
1330
.filter ( | _| body.len ( ) < = DICT_OBJECT_MAX )
1331
.and_then ( | c | c.compress ( & body) .ok ( ) )
1332
.map ( | c | ( FLAG_ZSTD | FLAG_DICT , c) ) ;
1333
dicted
1334
.or_else ( | | {
1335
zstd:: bulk:: compress( & body, level)
1336
.ok ( )
1337
.map ( | c | ( FLAG_ZSTD , c) )
1338
} )
1339
.filter ( | ( _, c ) | c.len ( ) < body.len ( ) )
1340
} ;
1341
( r, ty, body, packed)
1342
} ,
1343
)
da652d63 Andy McCall 1 month ago ↶
1344
.collect:: < Vec< _ > > ( ) ;
1345
compressed_batch.reverse ( ) ;
1346
}
1347
let Some ( ( r, ty, body, packed) ) = compressed_batch.pop ( ) else {
1348
continue ;
1349
} ;
1350
let r = & r;
1351
let ( flags, stored) = match packed {
a17fc622 Andy McCall 1 month ago ↶
1352
Some ( c) => c,
da652d63 Andy McCall 1 month ago ↶
1353
None => ( 0 , body.clone ( ) ) ,
cdb5beba Andy McCall 1 month ago ↶
1354
} ;
d02e545d Andy McCall 1 month ago ↶
1355
let header_len = 1 + 1 + 4 + 4 + 32 ;
1356
f.write_all ( & [ type_index ( ty) , flags] ) ? ;
1357
f.write_all ( & ( stored.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
1358
f.write_all ( & ( body.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
1359
f.write_all ( & r.0 ) ? ;
1360
f.write_all ( & stored) ? ;
75167672 Andy McCall 1 month ago
1361
index.push ( (
1362
* r,
1363
PackEntry {
1364
offset: offset + header_len,
1365
stored_len: stored.len ( ) as u32 ,
1366
raw_len: body.len ( ) as u32 ,
1367
ty,
1368
flags,
1369
} ,
1370
) ) ;
d02e545d Andy McCall 1 month ago ↶
1371
offset + = header_len + stored.len ( ) as u64 ;
1372
report.objects + = 1 ;
1373
report.raw_bytes + = body.len ( ) as u64 ;
1374
report.packed_bytes + = stored.len ( ) as u64 ;
1375
}
1376
f.flush ( ) ? ;
1377
f.get_ref ( ) .sync_all ( ) ? ;
a17fc622 Andy McCall 1 month ago ↶
1378
}
1379
1380
if let Some ( d) = & dict {
64818938 Andy McCall 1 month ago ↶
1381
self .backend
1382
.put_new ( & format! ( " pack-{id} .dict" ) , d)
1383
.map_err ( backend_err) ? ;
d02e545d Andy McCall 1 month ago ↶
1384
}
9ae4d15a Andy McCall 1 month ago ↶
1385
progress ( & format! ( " writing the index of {} objects" , index.len ( ) ) ) ;
8f10a07a Andy McCall 1 month ago ↶
1386
self .finish_pack_files ( & id, & tmp_pack, & index) ? ;
767ac6cd Andy McCall 17 days ago
1387
let mut retired = old_packs.to_vec ( ) ;
1388
retired.extend_from_slice ( loose_keys) ;
1389
self .retire ( & retired) ? ;
d02e545d Andy McCall 1 month ago ↶
1390
self .reload_packs ( ) ? ;
1391
Ok ( report)
ff0af1ee unknown 1 month ago
1392
}
1393
a17fc622 Andy McCall 1 month ago ↶
1394
1395
1396
fn train_dictionary ( & self , refs : & [ObjectRef]) -> Option< Vec< u8 > > {
1397
let step = ( refs.len ( ) / 10_000 ) .max ( 1 ) ;
1398
let mut samples: Vec< Vec< u8 > > = Vec :: new( ) ;
1399
let mut total = 0 usize ;
1400
for r in refs.iter ( ) .step_by ( step) {
1401
if total > 32 < < 20 {
1402
break ;
1403
}
1404
let Ok ( ( ty, body) ) = self .get ( r) else {
1405
continue ;
1406
} ;
1407
if matches! (
1408
ty,
1409
ObjectType:: Chunk | ObjectType:: Blob | ObjectType:: Change
1410
) & & ! body.is_empty ( )
1411
& & body.len ( ) < 1 < < 20
1412
{
1413
total + = body.len ( ) ;
1414
samples.push ( body) ;
1415
}
1416
}
1417
zstd:: dict:: from_samples( & samples, DICT_BYTES ) .ok ( )
1418
}
1419
64818938 Andy McCall 1 month ago ↶
1420
ff0af1ee unknown 1 month ago
1421
pub fn dir ( & self ) -> & Path {
64818938 Andy McCall 1 month ago ↶
1422
& self .scratch
ff0af1ee unknown 1 month ago
1423
}
1424
64818938 Andy McCall 1 month ago ↶
1425
1426
1427
# [ cfg ( test ) ]
387335ff Andy McCall 1 month ago ↶
1428
pub ( crate ) fn path_for ( & self , r : & ObjectRef) -> PathBuf {
64818938 Andy McCall 1 month ago ↶
1429
self .scratch.join ( loose_key ( r) )
1430
}
1431
1432
1433
1434
# [ cfg ( test ) ]
1435
pub ( crate ) fn remove_loose_for_test ( & self , r : & ObjectRef) -> Result< ( ) > {
1436
delete ( self .backend.as_ref ( ) , & loose_key ( r) )
ff0af1ee unknown 1 month ago
1437
}
1438
767ac6cd Andy McCall 17 days ago
1439
1440
1441
1442
ff0af1ee unknown 1 month ago
1443
pub fn has ( & self , r : & ObjectRef) -> bool {
767ac6cd Andy McCall 17 days ago
1444
if self .has_now ( r) {
1445
return true ;
1446
}
1447
let recent = self
1448
.has_relisted
1449
.get ( )
1450
.is_some_and ( | t | t.elapsed ( ) < HAS_RELIST_AFTER ) ;
1451
if recent {
1452
return false ;
1453
}
1454
match self .reload_if_changed ( ) {
1455
Ok ( true ) => {
1456
self .has_relisted.set ( None ) ;
1457
self .has_now ( r)
1458
}
1459
_ => {
1460
self .has_relisted.set ( Some ( std:: time:: Instant:: now( ) ) ) ;
1461
false
1462
}
1463
}
1464
}
1465
1466
1467
fn has_now ( & self , r : & ObjectRef) -> bool {
1468
self .find_packed ( r) .is_some ( )
75167672 Andy McCall 1 month ago
1469
| | self
1470
.pending
1471
.borrow ( )
1472
.as_ref ( )
1473
.is_some_and ( | p | p.lookup.contains_key ( r) )
767ac6cd Andy McCall 17 days ago
1474
| | self .backend.has ( & loose_key ( r) ) .unwrap_or ( false )
ff0af1ee unknown 1 month ago
1475
}
1476
8f10a07a Andy McCall 1 month ago ↶
1477
1478
1479
1480
1481
pub fn begin_batch ( & self ) -> Result< Batch< '_ > > {
1482
let depth = self .batch_depth.get ( ) ;
1483
if depth = = 0 {
75167672 Andy McCall 1 month ago
1484
* self .pending.borrow_mut ( ) = Some ( Pending {
1485
buffered: vec! [ ] ,
1486
buffered_bytes: 0 ,
1487
lookup: Default :: default( ) ,
1488
pack: None ,
1489
report: PackReport:: default( ) ,
1490
} ) ;
8f10a07a Andy McCall 1 month ago ↶
1491
}
1492
self .batch_depth.set ( depth + 1 ) ;
75167672 Andy McCall 1 month ago
1493
Ok ( Batch {
1494
store: self ,
1495
done: false ,
1496
} )
8f10a07a Andy McCall 1 month ago ↶
1497
}
1498
1499
fn finish_batch ( & self ) -> Result< ( ) > {
1500
let depth = self .batch_depth.get ( ) ;
1501
if depth = = 0 {
1502
return Ok ( ( ) ) ;
1503
}
1504
self .batch_depth.set ( depth - 1 ) ;
1505
if depth > 1 {
1506
return Ok ( ( ) ) ;
1507
}
75167672 Andy McCall 1 month ago
1508
let Some ( pending) = self .pending.borrow_mut ( ) .take ( ) else {
ef7d4ea6 Andy McCall 16 days ago ↶
1509
return self .flush_journal ( ) ;
75167672 Andy McCall 1 month ago
1510
} ;
ef7d4ea6 Andy McCall 16 days ago ↶
1511
self .write_pending ( pending) ? ;
1512
self .flush_journal ( )
4dcb8c09 Andy McCall 1 month ago ↶
1513
}
1514
1515
1516
1517
1518
pub fn flush ( & self ) -> Result< ( ) > {
1519
let Some ( pending) = self .pending.borrow_mut ( ) .take ( ) else {
ef7d4ea6 Andy McCall 16 days ago ↶
1520
return self .flush_journal ( ) ;
4dcb8c09 Andy McCall 1 month ago ↶
1521
} ;
1522
self .write_pending ( pending) ? ;
ef7d4ea6 Andy McCall 16 days ago ↶
1523
self .flush_journal ( ) ? ;
4dcb8c09 Andy McCall 1 month ago ↶
1524
* self .pending.borrow_mut ( ) = Some ( Pending {
1525
buffered: vec! [ ] ,
1526
buffered_bytes: 0 ,
1527
lookup: Default :: default( ) ,
1528
pack: None ,
1529
report: PackReport:: default( ) ,
1530
} ) ;
1531
Ok ( ( ) )
1532
}
1533
1534
fn write_pending ( & self , pending : Pending) -> Result< ( ) > {
8f10a07a Andy McCall 1 month ago ↶
1535
match pending.pack {
1536
None => {
b30a880f Andy McCall 1 month ago ↶
1537
let objects: Vec< ( ObjectType, & [u8 ]) > = pending
1538
.buffered
1539
.iter ( )
1540
.map ( | ( ty , body ) | ( * ty, body.as_slice ( ) ) )
1541
.collect ( ) ;
1542
self .put_loose_many ( & objects)
8f10a07a Andy McCall 1 month ago ↶
1543
}
1544
Some ( mut pack) => {
1545
pack.writer.flush ( ) ? ;
1546
pack.writer.get_ref ( ) .sync_all ( ) ? ;
1547
drop ( pack.writer) ;
1548
pack.index.sort_by_key ( | ( r , _) | * r) ;
1549
self .finish_pack_files ( & pack.id, & pack.tmp_path, & pack.index) ? ;
1550
Ok ( ( ) )
1551
}
1552
}
1553
}
1554
1555
64818938 Andy McCall 1 month ago ↶
1556
fn pending_get ( & self , r : & ObjectRef) -> Option< Result< Object> > {
8f10a07a Andy McCall 1 month ago ↶
1557
let mut guard = self .pending.borrow_mut ( ) ;
1558
let pending = guard.as_mut ( ) ? ;
1559
let entry = * pending.lookup.get ( r) ? ;
1560
Some ( match entry {
1561
PendingEntry:: Buffered( i) => {
1562
let ( ty, body) = & pending.buffered[ i] ;
1563
Ok ( ( * ty, body.clone ( ) ) )
1564
}
1565
PendingEntry:: Packed( e) => {
75167672 Andy McCall 1 month ago
1566
let Some ( pack) = pending.pack.as_mut ( ) else {
1567
return Some ( Err ( StoreError:: NotFound( * r) ) ) ;
1568
} ;
64818938 Andy McCall 1 month ago ↶
1569
1570
( | | {
1571
pack.writer.flush ( ) ? ;
1572
use std:: io:: { Read, Seek, SeekFrom} ;
1573
let mut f = fs:: File:: open( & pack.tmp_path) ? ;
1574
f.seek ( SeekFrom:: Start( e.offset) ) ? ;
1575
let mut stored = vec! [ 0 u8 ; e.stored_len as usize ] ;
1576
f.read_exact ( & mut stored) ? ;
1577
decode_entry ( r, e, stored, None )
1578
} ) ( )
8f10a07a Andy McCall 1 month ago ↶
1579
}
1580
} )
1581
}
1582
1583
75167672 Andy McCall 1 month ago
1584
fn pending_pack_write (
1585
& self ,
1586
pack : & mut PendingPack,
1587
r : & ObjectRef,
1588
ty : ObjectType,
1589
body : & [u8 ],
1590
report : & mut PackReport,
1591
) -> Result< PackEntry> {
8f10a07a Andy McCall 1 month ago ↶
1592
let ( flags, stored) = if self .is_nocompress ( r) {
1593
( 0 , body.to_vec ( ) )
1594
} else {
75167672 Andy McCall 1 month ago
1595
let compressed = zstd:: bulk:: compress( body, ZSTD_LEVEL )
1596
.map_err ( | e | StoreError:: Corrupt( * r, format! ( " zstd: {e} " ) ) ) ? ;
1597
if compressed.len ( ) < body.len ( ) {
1598
( FLAG_ZSTD , compressed)
1599
} else {
1600
( 0 , body.to_vec ( ) )
1601
}
8f10a07a Andy McCall 1 month ago ↶
1602
} ;
192fad1e Andy McCall 1 month ago ↶
1603
write_pack_entry ( pack, r, ty, body.len ( ) , flags, & stored, report)
8f10a07a Andy McCall 1 month ago ↶
1604
}
1605
1606
fn put_pending ( & self , r : ObjectRef, ty : ObjectType, body : & [u8 ]) -> Result< ( ) > {
1607
let mut guard = self .pending.borrow_mut ( ) ;
1608
let pending = guard.as_mut ( ) .expect ( " batch open" ) ;
1609
if pending.lookup.contains_key ( & r) {
1610
return Ok ( ( ) ) ;
1611
}
75167672 Andy McCall 1 month ago
1612
if pending.pack.is_none ( )
1613
& & pending.buffered.len ( ) < SPILL_OBJECTS
1614
& & pending.buffered_bytes + body.len ( ) < = SPILL_BYTES
1615
{
8f10a07a Andy McCall 1 month ago ↶
1616
pending.buffered.push ( ( ty, body.to_vec ( ) ) ) ;
1617
pending.buffered_bytes + = body.len ( ) ;
75167672 Andy McCall 1 month ago
1618
pending
1619
.lookup
1620
.insert ( r, PendingEntry:: Buffered( pending.buffered.len ( ) - 1 ) ) ;
8f10a07a Andy McCall 1 month ago ↶
1621
return Ok ( ( ) ) ;
1622
}
192fad1e Andy McCall 1 month ago ↶
1623
self .ensure_pack ( pending) ? ;
1624
let mut report = std:: mem:: take( & mut pending.report) ;
1625
let pack = pending.pack.as_mut ( ) .unwrap ( ) ;
1626
let e = self .pending_pack_write ( pack, & r, ty, body, & mut report) ? ;
1627
pending.report = report;
1628
pending.lookup.insert ( r, PendingEntry:: Packed( e) ) ;
1629
Ok ( ( ) )
1630
}
1631
1632
1633
1634
fn ensure_pack ( & self , pending : & mut Pending) -> Result< ( ) > {
8f10a07a Andy McCall 1 month ago ↶
1635
if pending.pack.is_none ( ) {
1636
64818938 Andy McCall 1 month ago ↶
1637
let id = fresh_id ( ) ;
1638
let tmp_path = self .scratch.join ( format! ( " .tmp-{id} .pack" ) ) ;
8f10a07a Andy McCall 1 month ago ↶
1639
let mut writer = io:: BufWriter:: new( fs:: File:: create( & tmp_path) ? ) ;
1640
writer.write_all ( PACK_MAGIC ) ? ;
75167672 Andy McCall 1 month ago
1641
let mut pack = PendingPack {
1642
id,
1643
tmp_path,
1644
writer,
1645
offset: PACK_MAGIC .len ( ) as u64 ,
1646
index: vec! [ ] ,
1647
} ;
8f10a07a Andy McCall 1 month ago ↶
1648
let buffered = std:: mem:: take( & mut pending.buffered) ;
1649
pending.buffered_bytes = 0 ;
1650
let mut report = std:: mem:: take( & mut pending.report) ;
1651
for ( bty, bbody) in & buffered {
1652
let br = hash_object ( * bty, bbody) ;
1653
let e = self .pending_pack_write ( & mut pack, & br, * bty, bbody, & mut report) ? ;
1654
pending.lookup.insert ( br, PendingEntry:: Packed( e) ) ;
1655
}
1656
pending.report = report;
1657
pending.pack = Some ( pack) ;
192fad1e Andy McCall 1 month ago ↶
1658
}
1659
Ok ( ( ) )
1660
}
1661
1662
1663
1664
1665
pub fn put_many ( & self , objects : & [( ObjectType , &[u8 ]) ]) -> Result< Vec< ObjectRef> > {
1666
use rayon:: prelude:: * ;
1667
let total: usize = objects.iter ( ) .map ( | ( _, b ) | b.len ( ) ) .sum ( ) ;
1668
if self .pending.borrow ( ) .is_none ( ) | | total < SPILL_BYTES {
1669
return objects.iter ( ) .map ( | ( ty , b ) | self .put ( * ty, b) ) .collect ( ) ;
1670
}
1671
for ( ty, b) in objects {
1672
if b.len ( ) > MAX_OBJECT_LEN as usize {
1673
return Err ( StoreError:: TooLarge {
1674
kind: ty.name ( ) ,
1675
size: b.len ( ) ,
1676
limit: MAX_OBJECT_LEN ,
1677
} ) ;
1678
}
8f10a07a Andy McCall 1 month ago ↶
1679
}
192fad1e Andy McCall 1 month ago ↶
1680
let refs: Vec< ObjectRef> = objects
1681
.par_iter ( )
1682
.map ( | ( ty , b ) | hash_object ( * ty, b) )
1683
.collect ( ) ;
1684
1685
let mut seen: std:: collections:: HashSet< ObjectRef> = std:: collections:: HashSet:: new( ) ;
1686
let mut todo: Vec< usize > = Vec :: new( ) ;
1687
for ( i, r) in refs.iter ( ) .enumerate ( ) {
1688
let known = self
1689
.pending
1690
.borrow ( )
1691
.as_ref ( )
1692
.is_some_and ( | p | p.lookup.contains_key ( r) ) ;
1693
if seen.insert ( * r)
1694
& & ! known
1695
& & self .find_packed ( r) .is_none ( )
64818938 Andy McCall 1 month ago ↶
1696
& & ! self .backend.has ( & loose_key ( r) ) .unwrap_or ( false )
192fad1e Andy McCall 1 month ago ↶
1697
{
1698
todo.push ( i) ;
1699
}
1700
}
64818938 Andy McCall 1 month ago ↶
1701
let raw = self .nocompress_set ( ) ? ;
192fad1e Andy McCall 1 month ago ↶
1702
let packed: Vec< ( u8 , Vec< u8 > ) > = todo
1703
.par_iter ( )
1704
.map ( | i | {
1705
let body = objects[ * i] .1 ;
1706
if raw.contains ( & refs[ * i] ) {
1707
return ( 0 , body.to_vec ( ) ) ;
1708
}
1709
match zstd:: bulk:: compress( body, ZSTD_LEVEL ) {
1710
Ok ( c) if c.len ( ) < body.len ( ) => ( FLAG_ZSTD , c) ,
1711
_ => ( 0 , body.to_vec ( ) ) ,
1712
}
1713
} )
1714
.collect ( ) ;
1715
let mut guard = self .pending.borrow_mut ( ) ;
1716
let pending = guard.as_mut ( ) .expect ( " batch open" ) ;
1717
self .ensure_pack ( pending) ? ;
8f10a07a Andy McCall 1 month ago ↶
1718
let mut report = std:: mem:: take( & mut pending.report) ;
1719
let pack = pending.pack.as_mut ( ) .unwrap ( ) ;
192fad1e Andy McCall 1 month ago ↶
1720
for ( i, ( flags, stored) ) in todo.iter ( ) .zip ( packed) {
1721
let ( ty, body) = objects[ * i] ;
1722
let e = write_pack_entry ( pack, & refs[ * i] , ty, body.len ( ) , flags, & stored, & mut report) ? ;
1723
pending.lookup.insert ( refs[ * i] , PendingEntry:: Packed( e) ) ;
1724
}
8f10a07a Andy McCall 1 month ago ↶
1725
pending.report = report;
192fad1e Andy McCall 1 month ago ↶
1726
Ok ( refs)
8f10a07a Andy McCall 1 month ago ↶
1727
}
1728
ff0af1ee unknown 1 month ago
1729
1730
pub fn put ( & self , ty : ObjectType, body : & [u8 ]) -> Result< ObjectRef> {
a9f686ed Andy McCall 1 month ago ↶
1731
1732
1733
1734
if body.len ( ) > MAX_OBJECT_LEN as usize {
1735
return Err ( StoreError:: TooLarge {
1736
kind: ty.name ( ) ,
1737
size: body.len ( ) ,
1738
limit: MAX_OBJECT_LEN ,
1739
} ) ;
1740
}
ff0af1ee unknown 1 month ago
1741
let r = hash_object ( ty, body) ;
64818938 Andy McCall 1 month ago ↶
1742
if self .find_packed ( & r) .is_some ( ) | | self .backend.has ( & loose_key ( & r) ) .unwrap_or ( false ) {
ff0af1ee unknown 1 month ago
1743
return Ok ( r) ;
1744
}
8f10a07a Andy McCall 1 month ago ↶
1745
if self .pending.borrow ( ) .is_some ( ) {
1746
self .put_pending ( r, ty, body) ? ;
1747
return Ok ( r) ;
1748
}
1749
self .put_loose ( ty, body) ? ;
1750
Ok ( r)
1751
}
1752
64818938 Andy McCall 1 month ago ↶
1753
8f10a07a Andy McCall 1 month ago ↶
1754
fn put_loose ( & self , ty : ObjectType, body : & [u8 ]) -> Result< ObjectRef> {
1755
let r = hash_object ( ty, body) ;
64818938 Andy McCall 1 month ago ↶
1756
let mut bytes = header ( ty, body.len ( ) ) ;
1757
bytes.extend_from_slice ( body) ;
4dcb8c09 Andy McCall 1 month ago ↶
1758
crate :: durable:: step( " write loose object" ) ? ;
64818938 Andy McCall 1 month ago ↶
1759
put_new_or_existing ( self .backend.as_ref ( ) , & loose_key ( & r) , & bytes) ? ;
ff0af1ee unknown 1 month ago
1760
Ok ( r)
b30a880f Andy McCall 1 month ago ↶
1761
}
1762
1763
64818938 Andy McCall 1 month ago ↶
1764
1765
1766
b30a880f Andy McCall 1 month ago ↶
1767
fn put_loose_many ( & self , objects : & [( ObjectType , &[u8 ]) ]) -> Result< ( ) > {
1768
if objects.len ( ) < = 1 {
1769
for ( ty, body) in objects {
1770
self .put_loose ( * ty, body) ? ;
1771
}
1772
return Ok ( ( ) ) ;
1773
}
1774
let mut seen = std:: collections:: HashSet:: new( ) ;
64818938 Andy McCall 1 month ago ↶
1775
let items: Vec< ( String, Vec< u8 > ) > = objects
b30a880f Andy McCall 1 month ago ↶
1776
.iter ( )
1777
.filter_map ( | ( ty , body ) | {
1778
let r = hash_object ( * ty, body) ;
64818938 Andy McCall 1 month ago ↶
1779
seen.insert ( r) .then ( | | {
1780
let mut bytes = header ( * ty, body.len ( ) ) ;
1781
bytes.extend_from_slice ( body) ;
1782
( loose_key ( & r) , bytes)
b30a880f Andy McCall 1 month ago ↶
1783
} )
1784
} )
1785
.collect ( ) ;
64818938 Andy McCall 1 month ago ↶
1786
self .backend.put_many_new ( & items) .map_err ( backend_err)
ff0af1ee unknown 1 month ago
1787
}
1788
09245702 Andy McCall 19 days ago ↶
1789
1790
1791
1792
767ac6cd Andy McCall 17 days ago
1793
1794
1795
1796
1797
1798
64818938 Andy McCall 1 month ago ↶
1799
pub fn get ( & self , r : & ObjectRef) -> Result< Object> {
767ac6cd Andy McCall 17 days ago
1800
match self .get_now ( r) {
1801
Err ( e) if is_miss ( & e) => {
1802
1803
let packed_miss =
1804
! matches! ( e, StoreError:: NotFound( _ ) ) | | self .find_packed ( r) .is_some ( ) ;
1805
let changed = if packed_miss {
1806
self .reload_packs ( ) ? ;
1807
true
1808
} else {
1809
self .reload_if_changed ( ) ?
1810
} ;
1811
if changed {
1812
self .get_now ( r)
1813
} else {
1814
Err ( e)
1815
}
1816
}
1817
other => other,
1818
}
1819
}
1820
1821
1822
fn get_now ( & self , r : & ObjectRef) -> Result< Object> {
09245702 Andy McCall 19 days ago ↶
1823
if let Some ( ( i, e) ) = self .find_packed ( r) {
767ac6cd Andy McCall 17 days ago
1824
let pack = self .packs.borrow ( ) [ i] .clone ( ) ;
1825
return pack.fetch ( self .backend.as_ref ( ) , r, e) ;
09245702 Andy McCall 19 days ago ↶
1826
}
64818938 Andy McCall 1 month ago ↶
1827
match get_optional ( self .backend.as_ref ( ) , & loose_key ( r) ) ? {
1828
Some ( bytes) => parse_loose ( & bytes, r) ,
09245702 Andy McCall 19 days ago ↶
1829
None => self .pending_get ( r) .unwrap_or ( Err ( StoreError:: NotFound( * r) ) ) ,
afaba5f1 Andy McCall 1 month ago ↶
1830
}
1831
}
1832
09245702 Andy McCall 19 days ago ↶
1833
1834
1835
767ac6cd Andy McCall 17 days ago
1836
1837
afaba5f1 Andy McCall 1 month ago ↶
1838
pub fn get_many ( & self , refs : & [ObjectRef]) -> Vec< Result< Object> > {
767ac6cd Andy McCall 17 days ago
1839
let mut out = self .get_many_now ( refs) ;
1840
let missed: Vec< usize > = out
1841
.iter ( )
1842
.enumerate ( )
1843
.filter ( | ( _, g ) | g.as_ref ( ) .is_err_and ( is_miss) )
1844
.map ( | ( i , _) | i )
1845
.collect ( ) ;
1846
if missed.is_empty ( ) {
1847
return out;
1848
}
1849
let packed_miss = missed.iter ( ) .any ( | i | {
1850
! matches! ( out[ * i] , Err ( StoreError:: NotFound( _ ) ) )
1851
| | self .find_packed ( & refs[ * i] ) .is_some ( )
1852
} ) ;
1853
let changed = if packed_miss {
1854
self .reload_packs ( ) .map ( | _| true )
1855
} else {
1856
self .reload_if_changed ( )
1857
} ;
1858
match changed {
1859
Ok ( true ) => {
1860
let again: Vec< ObjectRef> = missed.iter ( ) .map ( | i | refs[ * i] ) .collect ( ) ;
1861
for ( i, g) in missed.into_iter ( ) .zip ( self .get_many_now ( & again) ) {
1862
out[ i] = g;
1863
}
1864
}
1865
Ok ( false ) => { }
1866
Err ( e) => {
1867
let why = e.to_string ( ) ;
1868
for i in missed {
1869
out[ i] = Err ( StoreError:: Io( io:: Error:: other( why.clone ( ) ) ) ) ;
1870
}
1871
}
1872
}
1873
out
1874
}
1875
1876
1877
fn get_many_now ( & self , refs : & [ObjectRef]) -> Vec< Result< Object> > {
afaba5f1 Andy McCall 1 month ago ↶
1878
use rayon:: prelude:: * ;
64818938 Andy McCall 1 month ago ↶
1879
let backend = self .backend.as_ref ( ) ;
afaba5f1 Andy McCall 1 month ago ↶
1880
let packs = self .packs.borrow ( ) ;
09245702 Andy McCall 19 days ago ↶
1881
let place: Vec< Option< ( usize , PackEntry) > > = refs
75167672 Andy McCall 1 month ago
1882
.iter ( )
09245702 Andy McCall 19 days ago ↶
1883
.map ( | r | {
afaba5f1 Andy McCall 1 month ago ↶
1884
packs
1885
.iter ( )
1886
.enumerate ( )
09245702 Andy McCall 19 days ago ↶
1887
.find_map ( | ( p , pack ) | pack.find ( r) .map ( | e | ( p, e) ) )
afaba5f1 Andy McCall 1 month ago ↶
1888
} )
1889
.collect ( ) ;
767ac6cd Andy McCall 17 days ago
1890
let indexes: & [ Arc< PackIndex> ] = & packs;
09245702 Andy McCall 19 days ago ↶
1891
let found: Vec< Option< Result< Object> > > = refs
afaba5f1 Andy McCall 1 month ago ↶
1892
.par_iter ( )
09245702 Andy McCall 19 days ago ↶
1893
.zip ( place.par_iter ( ) )
1894
.map ( | ( r , at ) | match at {
1895
Some ( ( p, e) ) => Some ( indexes[ * p] .fetch ( backend, r, * e) ) ,
1896
None => match get_optional ( backend, & loose_key ( r) ) {
1897
Ok ( Some ( bytes) ) => Some ( parse_loose ( & bytes, r) ) ,
1898
Ok ( None ) => None ,
1899
Err ( e) => Some ( Err ( e) ) ,
1900
} ,
1901
} )
afaba5f1 Andy McCall 1 month ago ↶
1902
.collect ( ) ;
1903
drop ( packs) ;
1904
found
1905
.into_iter ( )
1906
.zip ( refs)
09245702 Andy McCall 19 days ago ↶
1907
.map ( | ( f , r ) | {
1908
f.unwrap_or_else ( | | self .pending_get ( r) .unwrap_or ( Err ( StoreError:: NotFound( * r) ) ) )
afaba5f1 Andy McCall 1 month ago ↶
1909
} )
1910
.collect ( )
ff0af1ee unknown 1 month ago
1911
}
1912
1913
pub fn get_typed ( & self , r : & ObjectRef, want : ObjectType) -> Result< Vec< u8 > > {
1914
let ( ty, body) = self .get ( r) ? ;
1915
if ty ! = want {
1916
return Err ( StoreError:: WrongType( * r, ty.name ( ) , want.name ( ) ) ) ;
1917
}
1918
Ok ( body)
1919
}
1920
6f8aeb99 Andy McCall 1 month ago ↶
1921
1922
ff0af1ee unknown 1 month ago
1923
pub fn put_change ( & self , c : & Change) -> Result< ObjectRef> {
5b4c5130 Andy McCall 1 month ago ↶
1924
let encoding = crate :: timing:: phase( " store: encode the change and its texts" ) ;
17f94b13 Andy McCall 1 month ago ↶
1925
let bytes = c.encode_streaming ( | batch | self .put_texts ( & batch) ) ? ;
5b4c5130 Andy McCall 1 month ago ↶
1926
drop ( encoding) ;
1927
let _t = crate :: timing:: phase( " store: put the encoding" ) ;
17f94b13 Andy McCall 1 month ago ↶
1928
self .put ( ObjectType:: Change, & bytes)
6f8aeb99 Andy McCall 1 month ago ↶
1929
}
1930
17f94b13 Andy McCall 1 month ago ↶
1931
1932
1933
pub fn put_texts ( & self , texts : & [crate:: objects:: StoredText]) -> Result< ( ) > {
192fad1e Andy McCall 1 month ago ↶
1934
let mut chunks: Vec< ( ObjectType, & [u8 ]) > = Vec :: new( ) ;
1935
for t in texts {
1936
if ! self .has ( & t.blob.hash ( ) ) {
1937
chunks.extend (
1938
crate :: chunk:: chunks( & t.content)
1939
.into_iter ( )
1940
.map ( | c | ( ObjectType:: Chunk, c) ) ,
1941
) ;
1942
}
6f8aeb99 Andy McCall 1 month ago ↶
1943
}
192fad1e Andy McCall 1 month ago ↶
1944
self .put_many ( & chunks) ? ;
1945
for t in texts {
1946
self .put ( ObjectType:: Blob, & t.blob.encode ( ) ) ? ;
6f8aeb99 Andy McCall 1 month ago ↶
1947
}
17f94b13 Andy McCall 1 month ago ↶
1948
Ok ( ( ) )
ff0af1ee unknown 1 month ago
1949
}
1950
1951
pub fn get_change ( & self , r : & ObjectRef) -> Result< Change> {
6f8aeb99 Andy McCall 1 month ago ↶
1952
Ok ( self .get_change_parts ( r) ? .0 )
1953
}
1954
1955
1956
1957
pub fn get_change_parts ( & self , r : & ObjectRef) -> Result< ( Change, Vec< ObjectRef> ) > {
1958
let bytes = self .get_typed ( r, ObjectType:: Change) ? ;
1959
let mut parts = Vec :: new( ) ;
1960
let mut failed = None ;
0f93f49c Andy McCall 1 month ago ↶
1961
let decoded = Change:: decode_with( & bytes, & mut | text, count, form| match self
1962
.read_text ( text)
1963
{
6f8aeb99 Andy McCall 1 month ago ↶
1964
Ok ( ( blob, content) ) => {
1965
parts.push ( * text) ;
1966
parts.extend ( blob.chunks) ;
0f93f49c Andy McCall 1 month ago ↶
1967
crate :: objects:: text_lines( & content, count, form)
6f8aeb99 Andy McCall 1 month ago ↶
1968
}
1969
Err ( e) => {
1970
let why = e.to_string ( ) ;
1971
failed = Some ( e) ;
1972
Err ( ObjectError:: Schema( format! (
1973
" text blob {} : {why} " ,
1974
text.short ( 12 )
1975
) ) )
1976
}
1977
} ) ;
1978
match ( decoded, failed) {
1979
( Ok ( c) , _ ) => Ok ( ( c, parts) ) ,
1980
( Err ( _ ) , Some ( StoreError:: NotFound( t) ) ) => Err ( StoreError:: Corrupt(
1981
* r,
1982
format! ( " its text blob {} is missing" , t.short ( 12 ) ) ,
1983
) ) ,
1984
( Err ( e) , _ ) => Err ( StoreError:: Corrupt( * r, e.to_string ( ) ) ) ,
1985
}
1986
}
1987
a4fad5b0 Andy McCall 1 month ago ↶
1988
1989
1990
1991
1992
pub fn get_change_lazy ( & self , r : & ObjectRef) -> Result< ( Change, Vec< crate:: objects:: TextRef> ) > {
86e1824f Andy McCall 1 month ago ↶
1993
let bytes = self .get_typed ( r, ObjectType:: Change) ? ;
a4fad5b0 Andy McCall 1 month ago ↶
1994
Change:: decode_skeleton( & bytes, * r) .map_err ( | e | StoreError:: Corrupt( * r, e.to_string ( ) ) )
86e1824f Andy McCall 1 month ago ↶
1995
}
1996
69816d68 Andy McCall 1 month ago ↶
1997
1998
1999
ce14f0d6 Andy McCall 1 month ago ↶
2000
2001
2002
2003
69816d68 Andy McCall 1 month ago ↶
2004
pub fn get_change_meta ( & self , r : & ObjectRef) -> Result< crate:: state:: ChangeMeta> {
ce14f0d6 Andy McCall 1 month ago ↶
2005
if self .metas.borrow ( ) .is_none ( ) {
2006
* self .metas.borrow_mut ( ) = Some ( self .read_metas_cache ( ) ) ;
2007
}
2008
let cached = self .metas.borrow ( ) .as_ref ( ) .and_then ( | m | m.get ( r) .cloned ( ) ) ;
2009
if let Some ( meta) = cached {
2010
if self .has ( r) {
2011
# [ cfg ( test ) ]
2012
assert_eq! (
2013
meta,
2014
Change:: decode_meta( & self .get_typed ( r, ObjectType:: Change) ? ) .unwrap ( ) ,
2015
" the metadata cache holds a change's metadata"
2016
) ;
2017
return Ok ( meta) ;
2018
}
2019
}
4d6c9c1b Andy McCall 1 month ago ↶
2020
let bytes = self .get_typed ( r, ObjectType:: Change) ? ;
ce14f0d6 Andy McCall 1 month ago ↶
2021
let meta =
2022
Change:: decode_meta( & bytes) .map_err ( | e | StoreError:: Corrupt( * r, e.to_string ( ) ) ) ? ;
2023
self .remember_meta ( r, & meta) ;
2024
Ok ( meta)
2025
}
2026
2027
2028
2029
64818938 Andy McCall 1 month ago ↶
2030
2031
ce14f0d6 Andy McCall 1 month ago ↶
2032
fn read_metas_cache ( & self ) -> crate:: fasthash:: FastMap< ObjectRef, crate:: state:: ChangeMeta> {
2033
let mut out = crate :: fasthash:: FastMap:: default( ) ;
64818938 Andy McCall 1 month ago ↶
2034
let Ok ( bytes) = fs:: read( self .scratch.join ( " metas" ) ) else {
ce14f0d6 Andy McCall 1 month ago ↶
2035
return out;
2036
} ;
2037
let mut r = crate :: flat:: Reader:: new( & bytes) ;
2038
let mut good = 0 ;
2039
while ! r.at_end ( ) {
2040
let mut record = | | -> std:: result:: Result< _ , ObjectError> {
2041
let h = r.object ( ) ? ;
2042
let body = r.bytes ( ) ? ;
2043
let check = r.fixed:: < 8> ( ) ? ;
2044
Ok ( ( h, body, check) )
2045
} ;
2046
let Ok ( ( h, body, check) ) = record ( ) else {
2047
break ;
2048
} ;
2049
let mut sum = blake3:: Hasher:: new( ) ;
2050
sum.update ( & h.0 ) .update ( body) ;
2051
if sum.finalize ( ) .as_bytes ( ) [ .. 8 ] ! = check {
2052
break ;
2053
}
2054
match crate :: state:: ChangeMeta:: read_flat( & mut crate :: flat:: Reader:: new( body) ) {
2055
Ok ( m) => out.insert ( h, m) ,
2056
Err ( _ ) => break ,
2057
} ;
2058
good + = 32 + 4 + body.len ( ) + 8 ;
2059
}
2060
2061
if good < bytes.len ( ) {
2062
let _ = fs:: OpenOptions:: new( )
2063
.write ( true )
64818938 Andy McCall 1 month ago ↶
2064
.open ( self .scratch.join ( " metas" ) )
ce14f0d6 Andy McCall 1 month ago ↶
2065
.and_then ( | f | f.set_len ( good as u64 ) ) ;
2066
}
2067
out
2068
}
2069
2070
2071
2072
fn remember_meta ( & self , r : & ObjectRef, meta : & crate:: state:: ChangeMeta) {
2073
let mut body = crate :: flat:: Writer:: default( ) ;
2074
meta.write_flat ( & mut body) ;
2075
let mut w = crate :: flat:: Writer:: default( ) ;
2076
w.object ( r) ;
2077
w.bytes ( & body.0 ) ;
2078
let mut sum = blake3:: Hasher:: new( ) ;
2079
sum.update ( & r.0 ) .update ( & body.0 ) ;
2080
w.fixed ( & sum.finalize ( ) .as_bytes ( ) [ .. 8 ] ) ;
2081
let _ = fs:: OpenOptions:: new( )
2082
.create ( true )
2083
.append ( true )
64818938 Andy McCall 1 month ago ↶
2084
.open ( self .scratch.join ( " metas" ) )
ce14f0d6 Andy McCall 1 month ago ↶
2085
.and_then ( | mut f | f.write_all ( & w.0 ) ) ;
2086
if let Some ( m) = self .metas.borrow_mut ( ) .as_mut ( ) {
2087
m.insert ( * r, meta.clone ( ) ) ;
2088
}
69816d68 Andy McCall 1 month ago ↶
2089
}
2090
6f8aeb99 Andy McCall 1 month ago ↶
2091
fn read_text ( & self , r : & ObjectRef) -> Result< ( Blob, Vec< u8 > ) > {
2092
let blob = Blob:: decode( & self .get_typed ( r, ObjectType:: Blob) ? ) ? ;
2093
let mut content = Vec :: with_capacity( blob.length as usize ) ;
2094
for c in & blob.chunks {
2095
content.extend ( self .get_typed ( c, ObjectType:: Chunk) ? ) ;
2096
}
2097
Ok ( ( blob, content) )
ff0af1ee unknown 1 month ago
2098
}
2099
2100
pub fn put_chunk ( & self , bytes : & [u8 ]) -> Result< ObjectRef> {
2101
self .put ( ObjectType:: Chunk, bytes)
2102
}
2103
cdb5beba Andy McCall 1 month ago ↶
2104
2105
pub fn put_chunk_nocompress ( & self , bytes : & [u8 ]) -> Result< ObjectRef> {
8f10a07a Andy McCall 1 month ago ↶
2106
let r = hash_object ( ObjectType:: Chunk, bytes) ;
64818938 Andy McCall 1 month ago ↶
2107
put_new_or_existing (
2108
self .backend.as_ref ( ) ,
2109
& format! ( " nocompress/{} " , r.to_hex ( ) ) ,
2110
b " " ,
2111
) ? ;
8f10a07a Andy McCall 1 month ago ↶
2112
self .put ( ObjectType:: Chunk, bytes)
cdb5beba Andy McCall 1 month ago ↶
2113
}
2114
2115
fn is_nocompress ( & self , r : & ObjectRef) -> bool {
64818938 Andy McCall 1 month ago ↶
2116
self .backend
2117
.has ( & format! ( " nocompress/{} " , r.to_hex ( ) ) )
2118
.unwrap_or ( false )
2119
}
2120
2121
2122
fn nocompress_set ( & self ) -> Result< std:: collections:: HashSet< ObjectRef> > {
2123
Ok ( self
2124
.backend
2125
.list ( " nocompress/" )
2126
.map_err ( backend_err) ?
2127
.into_iter ( )
2128
.filter_map ( | e | ObjectRef:: from_hex( e.key.trim_start_matches ( " nocompress/" ) ) )
2129
.collect ( ) )
cdb5beba Andy McCall 1 month ago ↶
2130
}
2131
86e682c2 Andy McCall 1 month ago ↶
2132
pub fn put_state ( & self , st : & StateObject) -> Result< ObjectRef> {
2133
self .put ( ObjectType:: State, & st.encode ( ) )
2134
}
2135
2136
pub fn get_state ( & self , r : & ObjectRef) -> Result< StateObject> {
2137
Ok ( StateObject:: decode( & self .get_typed ( r, ObjectType:: State) ? ) ? )
2138
}
2139
5b9c6ad4 Andy McCall 1 month ago ↶
2140
pub fn put_attest ( & self , a : & Attest) -> Result< ObjectRef> {
2141
self .put ( ObjectType:: Attest, & a.encode ( ) )
2142
}
2143
2144
pub fn get_attest ( & self , r : & ObjectRef) -> Result< Attest> {
2145
Ok ( Attest:: decode( & self .get_typed ( r, ObjectType:: Attest) ? ) ? )
fc1a466a Andy McCall 1 month ago ↶
2146
}
2147
2148
pub fn put_receipt ( & self , r : & Receipt) -> Result< ObjectRef> {
2149
self .put ( ObjectType:: Receipt, & r.encode ( ) )
5b9c6ad4 Andy McCall 1 month ago ↶
2150
}
2151
fc1a466a Andy McCall 1 month ago ↶
2152
pub fn get_receipt ( & self , r : & ObjectRef) -> Result< Receipt> {
2153
Ok ( Receipt:: decode( & self .get_typed ( r, ObjectType:: Receipt) ? ) ? )
5b9c6ad4 Andy McCall 1 month ago ↶
2154
}
2155
64818938 Andy McCall 1 month ago ↶
2156
2157
2158
fn index_add ( & self , index : & str , key : & ObjectRef, value : & ObjectRef) -> Result< ( ) > {
ef7d4ea6 Andy McCall 16 days ago ↶
2159
debug_assert! ( ENTRY_INDEXES .iter ( ) .any ( | ( i , _) | * i = = index) ) ;
64818938 Andy McCall 1 month ago ↶
2160
let entry = format! ( " {} {} " , fanout_prefix ( index, key) , value.to_hex ( ) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2161
put_new_or_existing ( self .backend.as_ref ( ) , & entry, b " " ) ? ;
2162
self .journal_add ( entry)
fc1a466a Andy McCall 1 month ago ↶
2163
}
2164
64818938 Andy McCall 1 month ago ↶
2165
2166
2167
fn index_get ( & self , index : & str , legacy : & str , key : & ObjectRef) -> Result< Vec< ObjectRef> > {
2168
let mut values: Vec< ObjectRef> = self
ef7d4ea6 Andy McCall 16 days ago ↶
2169
.entry_keys ( & fanout_prefix ( index, key) ) ?
64818938 Andy McCall 1 month ago ↶
2170
.into_iter ( )
ef7d4ea6 Andy McCall 16 days ago ↶
2171
.filter_map ( | k | k.rsplit ( ' /' ) .next ( ) .and_then ( ObjectRef:: from_hex) )
64818938 Andy McCall 1 month ago ↶
2172
.collect ( ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2173
if ! self .reads_legacy ( ) {
2174
2175
} else if let Some ( bytes) = get_optional ( self .backend.as_ref ( ) , & legacy_key ( legacy, key) ) ? {
64818938 Andy McCall 1 month ago ↶
2176
values.extend (
2177
String :: from_utf8_lossy( & bytes)
2178
.lines ( )
2179
.filter_map ( ObjectRef:: from_hex) ,
2180
) ;
5b9c6ad4 Andy McCall 1 month ago ↶
2181
}
fc1a466a Andy McCall 1 month ago ↶
2182
values.sort ( ) ;
64818938 Andy McCall 1 month ago ↶
2183
values.dedup ( ) ;
2184
Ok ( values)
5b9c6ad4 Andy McCall 1 month ago ↶
2185
}
2186
fc1a466a Andy McCall 1 month ago ↶
2187
2188
pub fn index_seal ( & self , change : & ObjectRef, attest : & ObjectRef) -> Result< ( ) > {
64818938 Andy McCall 1 month ago ↶
2189
self .index_add ( " seal" , change, attest)
fc1a466a Andy McCall 1 month ago ↶
2190
}
2191
2192
2193
pub fn seals_for ( & self , change : & ObjectRef) -> Result< Vec< ObjectRef> > {
64818938 Andy McCall 1 month ago ↶
2194
self .index_get ( " seal" , " seals" , change)
fc1a466a Andy McCall 1 month ago ↶
2195
}
2196
2197
c63fed2e Andy McCall 18 days ago ↶
2198
2199
2200
pub fn put_certificate ( & self , c : & crate:: cert:: SignedCertificate) -> Result< ObjectRef> {
2201
let r = self .put ( ObjectType:: Certificate, & c.cert.encode ( ) ) ? ;
2202
self .put_signature ( & r, & c.sig) ? ;
2203
self .index_add ( " cert" , & c.cert.key_id ( ) , & r) ? ;
2204
Ok ( r)
2205
}
2206
2207
2208
pub fn get_certificate ( & self , r : & ObjectRef) -> Result< crate:: cert:: SignedCertificate> {
2209
let cert = crate :: cert:: Certificate:: decode( & self .get_typed ( r, ObjectType:: Certificate) ? ) ? ;
2210
let sig = self
2211
.signatures ( r) ?
2212
.into_iter ( )
2213
.find ( | s | s.key = = cert.issuer )
2214
.ok_or ( StoreError:: NotFound( * r) ) ? ;
2215
Ok ( crate :: cert:: SignedCertificate { cert, sig } )
2216
}
2217
2218
2219
pub fn certificate_of ( & self , key : & ObjectRef) -> Result< Option< ObjectRef> > {
2220
Ok ( self
2221
.index_get ( " cert" , " certs" , key) ?
2222
.into_iter ( )
2223
.find ( | r | self .has ( r) ) )
2224
}
2225
f53cbe7a Andy McCall 18 days ago ↶
2226
2227
pub ( crate ) fn index_add_pub (
2228
& self ,
2229
index : & str ,
2230
key : & ObjectRef,
2231
value : & ObjectRef,
2232
) -> Result< ( ) > {
2233
self .index_add ( index, key, value)
2234
}
2235
2236
2237
2238
pub ( crate ) fn index_get_pub ( & self , index : & str , key : & ObjectRef) -> Result< Vec< ObjectRef> > {
2239
self .index_get ( index, & format! ( " {index} -lists" ) , key)
2240
}
2241
fc1a466a Andy McCall 1 month ago ↶
2242
pub fn index_receipt ( & self , state : & ObjectRef, attest : & ObjectRef) -> Result< ( ) > {
64818938 Andy McCall 1 month ago ↶
2243
self .index_add ( " receipt" , state, attest)
fc1a466a Andy McCall 1 month ago ↶
2244
}
2245
2246
2247
pub fn receipts_for ( & self , state : & ObjectRef) -> Result< Vec< ObjectRef> > {
64818938 Andy McCall 1 month ago ↶
2248
self .index_get ( " receipt" , " receipts" , state)
fc1a466a Andy McCall 1 month ago ↶
2249
}
2250
3a4b3e01 Andy McCall 19 days ago ↶
2251
pub fn index_approval ( & self , state : & ObjectRef, attest : & ObjectRef) -> Result< ( ) > {
2252
self .index_add ( " approval" , state, attest)
2253
}
2254
2255
2256
2257
pub fn approvals_for ( & self , state : & ObjectRef) -> Result< Vec< ObjectRef> > {
2258
self .index_get ( " approval" , " approvals" , state)
2259
}
2260
2261
2262
pub fn approval_states ( & self ) -> Result< Vec< ObjectRef> > {
2263
self .indexed_states ( " approval" , " approvals" )
2264
}
2265
fc1a466a Andy McCall 1 month ago ↶
2266
2267
pub fn receipt_states ( & self ) -> Result< Vec< ObjectRef> > {
3a4b3e01 Andy McCall 19 days ago ↶
2268
self .indexed_states ( " receipt" , " receipts" )
2269
}
2270
2271
2272
2273
fn indexed_states ( & self , one : & str , many : & str ) -> Result< Vec< ObjectRef> > {
64818938 Andy McCall 1 month ago ↶
2274
let mut out: Vec< ObjectRef> = Vec :: new( ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2275
for key in self .entry_keys ( & format! ( " {one} /" ) ) ? {
64818938 Andy McCall 1 month ago ↶
2276
ef7d4ea6 Andy McCall 16 days ago ↶
2277
let mut parts = key.splitn ( 4 , ' /' ) ;
64818938 Andy McCall 1 month ago ↶
2278
let ( Some ( _ ) , Some ( hh) , Some ( rest) , Some ( _ ) ) =
2279
( parts.next ( ) , parts.next ( ) , parts.next ( ) , parts.next ( ) )
2280
else {
2281
continue ;
2282
} ;
2283
out.extend ( ObjectRef:: from_hex( & format! ( " {hh} {rest} " ) ) ) ;
fc1a466a Andy McCall 1 month ago ↶
2284
}
ef7d4ea6 Andy McCall 16 days ago ↶
2285
let legacy = if self .reads_legacy ( ) {
2286
self .backend
2287
.list ( & format! ( " {many} /" ) )
2288
.map_err ( backend_err) ?
2289
} else {
2290
Vec :: new( )
2291
} ;
2292
for e in legacy {
64818938 Andy McCall 1 month ago ↶
2293
let mut parts = e.key.splitn ( 3 , ' /' ) ;
2294
let ( Some ( _ ) , Some ( hh) , Some ( rest) ) = ( parts.next ( ) , parts.next ( ) , parts.next ( ) ) else {
2295
continue ;
2296
} ;
2297
out.extend ( ObjectRef:: from_hex( & format! ( " {hh} {rest} " ) ) ) ;
2298
}
fc1a466a Andy McCall 1 month ago ↶
2299
out.sort ( ) ;
64818938 Andy McCall 1 month ago ↶
2300
out.dedup ( ) ;
fc1a466a Andy McCall 1 month ago ↶
2301
Ok ( out)
5b9c6ad4 Andy McCall 1 month ago ↶
2302
}
2303
1983686f Andy McCall 1 month ago ↶
2304
pub fn put_identity ( & self , id : & Identity) -> Result< ObjectRef> {
2305
self .put ( ObjectType:: Identity, & id.encode ( ) )
2306
}
2307
2308
pub fn get_identity ( & self , r : & ObjectRef) -> Result< Identity> {
2309
Ok ( Identity:: decode( & self .get_typed ( r, ObjectType:: Identity) ? ) ? )
2310
}
2311
64818938 Andy McCall 1 month ago ↶
2312
2313
1983686f Andy McCall 1 month ago ↶
2314
pub fn signatures ( & self , r : & ObjectRef) -> Result< Vec< Signature> > {
64818938 Andy McCall 1 month ago ↶
2315
let mut sigs: Vec< Signature> = Vec :: new( ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2316
for key in self .entry_keys ( & fanout_prefix ( " sig" , r) ) ? {
2317
2318
2319
2320
let Some ( bytes) = get_optional ( self .backend.as_ref ( ) , & key) ? else {
2321
continue ;
2322
} ;
64818938 Andy McCall 1 month ago ↶
2323
sigs.extend ( Signature:: decode_list( & bytes) ? ) ;
1983686f Andy McCall 1 month ago ↶
2324
}
64818938 Andy McCall 1 month ago ↶
2325
2326
ef7d4ea6 Andy McCall 16 days ago ↶
2327
let legacy = if self .reads_legacy ( ) {
2328
get_optional ( self .backend.as_ref ( ) , & legacy_key ( " sigs" , r) ) ?
2329
} else {
2330
None
2331
} ;
2332
if let Some ( bytes) = legacy {
64818938 Andy McCall 1 month ago ↶
2333
for sig in Signature:: decode_list( & bytes) ? {
2334
if ! sigs.iter ( ) .any ( | s | s.key = = sig.key ) {
2335
sigs.push ( sig) ;
2336
}
2337
}
2338
}
2339
sigs.sort_by_key ( | s | s.key ) ;
2340
sigs.dedup_by_key ( | s | s.key ) ;
2341
Ok ( sigs)
1983686f Andy McCall 1 month ago ↶
2342
}
2343
64818938 Andy McCall 1 month ago ↶
2344
2345
2346
1983686f Andy McCall 1 month ago ↶
2347
pub fn put_signature ( & self , r : & ObjectRef, sig : & Signature) -> Result< ( ) > {
64818938 Andy McCall 1 month ago ↶
2348
let key = format! ( " {} {} " , fanout_prefix ( " sig" , r) , sig.key.to_hex ( ) ) ;
2349
let bytes = Signature:: encode_list( std:: slice:: from_ref( sig) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2350
if get_optional ( self .backend.as_ref ( ) , & key) ? .as_deref ( ) ! = Some ( bytes.as_slice ( ) ) {
2351
delete ( self .backend.as_ref ( ) , & key) ? ;
2352
put_new_or_existing ( self .backend.as_ref ( ) , & key, & bytes) ? ;
2353
}
2354
2355
2356
self .journal_add ( key)
2357
}
2358
2359
2360
8156967b Andy McCall 16 days ago ↶
2361
2362
2363
ef7d4ea6 Andy McCall 16 days ago ↶
2364
fn reads_legacy ( & self ) -> bool {
8156967b Andy McCall 16 days ago ↶
2365
! self .legacy_folded.get ( )
ef7d4ea6 Andy McCall 16 days ago ↶
2366
}
2367
8156967b Andy McCall 16 days ago ↶
2368
2369
2370
2371
2372
2373
fn fold_legacy ( & self , progress : Progress) -> Result< ( ) > {
2374
let mut copied = 0 usize ;
2375
for ( index, legacy) in ENTRY_INDEXES {
2376
for e in self
2377
.backend
2378
.list ( & format! ( " {legacy} /" ) )
2379
.map_err ( backend_err) ?
2380
{
2381
2382
let mut parts = e.key.splitn ( 3 , ' /' ) ;
2383
let ( Some ( _ ) , Some ( hh) , Some ( rest) ) = ( parts.next ( ) , parts.next ( ) , parts.next ( ) )
2384
else {
2385
continue ;
2386
} ;
2387
let Some ( r) = ObjectRef:: from_hex( & format! ( " {hh} {rest} " ) ) else {
2388
continue ;
2389
} ;
2390
let Some ( bytes) = get_optional ( self .backend.as_ref ( ) , & e.key) ? else {
2391
continue ;
2392
} ;
2393
if index = = " sig" {
2394
let Ok ( sigs) = Signature:: decode_list( & bytes) else {
2395
progress ( & format! ( " {} : not a list of signatures, passed over" , e.key) ) ;
2396
continue ;
2397
} ;
2398
for sig in sigs {
2399
let key = format! ( " {} {} " , fanout_prefix ( " sig" , & r) , sig.key.to_hex ( ) ) ;
2400
let one = Signature:: encode_list( std:: slice:: from_ref( & sig) ) ;
2401
put_new_or_existing ( self .backend.as_ref ( ) , & key, & one) ? ;
2402
copied + = 1 ;
2403
}
2404
} else {
2405
for v in String :: from_utf8_lossy( & bytes)
2406
.lines ( )
2407
.filter_map ( ObjectRef:: from_hex)
2408
{
2409
let key = format! ( " {} {} " , fanout_prefix ( index, & r) , v.to_hex ( ) ) ;
2410
put_new_or_existing ( self .backend.as_ref ( ) , & key, b " " ) ? ;
2411
copied + = 1 ;
2412
}
2413
}
2414
}
2415
}
2416
if copied > 0 {
2417
progress ( & format! ( " {copied} entries copied out of older lists" ) ) ;
2418
}
2419
put_new_or_existing (
2420
self .backend.as_ref ( ) ,
2421
LEGACY_FOLDED_KEY ,
2422
format! ( " {} \n " , now_ms ( ) ) .as_bytes ( ) ,
2423
) ? ;
2424
self .legacy_folded.set ( true ) ;
2425
Ok ( ( ) )
2426
}
2427
ef7d4ea6 Andy McCall 16 days ago ↶
2428
2429
2430
2431
fn entry_keys ( & self , prefix : & str ) -> Result< Vec< String> > {
2432
if let Some ( keys) = self .with_entries ( | set | {
2433
set.range ( prefix.to_string ( ) .. )
2434
.take_while ( | k | k.starts_with ( prefix) )
2435
.cloned ( )
2436
.collect:: < Vec< String> > ( )
2437
} ) ? {
2438
return Ok ( keys) ;
2439
}
2440
Ok ( self
2441
.backend
2442
.list ( prefix)
2443
.map_err ( backend_err) ?
2444
.into_iter ( )
2445
.map ( | e | e.key )
2446
.collect ( ) )
2447
}
2448
2449
2450
2451
2452
fn with_entries < T> (
2453
& self ,
2454
f : impl FnOnce( &std ::collections ::BTreeSet <String > ) -> T,
2455
) -> Result< Option< T> > {
2456
if self .local | | ! self .folded.get ( ) {
2457
return Ok ( None ) ;
2458
}
771661aa Andy McCall 16 days ago ↶
2459
2460
2461
2462
2463
if self
2464
.entries_read
2465
.get ( )
2466
.is_some_and ( | t | t.elapsed ( ) > = ENTRIES_FRESH )
2467
{
2468
* self .entries.borrow_mut ( ) = None ;
2469
self .reload_if_changed ( ) ? ;
2470
if ! self .folded.get ( ) {
2471
return Ok ( None ) ;
2472
}
2473
}
ef7d4ea6 Andy McCall 16 days ago ↶
2474
if self .entries.borrow ( ) .is_none ( ) {
2475
let Some ( set) = self .read_entries ( ) ? else {
2476
return Ok ( None ) ;
2477
} ;
2478
* self .entries.borrow_mut ( ) = Some ( set) ;
2479
}
2480
Ok ( self .entries.borrow ( ) .as_ref ( ) .map ( f) )
2481
}
2482
2483
2484
2485
2486
2487
2488
fn read_entries ( & self ) -> Result< Option< std:: collections:: BTreeSet< String> > > {
2489
'attempt : for attempt in 0 .. 2 {
2490
if ! self .folded.get ( ) {
2491
return Ok ( None ) ;
2492
}
2493
let mut set = std:: collections:: BTreeSet:: new( ) ;
2494
let lists = self .entry_lists.borrow ( ) .clone ( ) ;
771661aa Andy McCall 16 days ago ↶
2495
self .lists_read
2496
.borrow_mut ( )
2497
.retain ( | k , _| lists.contains ( k) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2498
for key in & lists {
771661aa Andy McCall 16 days ago ↶
2499
let known = self .lists_read.borrow ( ) .get ( key) .cloned ( ) ;
2500
let keys = match known {
2501
Some ( keys) => keys,
2502
None => match get_optional ( self .backend.as_ref ( ) , key) ? {
2503
Some ( bytes) => {
2504
let keys = Arc:: new( decode_entry_list ( key, & bytes) ? ) ;
2505
self .lists_read
2506
.borrow_mut ( )
2507
.insert ( key.clone ( ) , keys.clone ( ) ) ;
2508
keys
2509
}
2510
None if attempt = = 0 => {
2511
self .reload_packs ( ) ? ;
2512
continue 'attempt ;
2513
}
2514
None => return Ok ( None ) ,
2515
} ,
2516
} ;
2517
set.extend ( keys.iter ( ) .cloned ( ) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2518
}
2519
set.extend ( self .read_record ( JOURNAL_KEY ) ? .0. into_keys ( ) ) ;
2520
set.extend ( self .journal_queue.borrow ( ) .iter ( ) .cloned ( ) ) ;
771661aa Andy McCall 16 days ago ↶
2521
self .entries_read.set ( Some ( std:: time:: Instant:: now( ) ) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2522
return Ok ( Some ( set) ) ;
2523
}
2524
Ok ( None )
2525
}
2526
2527
2528
2529
2530
2531
fn journal_add ( & self , key : String) -> Result< ( ) > {
2532
if self .local {
2533
return Ok ( ( ) ) ;
2534
}
2535
if let Some ( set) = self .entries.borrow_mut ( ) .as_mut ( ) {
2536
if ! set.insert ( key.clone ( ) ) {
2537
return Ok ( ( ) ) ;
2538
}
2539
}
2540
if self .batch_depth.get ( ) > 0 {
2541
self .journal_queue.borrow_mut ( ) .push ( key) ;
2542
return Ok ( ( ) ) ;
2543
}
2544
self .journal_append ( std:: slice:: from_ref( & key) )
2545
}
2546
2547
2548
fn flush_journal ( & self ) -> Result< ( ) > {
2549
let queued = std:: mem:: take( & mut * self .journal_queue.borrow_mut ( ) ) ;
2550
self .journal_append ( & queued)
2551
}
2552
2553
2554
2555
2556
fn journal_append ( & self , keys : & [String]) -> Result< ( ) > {
2557
if keys.is_empty ( ) {
64818938 Andy McCall 1 month ago ↶
2558
return Ok ( ( ) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
2559
}
2560
let now = now_ms ( ) ;
2561
let mut unfolded = 0 ;
2562
self .update_record ( JOURNAL_KEY , " the journal of entries" , | m | {
2563
expire_folded ( m, now) ;
2564
for k in keys {
2565
m.entry ( k.clone ( ) ) .or_insert ( 0 ) ;
2566
}
2567
unfolded = m.values ( ) .filter ( | t | * * t = = 0 ) .count ( ) ;
2568
} ) ? ;
2569
if unfolded > JOURNAL_FOLD_AT {
2570
self .fold_journal ( ) ? ;
2571
}
2572
Ok ( ( ) )
2573
}
2574
2575
2576
2577
fn fold_journal ( & self ) -> Result< ( ) > {
2578
let ( journal, _ ) = self .read_record ( JOURNAL_KEY ) ? ;
2579
let keys: Vec< String> = journal
2580
.into_iter ( )
2581
.filter ( | ( _, t ) | * t = = 0 )
2582
.map ( | ( k , _) | k )
2583
.collect ( ) ;
2584
if keys.is_empty ( ) {
2585
return Ok ( ( ) ) ;
2586
}
2587
self .put_entry_list ( PART_SUFFIX , keys.iter ( ) ) ? ;
2588
self .mark_folded ( & keys)
2589
}
2590
2591
2592
2593
fn mark_folded ( & self , keys : & [String]) -> Result< ( ) > {
2594
let now = now_ms ( ) ;
2595
self .update_record ( JOURNAL_KEY , " the journal of entries" , | m | {
2596
expire_folded ( m, now) ;
2597
for k in keys {
2598
if let Some ( t) = m.get_mut ( k) {
2599
if * t = = 0 {
2600
* t = now;
2601
}
2602
}
2603
}
2604
} )
2605
}
2606
2607
2608
2609
fn put_entry_list < 'a > (
2610
& self ,
2611
suffix : & str ,
2612
keys : impl Iterator< Item = & 'a String> ,
2613
) -> Result< String> {
2614
let key = format! ( " pack-{} {suffix} " , fresh_id ( ) ) ;
2615
let bytes = encode_entry_list ( keys) ? ;
2616
self .backend.put_new ( & key, & bytes) .map_err ( backend_err) ? ;
2617
Ok ( key)
2618
}
2619
2620
8156967b Andy McCall 16 days ago ↶
2621
2622
ef7d4ea6 Andy McCall 16 days ago ↶
2623
2624
2625
2626
2627
2628
pub fn fold_entries ( & self , progress : Progress) -> Result< bool > {
2629
if self .local {
2630
return Ok ( false ) ;
1983686f Andy McCall 1 month ago ↶
2631
}
ef7d4ea6 Andy McCall 16 days ago ↶
2632
self .reload_packs ( ) ? ;
8156967b Andy McCall 16 days ago ↶
2633
if ! self .legacy_folded.get ( ) {
2634
progress ( " folding older lists of signatures and index entries" ) ;
2635
self .fold_legacy ( progress) ? ;
2636
}
ef7d4ea6 Andy McCall 16 days ago ↶
2637
let ( journal, _ ) = self .read_record ( JOURNAL_KEY ) ? ;
2638
progress ( " folding signatures and index entries" ) ;
2639
let mut all: std:: collections:: BTreeSet< String> = journal.keys ( ) .cloned ( ) .collect ( ) ;
2640
for ( index, _ ) in ENTRY_INDEXES {
2641
for e in self
2642
.backend
2643
.list ( & format! ( " {index} /" ) )
2644
.map_err ( backend_err) ?
2645
{
2646
all.insert ( e.key) ;
2647
}
2648
}
2649
let lists = self .entry_lists.borrow ( ) .clone ( ) ;
2650
let unfolded: Vec< String> = journal
2651
.iter ( )
2652
.filter ( | ( _, t ) | * * t = = 0 )
2653
.map ( | ( k , _) | k.clone ( ) )
2654
.collect ( ) ;
2655
if unfolded.is_empty ( ) & & lists.len ( ) = = 1 & & lists[ 0 ] .ends_with ( LIST_SUFFIX ) {
2656
if let Some ( bytes) = get_optional ( self .backend.as_ref ( ) , & lists[ 0 ] ) ? {
2657
let held: std:: collections:: BTreeSet< String> =
2658
decode_entry_list ( & lists[ 0 ] , & bytes) ? .into_iter ( ) .collect ( ) ;
2659
if held = = all {
2660
return Ok ( false ) ;
2661
}
2662
}
2663
}
2664
self .put_entry_list ( LIST_SUFFIX , all.iter ( ) ) ? ;
2665
self .retire ( & lists) ? ;
2666
if ! unfolded.is_empty ( ) {
2667
self .mark_folded ( & unfolded) ? ;
2668
}
2669
* self .entries.borrow_mut ( ) = None ;
2670
self .reload_packs ( ) ? ;
2671
Ok ( true )
1983686f Andy McCall 1 month ago ↶
2672
}
2673
54e2e630 Andy McCall 29 days ago ↶
2674
2675
2676
2677
2678
2679
2680
2681
pub fn adopt_unfinished_packs (
2682
& self ,
2683
min_age : std:: time:: Duration,
2684
progress : & dyn Fn( &str ) ,
2685
) -> Result< ( usize , usize ) > {
2686
use std:: io:: { BufReader, Read} ;
2687
let mut packs = 0 ;
2688
let mut objects = 0 ;
2689
let Ok ( dir) = fs:: read_dir( & self .scratch) else {
2690
return Ok ( ( 0 , 0 ) ) ;
2691
} ;
2692
for entry in dir.flatten ( ) {
2693
let name = entry.file_name ( ) .to_string_lossy ( ) .to_string ( ) ;
2694
let Some ( id) = name
2695
.strip_prefix ( " .tmp-" )
2696
.and_then ( | n | n.strip_suffix ( " .pack" ) )
2697
else {
2698
continue ;
2699
} ;
2700
let path = entry.path ( ) ;
2701
let meta = fs:: metadata( & path) ? ;
2702
let age = meta
2703
.modified ( )
2704
.ok ( )
2705
.and_then ( | m | m.elapsed ( ) .ok ( ) )
2706
.unwrap_or_default ( ) ;
2707
if age < min_age {
2708
progress ( & format! (
2709
" {name} : written to {} s ago, left alone" ,
2710
age.as_secs ( )
2711
) ) ;
2712
continue ;
2713
}
2714
let mut f = BufReader:: with_capacity( 1 < < 20 , fs:: File:: open( & path) ? ) ;
2715
let mut magic = [ 0 u8 ; 8 ] ;
2716
if f.read_exact ( & mut magic) .is_err ( ) | | & magic ! = PACK_MAGIC {
2717
progress ( & format! ( " {name} : not a pack, left alone" ) ) ;
2718
continue ;
2719
}
2720
let mut offset = PACK_MAGIC .len ( ) as u64 ;
2721
let mut index: Vec< ( ObjectRef, PackEntry) > = Vec :: new( ) ;
2722
loop {
2723
let mut head = [ 0 u8 ; 42 ] ;
2724
if f.read_exact ( & mut head) .is_err ( ) {
2725
break ;
2726
}
2727
let Some ( ty) = ObjectType:: ALL .get ( head[ 0 ] as usize ) .copied ( ) else {
2728
break ;
2729
} ;
2730
let flags = head[ 1 ] ;
2731
let stored_len = u32 :: from_le_bytes( head[ 2 .. 6 ] .try_into ( ) .unwrap ( ) ) ;
2732
let raw_len = u32 :: from_le_bytes( head[ 6 .. 10 ] .try_into ( ) .unwrap ( ) ) ;
2733
let r = ObjectRef( head[ 10 .. 42 ] .try_into ( ) .unwrap ( ) ) ;
2734
let mut stored = vec! [ 0 u8 ; stored_len as usize ] ;
2735
if flags & FLAG_DICT ! = 0 | | f.read_exact ( & mut stored) .is_err ( ) {
2736
break ;
2737
}
2738
let e = PackEntry {
2739
offset: offset + 42 ,
2740
stored_len,
2741
raw_len,
2742
ty,
2743
flags,
2744
} ;
2745
if decode_entry ( & r, e, stored, None ) .is_err ( ) {
2746
break ;
2747
}
2748
index.push ( ( r, e) ) ;
2749
offset + = 42 + stored_len as u64 ;
2750
if index.len ( ) .is_multiple_of ( 200_000 ) {
2751
progress ( & format! (
2752
" {name} : {} objects checked, {} MiB" ,
2753
index.len ( ) ,
2754
offset > > 20
2755
) ) ;
2756
}
2757
}
2758
if index.is_empty ( ) {
2759
progress ( & format! ( " {name} : no whole object, left alone" ) ) ;
2760
continue ;
2761
}
2762
if offset < meta.len ( ) {
2763
progress ( & format! (
2764
" {name} : {} torn bytes at the end cut off" ,
2765
meta.len ( ) - offset
2766
) ) ;
2767
fs:: OpenOptions:: new( )
2768
.write ( true )
2769
.open ( & path) ?
2770
.set_len ( offset) ? ;
2771
}
2772
index.sort_by_key ( | ( r , _) | * r) ;
2773
index.dedup_by_key ( | ( r , _) | * r) ;
2774
objects + = index.len ( ) ;
2775
packs + = 1 ;
2776
progress ( & format! ( " {name} : {} objects indexed" , index.len ( ) ) ) ;
2777
self .finish_pack_files ( id, & path, & index) ? ;
2778
}
2779
Ok ( ( packs, objects) )
2780
}
2781
d02e545d Andy McCall 1 month ago ↶
2782
ff0af1ee unknown 1 month ago
2783
pub fn list ( & self ) -> io:: Result< Vec< ObjectRef> > {
64818938 Andy McCall 1 month ago ↶
2784
let mut out: Vec< ObjectRef> = self
2785
.loose_objects ( )
2786
.map_err ( | e | io:: Error:: other( e.to_string ( ) ) ) ?
2787
.into_iter ( )
2788
.map ( | ( r , _) | r )
2789
.collect ( ) ;
d02e545d Andy McCall 1 month ago ↶
2790
for p in self .packs.borrow ( ) .iter ( ) {
2791
out.extend ( p.refs.iter ( ) .copied ( ) ) ;
ff0af1ee unknown 1 month ago
2792
}
2793
out.sort ( ) ;
d02e545d Andy McCall 1 month ago ↶
2794
out.dedup ( ) ;
ff0af1ee unknown 1 month ago
2795
Ok ( out)
767ac6cd Andy McCall 17 days ago
2796
}
2797
}
2798
2799
2800
2801
fn is_miss ( e : & StoreError) -> bool {
2802
match e {
2803
StoreError:: NotFound( _ ) => true ,
2804
StoreError:: Corrupt( _ , why) => why = = NO_DICT ,
2805
_ => false ,
ff0af1ee unknown 1 month ago
2806
}
afaba5f1 Andy McCall 1 month ago ↶
2807
}
2808
64818938 Andy McCall 1 month ago ↶
2809
2810
fn parse_loose ( data : & [u8 ], r : & ObjectRef) -> Result< Object> {
2811
let nul = data
2812
.iter ( )
2813
.position ( | & b | b = = 0 )
2814
.ok_or_else ( | | StoreError:: Corrupt( * r, " no header" .into ( ) ) ) ? ;
2815
let head = std:: str:: from_utf8( & data[ .. nul] )
2816
.map_err ( | _| StoreError:: Corrupt( * r, " header not UTF-8" .into ( ) ) ) ? ;
2817
let mut parts = head.split ( ' ' ) ;
2818
let ( Some ( " oxy1" ) , Some ( ty) , Some ( len) , None ) =
2819
( parts.next ( ) , parts.next ( ) , parts.next ( ) , parts.next ( ) )
2820
else {
2821
return Err ( StoreError:: Corrupt( * r, format! ( " bad header {head:?} " ) ) ) ;
afaba5f1 Andy McCall 1 month ago ↶
2822
} ;
64818938 Andy McCall 1 month ago ↶
2823
let ty = ObjectType:: from_name( ty)
2824
.ok_or_else ( | | StoreError:: Corrupt( * r, format! ( " unknown type {ty} " ) ) ) ? ;
2825
let len: usize = len
2826
.parse ( )
2827
.map_err ( | _| StoreError:: Corrupt( * r, " bad length" .into ( ) ) ) ? ;
2828
let body = & data[ nul + 1 .. ] ;
2829
if body.len ( ) ! = len {
2830
return Err ( StoreError:: Corrupt(
2831
* r,
2832
format! ( " length {} != header {len} " , body.len ( ) ) ,
2833
) ) ;
2834
}
2835
if hash_object ( ty, body) ! = * r {
2836
return Err ( StoreError:: Corrupt( * r, " hash mismatch" .into ( ) ) ) ;
2837
}
2838
Ok ( ( ty, body.to_vec ( ) ) )
2839
}
2840
2841
2842
2843
# [ cfg ( test ) ]
2844
fn files_on_disk ( ) -> bool {
2845
std:: env:: var_os( " OXY_STORE_BACKEND" ) .is_none ( )
ff0af1ee unknown 1 month ago
2846
}
2847
2848
# [ cfg ( test ) ]
2849
mod tests {
2850
use super :: * ;
64818938 Andy McCall 1 month ago ↶
2851
2852
2853
2854
fn each_store ( dir : & Path, f : impl Fn( &str , Store ) ) {
2855
f ( " directory" , Store:: open( dir.join ( " objects" ) ) .unwrap ( ) ) ;
2856
f (
2857
" memory" ,
2858
Store:: open_on( Arc:: new( MemoryStore:: new( ) ) , dir.join ( " scratch" ) ) .unwrap ( ) ,
2859
) ;
2860
}
ff0af1ee unknown 1 month ago
2861
2862
# [ test ]
2863
fn put_get_verify ( ) {
64818938 Andy McCall 1 month ago ↶
2864
if ! super :: files_on_disk( ) {
2865
return ;
2866
}
ff0af1ee unknown 1 month ago
2867
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2868
let s = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
2869
let r = s.put ( ObjectType:: Chunk, b " hello" ) .unwrap ( ) ;
2870
assert! ( s.has ( & r) ) ;
2871
assert_eq! ( s.get ( & r) .unwrap ( ) , ( ObjectType:: Chunk, b " hello" .to_vec ( ) ) ) ;
2872
assert_eq! ( s.put ( ObjectType:: Chunk, b " hello" ) .unwrap ( ) , r) ;
2873
assert_eq! ( s.list ( ) .unwrap ( ) , vec! [ r] ) ;
75167672 Andy McCall 1 month ago
2874
assert! ( matches! (
2875
s.get_typed ( & r, ObjectType:: Blob) ,
2876
Err ( StoreError:: WrongType( .. ) )
2877
) ) ;
2878
assert! ( matches! (
2879
s.get ( & ObjectRef( [ 9 ; 32 ] ) ) ,
2880
Err ( StoreError:: NotFound( _ ) )
2881
) ) ;
ff0af1ee unknown 1 month ago
2882
2883
2884
let path = s.path_for ( & r) ;
2885
let mut data = fs:: read( & path) .unwrap ( ) ;
2886
let last = data.len ( ) - 1 ;
2887
data[ last] ^ = 1 ;
2888
fs:: write( & path, data) .unwrap ( ) ;
2889
assert! ( matches! ( s.get ( & r) , Err ( StoreError:: Corrupt( .. ) ) ) ) ;
2890
}
2891
2892
# [ test ]
d02e545d Andy McCall 1 month ago ↶
2893
fn packing_keeps_every_object_readable ( ) {
64818938 Andy McCall 1 month ago ↶
2894
if ! super :: files_on_disk( ) {
2895
return ;
2896
}
d02e545d Andy McCall 1 month ago ↶
2897
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2898
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2899
let mut refs = Vec :: new( ) ;
2900
for i in 0 .. 300 u32 {
2901
let body = format! ( " object {i} " ) .repeat ( 1 + ( i % 7 ) as usize ) ;
2902
refs.push ( ( s.put ( ObjectType:: Chunk, body.as_bytes ( ) ) .unwrap ( ) , body) ) ;
2903
}
2904
let c = crate :: objects:: tests:: sample_change( ) ;
2905
let cr = s.put_change ( & c) .unwrap ( ) ;
2906
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 301 ) ;
2907
let report = s.pack_loose ( ) .unwrap ( ) ;
2908
assert_eq! ( report.objects, 301 ) ;
2909
assert! ( report.packed_bytes < report.raw_bytes, " {report:?}" ) ;
2910
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 0 ) ;
2911
assert_eq! ( s.pack_count ( ) , 1 ) ;
2912
for ( r, body) in & refs {
2913
assert! ( s.has ( r) ) ;
75167672 Andy McCall 1 month ago
2914
assert_eq! (
2915
s.get ( r) .unwrap ( ) ,
2916
( ObjectType:: Chunk, body.as_bytes ( ) .to_vec ( ) )
2917
) ;
d02e545d Andy McCall 1 month ago ↶
2918
}
2919
assert_eq! ( s.get_change ( & cr) .unwrap ( ) , c) ;
2920
assert_eq! ( s.list ( ) .unwrap ( ) .len ( ) , 301 ) ;
2921
2922
75167672 Andy McCall 1 month ago
2923
assert_eq! (
2924
s.put ( ObjectType:: Chunk, refs[ 0 ] .1. as_bytes ( ) ) .unwrap ( ) ,
2925
refs[ 0 ] .0
2926
) ;
d02e545d Andy McCall 1 month ago ↶
2927
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 0 ) ;
2928
let extra = s.put ( ObjectType:: Chunk, b " after packing" ) .unwrap ( ) ;
2929
s.pack_loose ( ) .unwrap ( ) ;
2930
assert_eq! ( s.pack_count ( ) , 2 ) ;
2931
assert_eq! ( s.get ( & extra) .unwrap ( ) .1 , b " after packing" ) ;
2932
2933
let s2 = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2934
assert_eq! ( s2.pack_count ( ) , 2 ) ;
2935
assert_eq! ( s2.get ( & refs[ 5 ] .0 ) .unwrap ( ) .1 , refs[ 5 ] .1. as_bytes ( ) ) ;
75167672 Andy McCall 1 month ago
2936
assert! ( matches! (
2937
s2.get ( & ObjectRef( [ 9 ; 32 ] ) ) ,
2938
Err ( StoreError:: NotFound( _ ) )
2939
) ) ;
d02e545d Andy McCall 1 month ago ↶
2940
2941
let target = refs[ 5 ] .0 ;
2942
let ( pack_path, offset) = {
2943
let packs = s2.packs.borrow ( ) ;
2944
let ( i, e) = s2.find_packed ( & target) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
2945
( dir.path ( ) .join ( & packs[ i] .key) , e.offset as usize )
d02e545d Andy McCall 1 month ago ↶
2946
} ;
2947
let mut data = fs:: read( & pack_path) .unwrap ( ) ;
2948
data[ offset] ^ = 0xff ;
2949
fs:: write( & pack_path, data) .unwrap ( ) ;
2950
let s3 = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2951
assert! ( matches! ( s3.get ( & target) , Err ( StoreError:: Corrupt( .. ) ) ) ) ;
75167672 Andy McCall 1 month ago
2952
assert_eq! (
2953
s3.get ( & refs[ 6 ] .0 ) .unwrap ( ) .1 ,
2954
refs[ 6 ] .1. as_bytes ( ) ,
2955
" other objects are unaffected"
2956
) ;
a17fc622 Andy McCall 1 month ago ↶
2957
}
2958
2959
# [ test ]
2960
fn a_full_repack_trains_a_dictionary_and_reads_back ( ) {
64818938 Andy McCall 1 month ago ↶
2961
if ! super :: files_on_disk( ) {
2962
return ;
2963
}
a17fc622 Andy McCall 1 month ago ↶
2964
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2965
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2966
2967
let bodies: Vec< Vec< u8 > > = ( 0 .. 1500 )
2968
.map ( | i | {
2969
format! (
2970
" // SPDX-License-Identifier: GPL-2.0\n #include <linux/module.h>\n \
2971
static int probe_{i} (struct device *dev)\n {{ \n \t return {i} ;\n }} \n "
2972
)
2973
.into_bytes ( )
2974
} )
2975
.collect ( ) ;
2976
let refs: Vec< ObjectRef> = bodies
2977
.iter ( )
2978
.map ( | b | s.put ( ObjectType:: Chunk, b) .unwrap ( ) )
2979
.collect ( ) ;
2980
s.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
2981
let dicts = fs:: read_dir( dir.path ( ) )
2982
.unwrap ( )
2983
.flatten ( )
2984
.filter ( | e | e.path ( ) .extension ( ) .is_some_and ( | x | x = = " dict" ) )
2985
.count ( ) ;
2986
assert_eq! ( dicts, 1 , " the pack has a dictionary" ) ;
2987
let with_dict = refs
2988
.iter ( )
2989
.filter ( | r | s.find_packed ( r) .unwrap ( ) .1. flags & FLAG_DICT ! = 0 )
2990
.count ( ) ;
2991
assert! ( with_dict > 1000 , " most use it: {with_dict}" ) ;
2992
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2993
for ( r, b) in refs.iter ( ) .zip ( & bodies) {
2994
assert_eq! ( & again.get ( r) .unwrap ( ) .1 , b) ;
2995
}
a67914bc Andy McCall 19 days ago ↶
2996
let packs = | dir : & Path| {
2997
let mut v: Vec< String> = fs:: read_dir( dir)
2998
.unwrap ( )
2999
.flatten ( )
3000
.map ( | e | e.file_name ( ) .to_string_lossy ( ) .into_owned ( ) )
3001
.filter ( | n | n.starts_with ( " pack-" ) )
3002
.collect ( ) ;
3003
v.sort ( ) ;
3004
v
3005
} ;
3006
3007
3008
let before = packs ( dir.path ( ) ) ;
3009
let ( report, merged) = again.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
3010
assert_eq! ( ( report.objects, merged) , ( 0 , 0 ) ) ;
3011
assert_eq! ( packs ( dir.path ( ) ) , before) ;
767ac6cd Andy McCall 17 days ago
3012
3013
a67914bc Andy McCall 19 days ago ↶
3014
let extra = again.put ( ObjectType:: Chunk, b " one more\n " ) .unwrap ( ) ;
a17fc622 Andy McCall 1 month ago ↶
3015
again.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
a67914bc Andy McCall 19 days ago ↶
3016
let files = packs ( dir.path ( ) ) ;
767ac6cd Andy McCall 17 days ago
3017
assert_eq! (
3018
files.len ( ) ,
3019
7 ,
3020
" two of pack, index and dictionary, and the retired record: {files:?}"
3021
) ;
3022
assert_eq! ( again.pack_count ( ) , 1 , " the old pack is not read" ) ;
a17fc622 Andy McCall 1 month ago ↶
3023
assert_eq! ( & again.get ( & refs[ 7 ] ) .unwrap ( ) .1 , & bodies[ 7 ] ) ;
a67914bc Andy McCall 19 days ago ↶
3024
assert_eq! ( again.get ( & extra) .unwrap ( ) .1 , b " one more\n " ) ;
767ac6cd Andy McCall 17 days ago
3025
again
3026
.expire_retired ( std:: time:: Duration:: ZERO , & mut silent ( ) )
3027
.unwrap ( ) ;
3028
let files = packs ( dir.path ( ) ) ;
3029
assert_eq! ( files.len ( ) , 4 , " one pack, index, dictionary: {files:?}" ) ;
3030
assert! ( before
3031
.iter ( )
3032
.filter ( | f | * f ! = RETIRED_KEY )
3033
.all ( | f | ! files.contains ( f) ) ) ;
3034
assert_eq! ( & again.get ( & refs[ 8 ] ) .unwrap ( ) .1 , & bodies[ 8 ] ) ;
d02e545d Andy McCall 1 month ago ↶
3035
}
3036
3037
# [ test ]
cdb5beba Andy McCall 1 month ago ↶
3038
fn nocompress_chunks_pack_raw ( ) {
3039
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3040
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3041
let body = vec! [ b ' a' ; 10_000 ] ;
3042
let raw = s.put_chunk_nocompress ( & body) .unwrap ( ) ;
3043
let compressible = s.put ( ObjectType:: Chunk, & vec! [ b ' b' ; 10_000 ] ) .unwrap ( ) ;
3044
s.pack_loose ( ) .unwrap ( ) ;
3045
let packs = s.packs.borrow ( ) ;
3046
let ( i, e) = s.find_packed ( & raw) .unwrap ( ) ;
3047
assert_eq! ( ( e.flags, e.stored_len as usize ) , ( 0 , 10_000 ) ) ;
3048
let ( _ , c) = s.find_packed ( & compressible) .unwrap ( ) ;
3049
assert_eq! ( c.flags, FLAG_ZSTD ) ;
3050
assert! ( c.stored_len < 10_000 ) ;
64818938 Andy McCall 1 month ago ↶
3051
assert_eq! ( packs[ i] .fetch ( s.backend.as_ref ( ) , & raw, e) .unwrap ( ) .1 , body) ;
cdb5beba Andy McCall 1 month ago ↶
3052
}
3053
3054
# [ test ]
135212de Andy McCall 1 month ago ↶
3055
fn many_packs_merge_into_one ( ) {
3056
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3057
each_store ( dir.path ( ) , | which , s | {
3058
let mut refs = Vec :: new( ) ;
3059
for i in 0 .. ( MAX_PACKS + 2 ) {
3060
refs.push (
3061
s.put ( ObjectType:: Chunk, format! ( " pack {i} " ) .as_bytes ( ) )
3062
.unwrap ( ) ,
3063
) ;
3064
s.pack_loose ( ) .unwrap ( ) ;
3065
}
3066
assert_eq! ( s.pack_count ( ) , MAX_PACKS + 2 , " {which}" ) ;
3067
assert_eq! ( s.merge_packs ( ) .unwrap ( ) , MAX_PACKS + 2 ) ;
3068
assert_eq! ( s.pack_count ( ) , 1 ) ;
3069
assert_eq! ( s.merge_packs ( ) .unwrap ( ) , 0 ) ;
3070
for ( i, r) in refs.iter ( ) .enumerate ( ) {
3071
assert_eq! ( s.get ( r) .unwrap ( ) .1 , format! ( " pack {i} " ) .as_bytes ( ) ) ;
3072
}
3073
let again = Store:: open_on( s.backend ( ) .clone ( ) , s.dir ( ) ) .unwrap ( ) ;
3074
assert_eq! ( again.pack_count ( ) , 1 , " {which}: reopened" ) ;
3075
} ) ;
135212de Andy McCall 1 month ago ↶
3076
}
3077
3078
# [ test ]
ba160f60 Andy McCall 1 month ago ↶
3079
fn prune_removes_unreachable_loose_and_packed_objects ( ) {
3080
use std:: collections:: HashSet;
3081
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3082
each_store ( dir.path ( ) , | which , s | {
3083
let keep_a = s.put ( ObjectType:: Chunk, b " keep a" ) .unwrap ( ) ;
3084
let drop_a = s.put ( ObjectType:: Chunk, b " drop a" ) .unwrap ( ) ;
3085
s.pack_loose ( ) .unwrap ( ) ;
3086
let keep_b = s.put ( ObjectType:: Chunk, b " keep b" ) .unwrap ( ) ;
3087
let drop_b = s.put ( ObjectType:: Chunk, b " drop b" ) .unwrap ( ) ;
3088
let sk = crate :: identity:: SecretKey {
3089
ed_seed: [ 1 ; 32 ] ,
3090
ml_seed: [ 2 ; 32 ] ,
3091
} ;
3092
let id = sk.identity ( " a" , " b" , 0 ) ;
3093
let key = s.put_identity ( & id) .unwrap ( ) ;
3094
s.put_signature (
3095
& drop_b,
3096
& sk.sign ( crate :: identity:: Domain:: Change, & key, & drop_b) ,
3097
)
75167672 Andy McCall 1 month ago
3098
.unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3099
s.index_seal ( & drop_a, & ObjectRef( [ 3 ; 32 ] ) ) .unwrap ( ) ;
3100
let keep: HashSet< ObjectRef> = [ keep_a, keep_b, key] .into_iter ( ) .collect ( ) ;
3101
3102
let r = s
3103
.prune ( & keep, std:: time:: Duration:: from_secs( 3600 ) )
3104
.unwrap ( ) ;
3105
assert_eq! ( ( r.objects, r.deferred) , ( 0 , 2 ) , " {which}" ) ;
3106
let r = s.prune ( & keep, std:: time:: Duration:: ZERO ) .unwrap ( ) ;
3107
assert_eq! ( r.objects, 2 , " {which}: {r:?}" ) ;
3108
assert! ( s.has ( & keep_a) & & s.has ( & keep_b) & & s.has ( & key) ) ;
3109
assert! ( ! s.has ( & drop_a) & & ! s.has ( & drop_b) ) ;
3110
assert! ( s.signatures ( & drop_b) .unwrap ( ) .is_empty ( ) ) ;
3111
assert! ( s.seals_for ( & drop_a) .unwrap ( ) .is_empty ( ) ) ;
3112
assert_eq! ( s.pack_count ( ) , 1 ) ;
3113
assert_eq! ( s.get ( & keep_a) .unwrap ( ) .1 , b " keep a" ) ;
3114
assert_eq! ( s.list ( ) .unwrap ( ) .len ( ) , 3 ) ;
3115
} ) ;
ba160f60 Andy McCall 1 month ago ↶
3116
}
3117
3118
# [ test ]
1983686f Andy McCall 1 month ago ↶
3119
fn signatures_are_stored_beside_objects ( ) {
64818938 Andy McCall 1 month ago ↶
3120
use crate :: identity:: { Domain, SecretKey} ;
3121
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3122
each_store ( dir.path ( ) , | which , s | {
3123
let r = s.put ( ObjectType:: Chunk, b " x" ) .unwrap ( ) ;
3124
assert! ( s.signatures ( & r) .unwrap ( ) .is_empty ( ) ) ;
3125
let sk = SecretKey {
3126
ed_seed: [ 1 ; 32 ] ,
3127
ml_seed: [ 2 ; 32 ] ,
3128
} ;
3129
let id = sk.identity ( " a" , " b" , 0 ) ;
3130
let key = s.put_identity ( & id) .unwrap ( ) ;
3131
assert_eq! ( s.get_identity ( & key) .unwrap ( ) , id) ;
3132
let sig = sk.sign ( Domain:: Change, & key, & r) ;
3133
s.put_signature ( & r, & sig) .unwrap ( ) ;
3134
s.put_signature ( & r, & sig) .unwrap ( ) ;
3135
assert_eq! ( s.signatures ( & r) .unwrap ( ) , vec! [ sig.clone ( ) ] , " {which}" ) ;
3136
3137
let sk2 = SecretKey {
3138
ed_seed: [ 3 ; 32 ] ,
3139
ml_seed: [ 4 ; 32 ] ,
3140
} ;
3141
let key2 = s.put_identity ( & sk2.identity ( " c" , " d" , 0 ) ) .unwrap ( ) ;
3142
let sig2 = sk2.sign ( Domain:: Change, & key2, & r) ;
3143
s.put_signature ( & r, & sig2) .unwrap ( ) ;
3144
let mut both = vec! [ sig.clone ( ) , sig2.clone ( ) ] ;
3145
both.sort_by_key ( | s | s.key ) ;
3146
assert_eq! ( s.signatures ( & r) .unwrap ( ) , both) ;
3147
3148
assert_eq! ( s.get ( & r) .unwrap ( ) .1 , b " x" ) ;
3149
3150
s.index_seal ( & r, & ObjectRef( [ 5 ; 32 ] ) ) .unwrap ( ) ;
3151
s.index_seal ( & r, & ObjectRef( [ 4 ; 32 ] ) ) .unwrap ( ) ;
3152
s.index_seal ( & r, & ObjectRef( [ 5 ; 32 ] ) ) .unwrap ( ) ;
3153
assert_eq! (
3154
s.seals_for ( & r) .unwrap ( ) ,
3155
vec! [ ObjectRef( [ 4 ; 32 ] ) , ObjectRef( [ 5 ; 32 ] ) ]
3156
) ;
3157
let st = ObjectRef( [ 6 ; 32 ] ) ;
3158
s.index_receipt ( & st, & ObjectRef( [ 7 ; 32 ] ) ) .unwrap ( ) ;
3159
assert_eq! ( s.receipts_for ( & st) .unwrap ( ) , vec! [ ObjectRef( [ 7 ; 32 ] ) ] ) ;
3160
assert_eq! ( s.receipt_states ( ) .unwrap ( ) , vec! [ st] ) ;
3161
} ) ;
3162
}
3163
3164
3165
3166
3167
# [ test ]
3168
fn an_older_store_s_sidecar_lists_are_still_read ( ) {
3169
if ! super :: files_on_disk( ) {
3170
return ;
3171
}
1983686f Andy McCall 1 month ago ↶
3172
use crate :: identity:: { Domain, SecretKey} ;
3173
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3174
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3175
let r = s.put ( ObjectType:: Chunk, b " old" ) .unwrap ( ) ;
3176
let h = r.to_hex ( ) ;
75167672 Andy McCall 1 month ago
3177
let sk = SecretKey {
3178
ed_seed: [ 1 ; 32 ] ,
3179
ml_seed: [ 2 ; 32 ] ,
3180
} ;
64818938 Andy McCall 1 month ago ↶
3181
let key = s.put_identity ( & sk.identity ( " a" , " b" , 0 ) ) .unwrap ( ) ;
1983686f Andy McCall 1 month ago ↶
3182
let sig = sk.sign ( Domain:: Change, & key, & r) ;
64818938 Andy McCall 1 month ago ↶
3183
let legacy = dir.path ( ) .join ( " sigs" ) .join ( & h[ .. 2 ] ) ;
3184
fs:: create_dir_all( & legacy) .unwrap ( ) ;
3185
fs:: write(
3186
legacy.join ( & h[ 2 .. ] ) ,
3187
Signature:: encode_list( std:: slice:: from_ref( & sig) ) ,
3188
)
3189
.unwrap ( ) ;
3190
let seals = dir.path ( ) .join ( " seals" ) .join ( & h[ .. 2 ] ) ;
3191
fs:: create_dir_all( & seals) .unwrap ( ) ;
3192
fs:: write(
3193
seals.join ( & h[ 2 .. ] ) ,
3194
format! ( " {} \n " , ObjectRef( [ 9 ; 32 ] ) .to_hex ( ) ) ,
3195
)
3196
.unwrap ( ) ;
3197
let receipts = dir.path ( ) .join ( " receipts" ) .join ( & h[ .. 2 ] ) ;
3198
fs:: create_dir_all( & receipts) .unwrap ( ) ;
3199
fs:: write(
3200
receipts.join ( & h[ 2 .. ] ) ,
3201
format! ( " {} \n " , ObjectRef( [ 8 ; 32 ] ) .to_hex ( ) ) ,
3202
)
3203
.unwrap ( ) ;
3204
3205
assert_eq! ( s.signatures ( & r) .unwrap ( ) , vec! [ sig.clone ( ) ] ) ;
3206
assert_eq! ( s.seals_for ( & r) .unwrap ( ) , vec! [ ObjectRef( [ 9 ; 32 ] ) ] ) ;
3207
assert_eq! ( s.receipts_for ( & r) .unwrap ( ) , vec! [ ObjectRef( [ 8 ; 32 ] ) ] ) ;
3208
assert_eq! ( s.receipt_states ( ) .unwrap ( ) , vec! [ r] ) ;
3209
1983686f Andy McCall 1 month ago ↶
3210
s.put_signature ( & r, & sig) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3211
s.index_seal ( & r, & ObjectRef( [ 1 ; 32 ] ) ) .unwrap ( ) ;
3212
assert_eq! ( s.signatures ( & r) .unwrap ( ) .len ( ) , 1 ) ;
3213
assert_eq! (
3214
s.seals_for ( & r) .unwrap ( ) ,
3215
vec! [ ObjectRef( [ 1 ; 32 ] ) , ObjectRef( [ 9 ; 32 ] ) ]
3216
) ;
3217
3218
let r2 = s.put ( ObjectType:: Chunk, b " kept" ) .unwrap ( ) ;
3219
let keep = [ r2, key] .into_iter ( ) .collect ( ) ;
3220
s.prune ( & keep, std:: time:: Duration:: ZERO ) .unwrap ( ) ;
3221
assert! ( s.signatures ( & r) .unwrap ( ) .is_empty ( ) ) ;
3222
assert! ( s.seals_for ( & r) .unwrap ( ) .is_empty ( ) ) ;
3223
assert! ( s.receipt_states ( ) .unwrap ( ) .is_empty ( ) ) ;
1983686f Andy McCall 1 month ago ↶
3224
}
3225
3226
# [ test ]
ff0af1ee unknown 1 month ago
3227
fn change_round_trip_through_store ( ) {
3228
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3229
each_store ( dir.path ( ) , | which , s | {
3230
let c = crate :: objects:: tests:: sample_change( ) ;
3231
let r = s.put_change ( & c) .unwrap ( ) ;
3232
assert_eq! ( r, c.hash ( ) , " {which}" ) ;
3233
assert_eq! ( s.get_change ( & r) .unwrap ( ) , c) ;
3234
assert_eq! ( s.get_change_meta ( & r) .unwrap ( ) .message, c.message) ;
3235
} ) ;
ff0af1ee unknown 1 month ago
3236
}
2b872d07 Andy McCall 1 month ago ↶
3237
3238
fn xorshift ( state : & mut u64 ) -> u64 {
3239
* state ^ = * state < < 13 ;
3240
* state ^ = * state > > 7 ;
3241
* state ^ = * state < < 17 ;
3242
* state
3243
}
3244
3245
3246
3247
3248
# [ test ]
3249
fn corrupted_packs_and_indexes_fail_cleanly ( ) {
64818938 Andy McCall 1 month ago ↶
3250
if ! super :: files_on_disk( ) {
3251
return ;
3252
}
2b872d07 Andy McCall 1 month ago ↶
3253
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3254
let objects = dir.path ( ) .join ( " objects" ) ;
3255
let s = Store:: open( & objects) .unwrap ( ) ;
3256
let mut refs = Vec :: new( ) ;
3257
let mut seed = 0x9e3779b97f4a7c15 u64 ;
3258
for i in 0 .. 40 u32 {
3259
let len = ( xorshift ( & mut seed) % 5000 ) as usize ;
3260
let mut body = vec! [ 0 u8 ; len] ;
3261
for b in body.iter_mut ( ) {
75167672 Andy McCall 1 month ago
3262
* b = if i % 2 = = 0 {
3263
( xorshift ( & mut seed) & 0xff ) as u8
3264
} else {
3265
b ' a' + ( i % 26 ) as u8
3266
} ;
2b872d07 Andy McCall 1 month ago ↶
3267
}
3268
refs.push ( s.put ( ObjectType:: Chunk, & body) .unwrap ( ) ) ;
3269
}
3270
s.pack_loose ( ) .unwrap ( ) ;
75167672 Andy McCall 1 month ago
3271
let pack = fs:: read_dir( & objects)
3272
.unwrap ( )
3273
.filter_map ( | e | e.ok ( ) .map ( | e | e.path ( ) ) )
3274
.find ( | p | p.extension ( ) .is_some_and ( | x | x = = " pack" ) )
3275
.unwrap ( ) ;
2b872d07 Andy McCall 1 month ago ↶
3276
let idx = pack.with_extension ( " idx" ) ;
3277
let pristine_pack = fs:: read( & pack) .unwrap ( ) ;
3278
let pristine_idx = fs:: read( & idx) .unwrap ( ) ;
3279
3280
for round in 0 .. 300 u32 {
75167672 Andy McCall 1 month ago
3281
let ( path, pristine) = if round % 2 = = 0 {
3282
( & pack, & pristine_pack)
3283
} else {
3284
( & idx, & pristine_idx)
3285
} ;
2b872d07 Andy McCall 1 month ago ↶
3286
let mut data = pristine.clone ( ) ;
3287
match xorshift ( & mut seed) % 4 {
3288
0 => {
3289
let at = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
3290
data[ at] ^ = 1 < < ( xorshift ( & mut seed) % 8 ) ;
3291
}
3292
1 => {
3293
let at = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
3294
data[ at] = ( xorshift ( & mut seed) & 0xff ) as u8 ;
3295
}
3296
2 => {
3297
let keep = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
3298
data.truncate ( keep) ;
3299
}
3300
_ => {
3301
let at = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
3302
let n = ( ( xorshift ( & mut seed) % 8 ) + 1 ) as usize ;
3303
for k in 0 .. n.min ( data.len ( ) - at) {
3304
data[ at + k] = 0xff ;
3305
}
3306
}
3307
}
3308
fs:: write( path, & data) .unwrap ( ) ;
3309
3310
3311
if let Ok ( s2) = Store:: open( & objects) {
3312
for r in & refs {
3313
match s2.get ( r) {
75167672 Andy McCall 1 month ago
3314
Ok ( ( ty, body) ) => assert_eq! (
3315
hash_object ( ty, & body) ,
3316
* r,
3317
" a returned object always matches its reference"
3318
) ,
3319
Err ( StoreError:: Corrupt( .. ) )
3320
| Err ( StoreError:: NotFound( _ ) )
3321
| Err ( StoreError:: Io( _ ) ) => { }
2b872d07 Andy McCall 1 month ago ↶
3322
Err ( e) => panic! ( " unexpected error {e}" ) ,
3323
}
3324
}
3325
}
3326
fs:: write( path, pristine) .unwrap ( ) ;
3327
}
3328
3329
let s3 = Store:: open( & objects) .unwrap ( ) ;
3330
for r in & refs {
3331
let ( ty, body) = s3.get ( r) .unwrap ( ) ;
3332
assert_eq! ( hash_object ( ty, & body) , * r) ;
3333
}
3334
}
8f10a07a Andy McCall 1 month ago ↶
3335
3336
3337
3338
# [ test ]
3339
fn batches_write_loose_or_one_pack ( ) {
3340
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3341
each_store ( dir.path ( ) , | which , s | {
3342
let outer = s.begin_batch ( ) .unwrap ( ) ;
3343
let a = s.put ( ObjectType:: Chunk, b " small a" ) .unwrap ( ) ;
3344
{
3345
let inner = s.begin_batch ( ) .unwrap ( ) ;
3346
let b = s.put ( ObjectType:: Chunk, b " small b" ) .unwrap ( ) ;
3347
assert! ( s.has ( & b) ) ;
3348
assert_eq! ( s.get ( & b) .unwrap ( ) .1 , b " small b" ) ;
3349
inner.finish ( ) .unwrap ( ) ;
3350
assert_eq! (
3351
s.loose_count ( ) .unwrap ( ) ,
3352
0 ,
3353
" {which}: the inner batch defers to the outer one"
3354
) ;
3355
}
3356
assert_eq! ( s.get ( & a) .unwrap ( ) .1 , b " small a" ) ;
75167672 Andy McCall 1 month ago
3357
assert_eq! (
64818938 Andy McCall 1 month ago ↶
3358
s.put ( ObjectType:: Chunk, b " small a" ) .unwrap ( ) ,
3359
a,
3360
" idempotent while pending"
75167672 Andy McCall 1 month ago
3361
) ;
64818938 Andy McCall 1 month ago ↶
3362
outer.finish ( ) .unwrap ( ) ;
3363
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 2 ) ;
3364
assert_eq! ( s.pack_count ( ) , 0 ) ;
3365
assert_eq! ( s.get ( & a) .unwrap ( ) .1 , b " small a" ) ;
8f10a07a Andy McCall 1 month ago ↶
3366
64818938 Andy McCall 1 month ago ↶
3367
3368
let big = s.begin_batch ( ) .unwrap ( ) ;
3369
let mut refs = Vec :: new( ) ;
3370
let mut seed = 7 u64 ;
3371
for i in 0 .. 300 u32 {
3372
let mut body = vec! [ b ' z' ; 40_000 ] ;
3373
if i % 3 = = 0 {
3374
for b in body.iter_mut ( ) {
3375
* b = ( xorshift ( & mut seed) & 0xff ) as u8 ;
3376
}
8f10a07a Andy McCall 1 month ago ↶
3377
}
64818938 Andy McCall 1 month ago ↶
3378
body[ .. 4 ] .copy_from_slice ( & i.to_le_bytes ( ) ) ;
3379
let r = if i % 5 = = 0 {
3380
s.put_chunk_nocompress ( & body) .unwrap ( )
3381
} else {
3382
s.put ( ObjectType:: Chunk, & body) .unwrap ( )
3383
} ;
3384
assert_eq! (
3385
s.get ( & r) .unwrap ( ) .1 ,
3386
body,
3387
" readable while pending (object {i})"
3388
) ;
3389
refs.push ( ( r, body) ) ;
8f10a07a Andy McCall 1 month ago ↶
3390
}
64818938 Andy McCall 1 month ago ↶
3391
assert! ( s.has ( & refs[ 0 ] .0 ) ) ;
3392
big.finish ( ) .unwrap ( ) ;
3393
assert_eq! ( s.pack_count ( ) , 1 ) ;
75167672 Andy McCall 1 month ago
3394
assert_eq! (
64818938 Andy McCall 1 month ago ↶
3395
s.loose_count ( ) .unwrap ( ) ,
3396
2 ,
3397
" nothing from the big batch is loose"
75167672 Andy McCall 1 month ago
3398
) ;
64818938 Andy McCall 1 month ago ↶
3399
assert! ( fs:: read_dir( s.dir ( ) )
75167672 Andy McCall 1 month ago
3400
.unwrap ( )
64818938 Andy McCall 1 month ago ↶
3401
.flatten ( )
3402
.all ( | e | ! e.file_name ( ) .to_string_lossy ( ) .contains ( " tmp-" ) ) ) ;
3403
let s2 = Store:: open_on( s.backend ( ) .clone ( ) , s.dir ( ) ) .unwrap ( ) ;
3404
for ( r, body) in & refs {
3405
assert_eq! ( s2.get ( r) .unwrap ( ) .1 , * body) ;
3406
}
3407
3408
{
3409
let _b = s2.begin_batch ( ) .unwrap ( ) ;
3410
s2.put ( ObjectType:: Chunk, b " dropped" ) .unwrap ( ) ;
3411
}
3412
assert_eq! (
3413
s2.get ( & hash_object ( ObjectType:: Chunk, b " dropped" ) )
3414
.unwrap ( )
3415
.1 ,
3416
b " dropped"
3417
) ;
3418
} ) ;
afaba5f1 Andy McCall 1 month ago ↶
3419
}
3420
3421
# [ test ]
3422
fn get_many_reads_loose_and_packed_objects_in_order ( ) {
3423
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
64818938 Andy McCall 1 month ago ↶
3424
each_store ( dir.path ( ) , | which , s | {
3425
let packed: Vec< ObjectRef> = ( 0 .. 20 )
3426
.map ( | i | {
3427
s.put ( ObjectType:: Chunk, format! ( " packed {i} " ) .as_bytes ( ) )
3428
.unwrap ( )
3429
} )
3430
.collect ( ) ;
3431
s.pack_loose ( ) .unwrap ( ) ;
3432
let loose: Vec< ObjectRef> = ( 0 .. 20 )
3433
.map ( | i | {
3434
s.put ( ObjectType:: Chunk, format! ( " loose {i} " ) .as_bytes ( ) )
3435
.unwrap ( )
3436
} )
3437
.collect ( ) ;
3438
let missing = hash_object ( ObjectType:: Chunk, b " never stored" ) ;
3439
let mut refs: Vec< ObjectRef> = Vec :: new( ) ;
3440
for i in 0 .. 20 {
3441
refs.push ( loose[ i] ) ;
3442
refs.push ( packed[ i] ) ;
3443
}
3444
refs.push ( missing) ;
3445
let got = s.get_many ( & refs) ;
3446
assert_eq! ( got.len ( ) , refs.len ( ) ) ;
3447
for ( i, r) in refs.iter ( ) .enumerate ( ) .take ( 40 ) {
3448
let want = if i % 2 = = 0 {
3449
format! ( " loose {} " , i / 2 )
3450
} else {
3451
format! ( " packed {} " , i / 2 )
3452
} ;
3453
let ( ty, body) = got[ i] .as_ref ( ) .unwrap ( ) ;
3454
assert_eq! (
3455
( * ty, body.as_slice ( ) ) ,
3456
( ObjectType:: Chunk, want.as_bytes ( ) ) ,
3457
" {which}: {r:?}"
3458
) ;
3459
}
3460
assert! ( matches! ( got[ 40 ] , Err ( StoreError:: NotFound( _ ) ) ) ) ;
3461
} ) ;
09245702 Andy McCall 19 days ago ↶
3462
}
3463
3464
3465
3466
3467
# [ test ]
3468
fn packed_objects_cost_no_loose_lookups ( ) {
3469
use std:: sync:: atomic:: { AtomicUsize, Ordering} ;
3470
struct Counting ( MemoryStore, AtomicUsize) ;
3471
impl crate:: strata:: Store for Counting {
3472
fn describe ( & self ) -> String {
3473
" counting" .into ( )
3474
}
3475
fn has ( & self , k : & str ) -> crate:: strata:: Result< bool > {
3476
self .0. has ( k)
3477
}
3478
fn get ( & self , k : & str ) -> crate:: strata:: Result< Vec< u8 > > {
3479
if k.starts_with ( " loose/" ) {
3480
self .1. fetch_add ( 1 , Ordering:: Relaxed) ;
3481
}
3482
self .0. get ( k)
3483
}
3484
fn get_range (
3485
& self ,
3486
k : & str ,
3487
r : std:: ops:: Range< u64 > ,
3488
) -> crate:: strata:: Result< Vec< u8 > > {
3489
self .0. get_range ( k, r)
3490
}
3491
fn put_new ( & self , k : & str , b : & [u8 ]) -> crate:: strata:: Result< ( ) > {
3492
self .0. put_new ( k, b)
3493
}
3494
fn list ( & self , p : & str ) -> crate:: strata:: Result< Vec< crate:: strata:: Entry> > {
3495
self .0. list ( p)
3496
}
3497
fn delete ( & self , k : & str ) -> crate:: strata:: Result< ( ) > {
3498
self .0. delete ( k)
3499
}
3500
fn read_ref (
3501
& self ,
3502
k : & str ,
3503
) -> crate:: strata:: Result< Option< ( Vec< u8 > , crate:: strata:: Version) > > {
3504
self .0. read_ref ( k)
3505
}
3506
fn write_ref (
3507
& self ,
3508
k : & str ,
3509
b : & [u8 ],
3510
e : Option< & crate:: strata:: Version> ,
3511
) -> crate:: strata:: Result< crate:: strata:: Version> {
3512
self .0. write_ref ( k, b, e)
3513
}
3514
}
3515
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3516
let backend = Arc:: new( Counting( MemoryStore:: new( ) , AtomicUsize:: new( 0 ) ) ) ;
3517
let s = Store:: open_on( backend.clone ( ) , dir.path ( ) .join ( " scratch" ) ) .unwrap ( ) ;
3518
let refs: Vec< ObjectRef> = ( 0 .. 10 )
3519
.map ( | i | {
3520
s.put ( ObjectType:: Chunk, format! ( " p {i} " ) .as_bytes ( ) )
3521
.unwrap ( )
3522
} )
3523
.collect ( ) ;
3524
s.pack_loose ( ) .unwrap ( ) ;
3525
let s = Store:: open_on( backend.clone ( ) , dir.path ( ) .join ( " scratch" ) ) .unwrap ( ) ;
3526
backend.1. store ( 0 , Ordering:: Relaxed) ;
3527
for r in & refs {
3528
assert! ( s.get ( r) .is_ok ( ) ) ;
3529
}
3530
assert! ( s.get_many ( & refs) .iter ( ) .all ( | g | g.is_ok ( ) ) ) ;
3531
assert_eq! ( backend.1. load ( Ordering:: Relaxed) , 0 , " no loose lookups" ) ;
3532
3533
let missing = hash_object ( ObjectType:: Chunk, b " never stored" ) ;
3534
assert! ( matches! ( s.get ( & missing) , Err ( StoreError:: NotFound( _ ) ) ) ) ;
3535
assert! ( backend.1. load ( Ordering:: Relaxed) > 0 ) ;
767ac6cd Andy McCall 17 days ago
3536
}
3537
}
3538
3539
3540
3541
# [ cfg ( test ) ]
3542
pub ( crate ) mod reader_tests {
3543
use super :: * ;
3544
3545
fn chunk ( i : usize ) -> Vec< u8 > {
3546
format! ( " object {i} " ) .repeat ( 1 + i % 5 ) .into_bytes ( )
3547
}
3548
3549
3550
fn each_pair ( f : impl Fn( &str , Store , Store ) ) {
3551
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3552
let s = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
3553
let r = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
3554
f ( " directory" , s, r) ;
3555
let m: Arc< Backend> = Arc:: new( MemoryStore:: new( ) ) ;
3556
let s = Store:: open_on( m.clone ( ) , dir.path ( ) .join ( " scratch" ) ) .unwrap ( ) ;
3557
let r = Store:: open_on( m, dir.path ( ) .join ( " scratch-r" ) ) .unwrap ( ) ;
3558
f ( " memory" , s, r) ;
3559
}
3560
3561
3562
pub ( crate ) fn age_retired ( s : & Store, by : std:: time:: Duration) {
3563
s.update_retired ( | m | {
3564
for t in m.values_mut ( ) {
3565
* t = t.saturating_sub ( by.as_millis ( ) as u64 ) ;
3566
}
3567
} )
3568
.unwrap ( ) ;
3569
}
3570
3571
fn retired_keys ( s : & Store) -> Vec< String> {
3572
s.read_retired ( ) .unwrap ( ) .0. into_keys ( ) .collect ( )
3573
}
3574
3575
# [ test ]
3576
fn a_reader_opened_before_a_repack_reads_every_object_after_it ( ) {
3577
each_pair ( | which , writer , _| {
3578
let mut refs = Vec :: new( ) ;
3579
for i in 0 .. 40 {
3580
refs.push ( writer.put ( ObjectType:: Chunk, & chunk ( i) ) .unwrap ( ) ) ;
3581
}
3582
writer.pack_loose ( ) .unwrap ( ) ;
3583
for i in 40 .. 80 {
3584
refs.push ( writer.put ( ObjectType:: Chunk, & chunk ( i) ) .unwrap ( ) ) ;
3585
}
3586
3587
let reader = Store:: open_on( writer.backend ( ) .clone ( ) , writer.dir ( ) ) .unwrap ( ) ;
3588
assert_eq! ( reader.pack_count ( ) , 1 , " {which}" ) ;
3589
let ( _ , merged) = writer.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
3590
assert_eq! ( merged, 1 ) ;
3591
3592
let retired = retired_keys ( & writer) ;
3593
assert_eq! ( retired.len ( ) , 81 , " {which}: {retired:?}" ) ;
3594
assert_eq! ( writer.loose_count ( ) .unwrap ( ) , 0 , " retired is not loose" ) ;
3595
3596
for ( i, r) in refs.iter ( ) .enumerate ( ) {
3597
assert_eq! ( reader.get ( r) .unwrap ( ) .1 , chunk ( i) , " {which}: {i}" ) ;
3598
}
3599
assert_eq! ( reader.pack_count ( ) , 1 ) ;
3600
3601
let fresh = Store:: open_on( writer.backend ( ) .clone ( ) , writer.dir ( ) ) .unwrap ( ) ;
3602
assert_eq! ( fresh.pack_count ( ) , 1 ) ;
3603
assert_ne! ( fresh.packs.borrow ( ) [ 0 ] .key, reader.packs.borrow ( ) [ 0 ] .key) ;
3604
3605
3606
let report = writer
3607
.expire_retired ( std:: time:: Duration:: ZERO , & mut silent ( ) )
3608
.unwrap ( ) ;
3609
assert_eq! ( ( report.packs, report.loose) , ( 1 , 80 ) , " {which}" ) ;
3610
assert! ( retired_keys ( & writer) .is_empty ( ) ) ;
3611
for ( i, r) in refs.iter ( ) .enumerate ( ) {
3612
assert_eq! ( reader.get ( r) .unwrap ( ) .1 , chunk ( i) , " {which}: {i}" ) ;
3613
}
3614
let other = Store:: open_on( writer.backend ( ) .clone ( ) , writer.dir ( ) ) .unwrap ( ) ;
3615
let before = other.packs.borrow ( ) [ 0 ] .key.clone ( ) ;
3616
writer.put ( ObjectType:: Chunk, b " new" ) .unwrap ( ) ;
3617
writer.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
3618
writer
3619
.expire_retired ( std:: time:: Duration:: ZERO , & mut silent ( ) )
3620
.unwrap ( ) ;
3621
assert! ( other.get_many ( & refs) .iter ( ) .all ( | g | g.is_ok ( ) ) , " {which}" ) ;
3622
assert_ne! ( other.packs.borrow ( ) [ 0 ] .key, before) ;
3623
let third = Store:: open_on( writer.backend ( ) .clone ( ) , writer.dir ( ) ) .unwrap ( ) ;
3624
writer.put ( ObjectType:: Chunk, b " newer" ) .unwrap ( ) ;
3625
writer.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
3626
writer
3627
.expire_retired ( std:: time:: Duration:: ZERO , & mut silent ( ) )
3628
.unwrap ( ) ;
3629
assert! ( refs.iter ( ) .all ( | r | third.has ( r) ) , " {which}" ) ;
3630
assert! ( ! third.has ( & hash_object ( ObjectType:: Chunk, b " never" ) ) ) ;
3631
} ) ;
3632
}
3633
3634
# [ test ]
3635
fn a_reader_opened_before_a_spilled_batch_reads_its_objects ( ) {
3636
each_pair ( | which , writer , reader | {
3637
assert_eq! ( reader.pack_count ( ) , 0 ) ;
3638
let mut refs = Vec :: new( ) ;
3639
{
3640
let batch = writer.begin_batch ( ) .unwrap ( ) ;
3641
for i in 0 .. ( SPILL_OBJECTS + 50 ) {
3642
refs.push ( writer.put ( ObjectType:: Chunk, & chunk ( i) ) .unwrap ( ) ) ;
3643
}
3644
batch.finish ( ) .unwrap ( ) ;
3645
}
3646
assert_eq! ( writer.pack_count ( ) , 1 , " {which}: the batch spilled" ) ;
3647
assert_eq! ( reader.get ( & refs[ 0 ] ) .unwrap ( ) .1 , chunk ( 0 ) , " {which}" ) ;
3648
assert_eq! ( reader.pack_count ( ) , 1 , " the miss loaded the new pack" ) ;
3649
let got = reader.get_many ( & refs) ;
3650
assert! ( got.iter ( ) .all ( | g | g.is_ok ( ) ) , " {which}" ) ;
3651
3652
let late = Store:: open_on( writer.backend ( ) .clone ( ) , writer.dir ( ) ) .unwrap ( ) ;
3653
{
3654
let batch = writer.begin_batch ( ) .unwrap ( ) ;
3655
for i in 1000 .. ( 1000 + SPILL_OBJECTS + 1 ) {
3656
writer.put ( ObjectType:: Chunk, & chunk ( i) ) .unwrap ( ) ;
3657
}
3658
batch.finish ( ) .unwrap ( ) ;
3659
}
3660
assert! ( late.has ( & hash_object ( ObjectType:: Chunk, & chunk ( 1000 ) ) ) ) ;
3661
} ) ;
3662
}
3663
3664
# [ test ]
3665
fn retired_entries_expire_after_the_hour_and_are_never_loaded ( ) {
3666
each_pair ( | which , s , _| {
3667
for i in 0 .. 10 {
3668
s.put ( ObjectType:: Chunk, & chunk ( i) ) .unwrap ( ) ;
3669
}
3670
s.pack_loose ( ) .unwrap ( ) ;
3671
s.put ( ObjectType:: Chunk, & chunk ( 10 ) ) .unwrap ( ) ;
3672
s.repack_all ( ZSTD_LEVEL ) .unwrap ( ) ;
3673
3674
age_retired ( & s, RETIRED_FOR + std:: time:: Duration:: from_secs( 60 ) ) ;
3675
let old = retired_keys ( & s) ;
3676
assert_eq! ( old.len ( ) , 12 , " {which}: {old:?}" ) ;
3677
3678
s.put ( ObjectType:: Chunk, & chunk ( 11 ) ) .unwrap ( ) ;
3679
s.repack_all ( ZSTD_LEVEL ) .unwrap ( ) ;
3680
assert_eq! ( retired_keys ( & s) .len ( ) , 14 ) ;
3681
let listed = s
3682
.backend ( )
3683
.list ( " pack-" )
3684
.unwrap ( )
3685
.into_iter ( )
3686
.filter ( | e | e.key.ends_with ( " .idx" ) )
3687
.count ( ) ;
3688
assert_eq! ( listed, 3 , " {which}" ) ;
3689
let fresh = Store:: open_on( s.backend ( ) .clone ( ) , s.dir ( ) ) .unwrap ( ) ;
3690
assert_eq! (
3691
fresh.pack_count ( ) ,
3692
1 ,
3693
" {which}: retired packs are not loaded"
3694
) ;
3695
let report = s.expire_retired ( RETIRED_FOR , & mut silent ( ) ) .unwrap ( ) ;
3696
assert_eq! (
3697
report,
3698
RetiredReport {
3699
packs: 1 ,
3700
loose: 11 ,
3701
kept: 2
3702
} ,
3703
" {which}"
3704
) ;
3705
let young = retired_keys ( & s) ;
3706
assert_eq! ( young.len ( ) , 2 , " {which}: {young:?}" ) ;
3707
assert! ( young.iter ( ) .all ( | k | ! old.contains ( k) ) ) ;
3708
for k in old.iter ( ) .filter ( | k | k.ends_with ( " .pack" ) ) {
3709
assert! ( ! s.backend ( ) .has ( k) .unwrap ( ) , " {which}: {k}" ) ;
3710
}
3711
for k in & young {
3712
assert! ( s.backend ( ) .has ( k) .unwrap ( ) , " {which}: {k} kept" ) ;
3713
}
3714
for i in 0 .. 12 {
3715
let r = hash_object ( ObjectType:: Chunk, & chunk ( i) ) ;
3716
assert_eq! ( fresh.get ( & r) .unwrap ( ) .1 , chunk ( i) , " {which}" ) ;
3717
}
3718
} ) ;
3719
}
3720
3721
3722
3723
# [ test ]
3724
fn a_retired_loose_object_no_pack_holds_is_kept ( ) {
3725
each_pair ( | which , s , _| {
3726
let a = s.put ( ObjectType:: Chunk, b " a" ) .unwrap ( ) ;
3727
let b = s.put ( ObjectType:: Chunk, b " b" ) .unwrap ( ) ;
3728
s.pack_loose ( ) .unwrap ( ) ;
3729
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 0 ) ;
3730
3731
let first = s.packs.borrow ( ) [ 0 ] .key.clone ( ) ;
3732
s.write_pack ( & [ a] , & [ ] , & [ first] , ZSTD_LEVEL , & mut silent ( ) )
3733
.unwrap ( ) ;
3734
let report = s
3735
.expire_retired ( std:: time:: Duration:: ZERO , & mut silent ( ) )
3736
.unwrap ( ) ;
3737
assert_eq! ( ( report.packs, report.loose) , ( 1 , 1 ) , " {which}: a's copy" ) ;
3738
assert! ( retired_keys ( & s) .is_empty ( ) ) ;
3739
assert_eq! ( s.get ( & b) .unwrap ( ) .1 , b " b" , " {which}" ) ;
3740
assert_eq! ( s.get ( & a) .unwrap ( ) .1 , b " a" ) ;
3741
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 1 , " b is loose again" ) ;
3742
3743
let keep = [ a] .into_iter ( ) .collect ( ) ;
3744
let r = s.prune ( & keep, std:: time:: Duration:: ZERO ) .unwrap ( ) ;
3745
assert_eq! ( r.objects, 1 ) ;
3746
assert! ( ! s.has ( & b) ) ;
3747
} ) ;
3748
}
3749
3750
3751
3752
pub ( crate ) struct Racing {
3753
inner : MemoryStore,
3754
lists : std:: sync:: atomic:: AtomicUsize,
3755
3756
pub (crate) doomed : std:: sync:: Mutex< Option< String> > ,
3757
3758
ghost : bool ,
3759
}
3760
3761
impl crate:: strata:: Store for Racing {
3762
fn describe ( & self ) -> String {
3763
" racing" .into ( )
3764
}
3765
fn has ( & self , k : & str ) -> crate:: strata:: Result< bool > {
3766
self .inner.has ( k)
3767
}
3768
fn get ( & self , k : & str ) -> crate:: strata:: Result< Vec< u8 > > {
3769
self .inner.get ( k)
3770
}
3771
fn get_range ( & self , k : & str , r : std:: ops:: Range< u64 > ) -> crate:: strata:: Result< Vec< u8 > > {
3772
self .inner.get_range ( k, r)
3773
}
3774
fn put_new ( & self , k : & str , b : & [u8 ]) -> crate:: strata:: Result< ( ) > {
3775
self .inner.put_new ( k, b)
3776
}
3777
fn list ( & self , p : & str ) -> crate:: strata:: Result< Vec< crate:: strata:: Entry> > {
3778
let mut out = self .inner.list ( p) ? ;
3779
if p = = " pack-" {
3780
self .lists
3781
.fetch_add ( 1 , std:: sync:: atomic:: Ordering:: Relaxed) ;
3782
if let Some ( k) = self .doomed.lock ( ) .unwrap ( ) .take ( ) {
3783
self .inner.delete ( & k) ? ;
3784
}
3785
if self .ghost {
3786
for k in [ " pack-0000.idx" , " pack-0000.pack" ] {
3787
out.push ( crate :: strata:: Entry {
3788
key: k.into ( ) ,
3789
size: 100 ,
3790
modified_ms: None ,
3791
} ) ;
3792
}
3793
out.sort_by ( | a , b | a.key.cmp ( & b.key) ) ;
3794
}
3795
}
3796
Ok ( out)
3797
}
3798
fn delete ( & self , k : & str ) -> crate:: strata:: Result< ( ) > {
3799
self .inner.delete ( k)
3800
}
3801
fn read_ref (
3802
& self ,
3803
k : & str ,
3804
) -> crate:: strata:: Result< Option< ( Vec< u8 > , crate:: strata:: Version) > > {
3805
self .inner.read_ref ( k)
3806
}
3807
fn write_ref (
3808
& self ,
3809
k : & str ,
3810
b : & [u8 ],
3811
e : Option< & crate:: strata:: Version> ,
3812
) -> crate:: strata:: Result< crate:: strata:: Version> {
3813
self .inner.write_ref ( k, b, e)
3814
}
3815
}
3816
3817
pub ( crate ) fn racing ( ghost : bool ) -> Arc< Racing> {
3818
Arc:: new( Racing {
3819
inner: MemoryStore:: new( ) ,
3820
lists: Default :: default( ) ,
3821
doomed: Default :: default( ) ,
3822
ghost,
3823
} )
3824
}
3825
3826
# [ test ]
3827
fn an_index_deleted_between_listing_and_loading_is_passed_over ( ) {
3828
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3829
let backend = racing ( false ) ;
3830
let s = Store:: open_on( backend.clone ( ) , dir.path ( ) ) .unwrap ( ) ;
3831
let a = s.put ( ObjectType:: Chunk, b " a" ) .unwrap ( ) ;
3832
s.pack_loose ( ) .unwrap ( ) ;
3833
let b = s.put ( ObjectType:: Chunk, b " b" ) .unwrap ( ) ;
3834
s.pack_loose ( ) .unwrap ( ) ;
3835
let idx = {
3836
let packs = s.packs.borrow ( ) ;
3837
let ( i, _ ) = s.find_packed ( & a) .unwrap ( ) ;
3838
format! ( " {} .idx" , packs[ i] .key.trim_end_matches ( " .pack" ) )
3839
} ;
3840
* backend.doomed.lock ( ) .unwrap ( ) = Some ( idx) ;
3841
let before = backend.lists.load ( std:: sync:: atomic:: Ordering:: Relaxed) ;
3842
let again = Store:: open_on( backend.clone ( ) , dir.path ( ) ) .unwrap ( ) ;
3843
assert_eq! ( again.pack_count ( ) , 1 , " the deleted one is passed over" ) ;
3844
assert_eq! (
3845
backend.lists.load ( std:: sync:: atomic:: Ordering:: Relaxed) - before,
3846
2 ,
3847
" and the store listed again"
3848
) ;
3849
assert_eq! ( again.get ( & b) .unwrap ( ) .1 , b " b" ) ;
3850
3851
let ghosted = racing ( true ) ;
3852
let s = Store:: open_on( ghosted.clone ( ) , dir.path ( ) .join ( " g" ) ) .unwrap ( ) ;
3853
let c = s.put ( ObjectType:: Chunk, b " c" ) .unwrap ( ) ;
3854
s.pack_loose ( ) .unwrap ( ) ;
3855
let again = Store:: open_on( ghosted, dir.path ( ) .join ( " g" ) ) .unwrap ( ) ;
3856
assert_eq! ( again.pack_count ( ) , 1 ) ;
3857
assert_eq! ( again.get ( & c) .unwrap ( ) .1 , b " c" ) ;
a9f686ed Andy McCall 1 month ago ↶
3858
}
3859
}
3860
3861
# [ cfg ( test ) ]
3862
mod batch_tests {
3863
use super :: * ;
3864
3865
# [ test ]
3866
fn a_large_batch_packs_every_object_and_indexes_them_all ( ) {
3867
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3868
let store = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3869
let mut refs = Vec :: new( ) ;
3870
{
3871
let batch = store.begin_batch ( ) .unwrap ( ) ;
3872
for i in 0 .. 1000 u32 {
3873
let body = format! ( " object {i} {} " , " x" .repeat ( 20_000 + i as usize ) ) .into_bytes ( ) ;
3874
refs.push ( store.put ( ObjectType:: Blob, & body) .unwrap ( ) ) ;
3875
}
3876
batch.finish ( ) .unwrap ( ) ;
3877
}
3878
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3879
for r in & refs {
3880
again
54e2e630 Andy McCall 29 days ago ↶
3881
.get ( r)
3882
.unwrap_or_else ( | e | panic! ( " {}: {e}" , r.short ( 12 ) ) ) ;
3883
}
3884
}
3885
3886
# [ test ]
3887
fn a_pack_a_stopped_batch_left_is_adopted_and_its_torn_end_cut ( ) {
3888
3889
3890
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3891
let mut refs = Vec :: new( ) ;
3892
{
3893
let store = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3894
let batch = store.begin_batch ( ) .unwrap ( ) ;
3895
for i in 0 .. 300 u32 {
3896
let body = format! ( " object {i} {} " , " y" .repeat ( 20_000 + i as usize ) ) .into_bytes ( ) ;
3897
refs.push ( store.put ( ObjectType:: Blob, & body) .unwrap ( ) ) ;
3898
}
3899
std:: mem:: forget( batch) ;
3900
}
3901
let tmp: Vec< _ > = fs:: read_dir( dir.path ( ) )
3902
.unwrap ( )
3903
.flatten ( )
3904
.filter ( | e | e.file_name ( ) .to_string_lossy ( ) .starts_with ( " .tmp-" ) )
3905
.map ( | e | e.path ( ) )
3906
.collect ( ) ;
3907
assert_eq! ( tmp.len ( ) , 1 , " one unfinished pack" ) ;
3908
3909
let mut f = fs:: OpenOptions:: new( ) .append ( true ) .open ( & tmp[ 0 ] ) .unwrap ( ) ;
3910
f.write_all ( & [ 0 , 1 , 0xff , 0 , 0 , 0 , 9 , 9 , 0 , 0 ] ) .unwrap ( ) ;
3911
f.write_all ( & [ 7 ; 40 ] ) .unwrap ( ) ;
3912
drop ( f) ;
3913
let store = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3914
assert! ( store.get ( & refs[ 0 ] ) .is_err ( ) , " unreadable before" ) ;
3915
let young = store
3916
.adopt_unfinished_packs ( std:: time:: Duration:: from_secs( 3600 ) , & | _ | { } )
3917
.unwrap ( ) ;
3918
assert_eq! ( young, ( 0 , 0 ) , " a pack written to lately is left alone" ) ;
3919
let ( packs, objects) = store
3920
.adopt_unfinished_packs ( std:: time:: Duration:: ZERO , & | _ | { } )
3921
.unwrap ( ) ;
3922
assert_eq! ( ( packs, objects) , ( 1 , 300 ) ) ;
3923
for r in & refs {
3924
store
a9f686ed Andy McCall 1 month ago ↶
3925
.get ( r)
3926
.unwrap_or_else ( | e | panic! ( " {}: {e}" , r.short ( 12 ) ) ) ;
3927
}
54e2e630 Andy McCall 29 days ago ↶
3928
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3929
assert! ( again.get ( & refs[ 299 ] ) .is_ok ( ) , " indexed for good" ) ;
a9f686ed Andy McCall 1 month ago ↶
3930
}
3931
}
3932
3933
# [ cfg ( test ) ]
3934
mod size_tests {
3935
use super :: * ;
3936
3937
# [ test ]
3938
fn an_object_over_the_limit_is_refused_and_nothing_is_written ( ) {
3939
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3940
let store = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3941
let big = vec! [ b ' x' ; MAX_OBJECT_LEN as usize + 1 ] ;
3942
{
3943
let batch = store.begin_batch ( ) .unwrap ( ) ;
3944
store.put ( ObjectType:: Blob, b " small" ) .unwrap ( ) ;
3945
let e = store.put ( ObjectType:: Change, & big) .unwrap_err ( ) ;
3946
assert! (
3947
matches! ( e, StoreError:: TooLarge { kind: " change" , .. } ) ,
3948
" {e}"
3949
) ;
3950
assert! ( e.to_string ( ) .contains ( " commit it in parts" ) , " {e}" ) ;
3951
batch.finish ( ) .unwrap ( ) ;
3952
}
3953
3954
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3955
again.get ( & hash_object ( ObjectType:: Blob, b " small" ) ) .unwrap ( ) ;
6f8aeb99 Andy McCall 1 month ago ↶
3956
}
3957
}
3958
3959
# [ cfg ( test ) ]
3960
mod text_tests {
3961
use super :: * ;
3962
use crate :: objects:: { AtomRef, Edit, CHANGE_VERSION } ;
3963
3964
fn large_change ( ) -> Change {
3965
let mut c = crate :: objects:: tests:: sample_change( ) ;
3966
assert_eq! ( c.version, CHANGE_VERSION ) ;
3967
c.edits[ 0 ] = Edit:: Insert {
3968
node: crate :: ids:: NodeId( [ 7 ; 16 ] ) ,
3969
after: AtomRef:: Start,
3970
before: AtomRef:: End,
3971
lines: ( 0 .. 2000 )
3972
.map ( | i | format! ( " line {i} \n " ) .into_bytes ( ) )
3973
.collect ( ) ,
3974
} ;
3975
c
3976
}
3977
3978
# [ test ]
3979
fn a_large_insert_is_stored_beside_its_change_and_read_back ( ) {
3980
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
3981
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
3982
let c = large_change ( ) ;
3983
let r = s.put_change ( & c) .unwrap ( ) ;
3984
assert_eq! ( r, c.hash ( ) ) ;
3985
let ( _ , body) = s.get ( & r) .unwrap ( ) ;
3986
assert! (
3987
body.len ( ) < 1024 ,
3988
" the change holds a reference, not {} bytes of lines" ,
3989
body.len ( )
3990
) ;
3991
let ( back, parts) = s.get_change_parts ( & r) .unwrap ( ) ;
3992
assert_eq! ( back, c) ;
3993
3994
assert_eq! ( parts.len ( ) , 2 ) ;
3995
for p in & parts {
3996
assert! ( s.has ( p) ) ;
3997
}
3998
3999
let n = s.list ( ) .unwrap ( ) .len ( ) ;
4000
s.put_change ( & c) .unwrap ( ) ;
4001
assert_eq! ( s.list ( ) .unwrap ( ) .len ( ) , n) ;
4002
}
4003
4004
# [ test ]
4005
fn a_change_whose_text_blob_is_missing_is_reported_not_misread ( ) {
64818938 Andy McCall 1 month ago ↶
4006
if ! super :: files_on_disk( ) {
4007
return ;
4008
}
6f8aeb99 Andy McCall 1 month ago ↶
4009
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
4010
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
4011
let c = large_change ( ) ;
4012
let r = s.put_change ( & c) .unwrap ( ) ;
4013
let ( _ , parts) = s.get_change_parts ( & r) .unwrap ( ) ;
4014
fs:: remove_file( s.path_for ( & parts[ 0 ] ) ) .unwrap ( ) ;
4015
let e = s.get_change ( & r) .unwrap_err ( ) ;
4016
assert! (
4017
matches! ( & e, StoreError:: Corrupt( h, why) if * h = = r & & why.contains ( " missing" ) ) ,
4018
" {e}"
4019
) ;
192fad1e Andy McCall 1 month ago ↶
4020
}
4021
}
4022
4023
# [ cfg ( test ) ]
4024
mod put_many_tests {
4025
use super :: * ;
4026
4027
# [ test ]
4028
fn many_objects_in_a_batch_are_compressed_together_and_all_read_back ( ) {
4029
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
4030
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
4031
let before = s.put ( ObjectType:: Chunk, b " already here" ) .unwrap ( ) ;
4032
let bodies: Vec< Vec< u8 > > = ( 0 .. 200 u32 )
4033
.map ( | i | format! ( " chunk {i} " ) .repeat ( 6000 ) .into_bytes ( ) )
4034
.collect ( ) ;
4035
let mut objects: Vec< ( ObjectType, & [u8 ]) > = bodies
4036
.iter ( )
4037
.map ( | b | ( ObjectType:: Chunk, b.as_slice ( ) ) )
4038
.collect ( ) ;
4039
objects.push ( ( ObjectType:: Chunk, bodies[ 0 ] .as_slice ( ) ) ) ;
4040
objects.push ( ( ObjectType:: Chunk, b " already here" ) ) ;
4041
let refs = {
4042
let batch = s.begin_batch ( ) .unwrap ( ) ;
4043
let refs = s.put_many ( & objects) .unwrap ( ) ;
4044
batch.finish ( ) .unwrap ( ) ;
4045
refs
4046
} ;
4047
assert_eq! ( refs.len ( ) , objects.len ( ) ) ;
4048
assert_eq! ( refs[ 200 ] , refs[ 0 ] , " a repeat is the same object" ) ;
4049
assert_eq! ( refs[ 201 ] , before) ;
4050
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
4051
for ( r, b) in refs.iter ( ) .zip ( & objects) {
4052
assert_eq! ( again.get ( r) .unwrap ( ) .1 , b.1 ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
4053
}
4054
}
4055
}
4056
4057
4058
4059
# [ cfg ( test ) ]
4060
mod entry_tests {
4061
use super :: * ;
4062
use crate :: identity:: { Domain, SecretKey} ;
4063
use crate :: strata:: Store as _ ;
4064
use std:: collections:: HashMap;
4065
use std:: sync:: atomic:: { AtomicBool, Ordering} ;
4066
use std:: sync:: Mutex;
4067
4068
4069
4070
4071
4072
# [ derive ( Default ) ]
4073
struct Counted {
4074
inner : MemoryStore,
4075
counts : Mutex< HashMap< & 'static str , usize > > ,
4076
interfere : AtomicBool,
4077
}
4078
4079
impl Counted {
4080
fn count ( & self , kind : & 'static str ) {
4081
* self .counts.lock ( ) .unwrap ( ) .entry ( kind) .or_default ( ) + = 1 ;
4082
}
4083
fn n ( & self , kind : & str ) -> usize {
4084
self .counts.lock ( ) .unwrap ( ) .get ( kind) .copied ( ) .unwrap_or ( 0 )
192fad1e Andy McCall 1 month ago ↶
4085
}
ef7d4ea6 Andy McCall 16 days ago ↶
4086
fn reset ( & self ) {
4087
self .counts.lock ( ) .unwrap ( ) .clear ( ) ;
4088
}
4089
fn total ( & self ) -> usize {
4090
self .counts.lock ( ) .unwrap ( ) .values ( ) .sum ( )
4091
}
4092
fn summary ( & self ) -> String {
4093
let c = self .counts.lock ( ) .unwrap ( ) ;
4094
let mut v: Vec< String> = c.iter ( ) .map ( | ( k , n ) | format! ( " {k} {n} " ) ) .collect ( ) ;
4095
v.sort ( ) ;
4096
v.join ( " , " )
4097
}
4098
}
4099
4100
impl crate:: strata:: Store for Counted {
4101
fn describe ( & self ) -> String {
4102
" counted" .into ( )
4103
}
4104
fn has ( & self , k : & str ) -> crate:: strata:: Result< bool > {
4105
self .count ( " has" ) ;
4106
self .inner.has ( k)
4107
}
4108
fn get ( & self , k : & str ) -> crate:: strata:: Result< Vec< u8 > > {
4109
self .count ( if is_legacy ( k) { " get_legacy" } else { " get" } ) ;
4110
self .inner.get ( k)
4111
}
4112
fn get_range ( & self , k : & str , r : std:: ops:: Range< u64 > ) -> crate:: strata:: Result< Vec< u8 > > {
4113
self .count ( " range" ) ;
4114
self .inner.get_range ( k, r)
4115
}
4116
fn put_new ( & self , k : & str , b : & [u8 ]) -> crate:: strata:: Result< ( ) > {
4117
self .count ( " put" ) ;
4118
self .inner.put_new ( k, b)
4119
}
4120
fn list ( & self , p : & str ) -> crate:: strata:: Result< Vec< crate:: strata:: Entry> > {
4121
self .count ( if p = = " pack-" {
4122
" list_packs"
4123
} else if is_legacy ( p) {
4124
" list_legacy"
4125
} else {
4126
" list"
4127
} ) ;
4128
self .inner.list ( p)
4129
}
4130
fn delete ( & self , k : & str ) -> crate:: strata:: Result< ( ) > {
4131
self .count ( " delete" ) ;
4132
self .inner.delete ( k)
4133
}
4134
fn read_ref (
4135
& self ,
4136
k : & str ,
4137
) -> crate:: strata:: Result< Option< ( Vec< u8 > , crate:: strata:: Version) > > {
4138
self .count ( if k = = JOURNAL_KEY {
4139
" read_journal"
4140
} else {
4141
" read_ref"
4142
} ) ;
4143
self .inner.read_ref ( k)
4144
}
4145
fn write_ref (
4146
& self ,
4147
k : & str ,
4148
b : & [u8 ],
4149
e : Option< & crate:: strata:: Version> ,
4150
) -> crate:: strata:: Result< crate:: strata:: Version> {
4151
self .count ( " write_ref" ) ;
4152
if k = = JOURNAL_KEY & & self .interfere.swap ( false , Ordering:: SeqCst) {
4153
let ( mut m, v) = match self .inner.read_ref ( k) ? {
4154
Some ( ( bytes, v) ) => ( parse_retired ( & bytes) , Some ( v) ) ,
4155
None => ( Default :: default( ) , None ) ,
4156
} ;
4157
m.insert (
4158
format! ( " seal/{} " , " c" .repeat ( 64 ) ) + " /" + & " d" .repeat ( 64 ) ,
4159
0 ,
4160
) ;
4161
self .inner.write_ref ( k, & encode_retired ( & m) , v.as_ref ( ) ) ? ;
4162
}
4163
self .inner.write_ref ( k, b, e)
4164
}
4165
}
4166
4167
4168
fn is_legacy ( k : & str ) -> bool {
4169
ENTRY_INDEXES
4170
.iter ( )
4171
.any ( | ( _, legacy ) | k.starts_with ( & format! ( " {legacy} /" ) ) )
4172
}
4173
4174
struct Fixture {
4175
backend : Arc< Counted> ,
4176
dir : tempfile:: TempDir,
4177
handles : std:: cell:: Cell< usize > ,
4178
}
4179
4180
impl Fixture {
4181
fn new ( ) -> Fixture {
4182
Fixture {
4183
backend: Arc:: new( Counted:: default( ) ) ,
4184
dir: tempfile:: tempdir( ) .unwrap ( ) ,
4185
handles: Default :: default( ) ,
4186
}
4187
}
4188
4189
fn open ( & self ) -> Store {
4190
let n = self .handles.get ( ) + 1 ;
4191
self .handles.set ( n) ;
4192
Store:: open_on( self .backend.clone ( ) , self .dir.path ( ) .join ( format! ( " s{n} " ) ) ) .unwrap ( )
4193
}
4194
}
4195
4196
fn signer ( n : u8 ) -> SecretKey {
4197
SecretKey {
4198
ed_seed: [ n; 32 ] ,
4199
ml_seed: [ n + 100 ; 32 ] ,
4200
}
4201
}
4202
4203
fn sign ( s : & Store, r : & ObjectRef, n : u8 ) -> Signature {
4204
let sk = signer ( n) ;
4205
let key = s.put_identity ( & sk.identity ( " a" , " b" , 0 ) ) .unwrap ( ) ;
4206
let sig = sk.sign ( Domain:: Change, & key, r) ;
4207
s.put_signature ( r, & sig) .unwrap ( ) ;
4208
sig
4209
}
4210
4211
fn journal ( s : & Store) -> std:: collections:: BTreeMap< String, u64 > {
4212
s.read_record ( JOURNAL_KEY ) .unwrap ( ) .0
4213
}
4214
4215
fn fold ( s : & Store) -> bool {
4216
s.fold_entries ( & mut silent ( ) ) .unwrap ( )
4217
}
4218
4219
4220
fn old_writer_signs ( f : & Fixture, r : & ObjectRef, n : u8 ) -> Signature {
4221
let sk = signer ( n) ;
4222
let sig = sk.sign ( Domain:: Change, & ObjectRef( [ n; 32 ] ) , r) ;
4223
f.backend
4224
.put_new (
4225
& format! ( " {} {} " , fanout_prefix ( " sig" , r) , sig.key.to_hex ( ) ) ,
4226
& Signature:: encode_list( std:: slice:: from_ref( & sig) ) ,
4227
)
4228
.unwrap ( ) ;
4229
sig
4230
}
4231
4232
4233
4234
4235
# [ test ]
4236
fn an_entry_written_after_a_fold_is_found_through_the_journal ( ) {
4237
let f = Fixture:: new( ) ;
4238
let w = f.open ( ) ;
4239
let r1 = w.put ( ObjectType:: Chunk, b " one" ) .unwrap ( ) ;
4240
let s1 = sign ( & w, & r1, 1 ) ;
4241
assert! ( fold ( & w) ) ;
4242
assert! ( ! fold ( & w) , " nothing new: no second list" ) ;
4243
4244
let early = f.open ( ) ;
4245
assert_eq! ( early.signatures ( & r1) .unwrap ( ) , vec! [ s1.clone ( ) ] ) ;
4246
4247
let w2 = f.open ( ) ;
4248
let r2 = w2.put ( ObjectType:: Chunk, b " two" ) .unwrap ( ) ;
4249
let s2 = sign ( & w2, & r2, 2 ) ;
4250
w2.index_seal ( & r2, & ObjectRef( [ 9 ; 32 ] ) ) .unwrap ( ) ;
4251
w2.index_receipt ( & r2, & ObjectRef( [ 8 ; 32 ] ) ) .unwrap ( ) ;
4252
4253
assert_eq! ( w2.signatures ( & r2) .unwrap ( ) , vec! [ s2.clone ( ) ] ) ;
4254
4255
let later = f.open ( ) ;
4256
f.backend.reset ( ) ;
4257
assert_eq! ( later.signatures ( & r1) .unwrap ( ) , vec! [ s1] ) ;
4258
assert_eq! ( later.signatures ( & r2) .unwrap ( ) , vec! [ s2.clone ( ) ] ) ;
4259
assert_eq! ( later.seals_for ( & r2) .unwrap ( ) , vec! [ ObjectRef( [ 9 ; 32 ] ) ] ) ;
4260
assert_eq! ( later.receipts_for ( & r2) .unwrap ( ) , vec! [ ObjectRef( [ 8 ; 32 ] ) ] ) ;
4261
assert_eq! ( later.receipt_states ( ) .unwrap ( ) , vec! [ r2] ) ;
4262
assert! ( later.seals_for ( & r1) .unwrap ( ) .is_empty ( ) ) ;
4263
assert_eq! ( f.backend.n ( " list" ) , 0 , " {}" , f.backend.summary ( ) ) ;
4264
assert_eq! ( f.backend.n ( " read_journal" ) , 1 , " {}" , f.backend.summary ( ) ) ;
4265
4266
4267
4268
assert! ( early.signatures ( & r2) .unwrap ( ) .is_empty ( ) ) ;
4269
early.refresh ( ) .unwrap ( ) ;
4270
assert_eq! ( early.signatures ( & r2) .unwrap ( ) , vec! [ s2] ) ;
4271
}
4272
4273
4274
4275
4276
4277
# [ test ]
4278
fn a_fold_keeps_the_journal_for_the_hour_readers_may_need_it ( ) {
4279
let f = Fixture:: new( ) ;
4280
let w = f.open ( ) ;
4281
let r1 = w.put ( ObjectType:: Chunk, b " one" ) .unwrap ( ) ;
4282
let s1 = sign ( & w, & r1, 1 ) ;
4283
assert! ( fold ( & w) ) ;
4284
let r2 = w.put ( ObjectType:: Chunk, b " two" ) .unwrap ( ) ;
4285
let s2 = sign ( & w, & r2, 2 ) ;
4286
assert! ( journal ( & w) .values ( ) .any ( | t | * t = = 0 ) ) ;
4287
4288
4289
let stale = f.open ( ) ;
4290
let stale_after_expiry = f.open ( ) ;
4291
assert! ( fold ( & w) ) ;
4292
assert! (
4293
journal ( & w) .values ( ) .all ( | t | * t ! = 0 ) ,
4294
" every line is marked folded"
4295
) ;
4296
assert! ( journal ( & w) .len ( ) > = 2 , " and kept" ) ;
4297
assert_eq! ( stale.signatures ( & r1) .unwrap ( ) , vec! [ s1.clone ( ) ] ) ;
4298
assert_eq! ( stale.signatures ( & r2) .unwrap ( ) , vec! [ s2.clone ( ) ] ) ;
4299
4300
4301
4302
reader_tests:: age_retired( & w, RETIRED_FOR * 2 ) ;
4303
w.update_record ( JOURNAL_KEY , " test" , | m | {
4304
for t in m.values_mut ( ) {
4305
* t = t.saturating_sub ( 2 * RETIRED_FOR .as_millis ( ) as u64 ) ;
4306
}
4307
} )
4308
.unwrap ( ) ;
4309
w.expire_retired ( RETIRED_FOR , & mut silent ( ) ) .unwrap ( ) ;
4310
let lists: Vec< String> = f
4311
.backend
4312
.inner
4313
.list ( " pack-" )
4314
.unwrap ( )
4315
.into_iter ( )
4316
.map ( | e | e.key )
4317
.filter ( | k | is_entry_list ( k) )
4318
.collect ( ) ;
4319
assert_eq! ( lists.len ( ) , 1 , " the replaced list is deleted: {lists:?}" ) ;
4320
let r3 = w.put ( ObjectType:: Chunk, b " three" ) .unwrap ( ) ;
4321
let s3 = sign ( & w, & r3, 3 ) ;
4322
let j = journal ( & w) ;
4323
assert_eq! ( j.len ( ) , 1 , " only the new line is left: {j:?}" ) ;
4324
assert! ( j.keys ( ) .all ( | k | k.starts_with ( & fanout_prefix ( " sig" , & r3) ) ) ) ;
4325
4326
4327
assert_eq! (
4328
stale_after_expiry.signatures ( & r1) .unwrap ( ) ,
4329
vec! [ s1.clone ( ) ]
4330
) ;
4331
assert_eq! (
4332
stale_after_expiry.signatures ( & r3) .unwrap ( ) ,
4333
vec! [ s3.clone ( ) ]
4334
) ;
4335
let fresh = f.open ( ) ;
4336
f.backend.reset ( ) ;
4337
assert_eq! ( fresh.signatures ( & r1) .unwrap ( ) , vec! [ s1] ) ;
4338
assert_eq! ( fresh.signatures ( & r2) .unwrap ( ) , vec! [ s2] ) ;
4339
assert_eq! ( fresh.signatures ( & r3) .unwrap ( ) , vec! [ s3] ) ;
4340
assert_eq! ( f.backend.n ( " list" ) , 0 ) ;
4341
}
4342
4343
4344
4345
4346
4347
# [ test ]
4348
fn an_old_layout_store_reads_before_and_after_its_first_fold ( ) {
4349
let f = Fixture:: new( ) ;
4350
let w = f.open ( ) ;
4351
let r1 = w.put ( ObjectType:: Chunk, b " one" ) .unwrap ( ) ;
4352
let r2 = w.put ( ObjectType:: Chunk, b " two" ) .unwrap ( ) ;
4353
let s1 = old_writer_signs ( & f, & r1, 1 ) ;
4354
let s2 = SecretKey {
4355
ed_seed: [ 2 ; 32 ] ,
4356
ml_seed: [ 3 ; 32 ] ,
4357
}
4358
.sign ( Domain:: Change, & ObjectRef( [ 2 ; 32 ] ) , & r2) ;
4359
f.backend
4360
.put_new (
4361
& legacy_key ( " sigs" , & r2) ,
4362
& Signature:: encode_list( std:: slice:: from_ref( & s2) ) ,
4363
)
4364
.unwrap ( ) ;
4365
f.backend
4366
.put_new (
4367
& format! ( " {} {} " , fanout_prefix ( " seal" , & r1) , " ab" .repeat ( 32 ) ) ,
4368
b " " ,
4369
)
4370
.unwrap ( ) ;
4371
f.backend
4372
.put_new (
4373
& legacy_key ( " receipts" , & r2) ,
4374
format! ( " {} \n " , ObjectRef( [ 7 ; 32 ] ) .to_hex ( ) ) .as_bytes ( ) ,
4375
)
4376
.unwrap ( ) ;
4377
let check = | s : & Store| {
4378
assert_eq! ( s.signatures ( & r1) .unwrap ( ) , vec! [ s1.clone ( ) ] ) ;
4379
assert_eq! ( s.signatures ( & r2) .unwrap ( ) , vec! [ s2.clone ( ) ] ) ;
4380
assert_eq! ( s.seals_for ( & r1) .unwrap ( ) , vec! [ ObjectRef( [ 0xab ; 32 ] ) ] ) ;
4381
assert_eq! ( s.receipts_for ( & r2) .unwrap ( ) , vec! [ ObjectRef( [ 7 ; 32 ] ) ] ) ;
4382
assert_eq! ( s.receipt_states ( ) .unwrap ( ) , vec! [ r2] ) ;
4383
} ;
4384
let reader = f.open ( ) ;
4385
assert! ( ! reader.folded.get ( ) ) ;
4386
check ( & reader) ;
4387
assert! ( f.backend.inner.read_ref ( JOURNAL_KEY ) .unwrap ( ) .is_none ( ) ) ;
4388
4389
assert! ( fold ( & w) ) ;
4390
let reader = f.open ( ) ;
4391
assert! ( reader.folded.get ( ) ) ;
4392
check ( & reader) ;
8156967b Andy McCall 16 days ago ↶
4393
4394
4395
4396
assert! ( f.backend.inner.has ( LEGACY_FOLDED_KEY ) .unwrap ( ) ) ;
4397
assert! ( f
4398
.backend
4399
.inner
4400
.has ( & format! ( " {} {} " , fanout_prefix ( " sig" , & r2) , s2.key.to_hex ( ) ) )
4401
.unwrap ( ) ) ;
4402
assert! ( f
4403
.backend
4404
.inner
4405
.has ( & format! (
4406
" {} {} " ,
4407
fanout_prefix ( " receipt" , & r2) ,
4408
ObjectRef( [ 7 ; 32 ] ) .to_hex ( )
4409
) )
4410
.unwrap ( ) ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
4411
4412
4413
let r3 = w.put ( ObjectType:: Chunk, b " three" ) .unwrap ( ) ;
4414
let s3 = old_writer_signs ( & f, & r3, 3 ) ;
4415
assert! ( f.open ( ) .signatures ( & r3) .unwrap ( ) .is_empty ( ) ) ;
4416
assert! ( fold ( & w) ) ;
4417
assert_eq! ( f.open ( ) .signatures ( & r3) .unwrap ( ) , vec! [ s3] ) ;
4418
}
4419
4420
4421
4422
# [ test ]
4423
fn concurrent_journal_appends_lose_nothing ( ) {
4424
let f = Fixture:: new( ) ;
4425
4426
let w = f.open ( ) ;
4427
f.backend.interfere.store ( true , Ordering:: SeqCst) ;
4428
w.index_seal ( & ObjectRef( [ 1 ; 32 ] ) , & ObjectRef( [ 2 ; 32 ] ) )
4429
.unwrap ( ) ;
4430
let j = journal ( & w) ;
4431
assert_eq! ( j.len ( ) , 2 , " the competitor's line and ours: {j:?}" ) ;
4432
4433
let backend: Arc< Backend> = f.backend.clone ( ) ;
4434
std:: thread:: scope( | scope | {
4435
for t in 0 .. 8 u8 {
4436
let backend = backend.clone ( ) ;
4437
let dir = f.dir.path ( ) .join ( format! ( " t{t} " ) ) ;
4438
scope.spawn ( move | | {
4439
let s = Store:: open_on( backend, dir) .unwrap ( ) ;
4440
for i in 0 .. 25 u8 {
4441
s.index_seal ( & ObjectRef( [ t + 10 ; 32 ] ) , & ObjectRef( [ i; 32 ] ) )
4442
.unwrap ( ) ;
4443
}
4444
} ) ;
4445
}
4446
} ) ;
4447
assert_eq! ( journal ( & w) .len ( ) , 2 + 8 * 25 ) ;
4448
assert! ( fold ( & w) ) ;
4449
let r = f.open ( ) ;
4450
for t in 0 .. 8 u8 {
4451
assert_eq! ( r.seals_for ( & ObjectRef( [ t + 10 ; 32 ] ) ) .unwrap ( ) .len ( ) , 25 ) ;
4452
}
4453
}
4454
4455
4456
4457
# [ test ]
4458
fn a_long_journal_is_folded_into_a_partial_list ( ) {
4459
let f = Fixture:: new( ) ;
4460
let w = f.open ( ) ;
4461
assert! ( fold ( & w) , " folded, with nothing yet" ) ;
4462
let key = ObjectRef( [ 5 ; 32 ] ) ;
4463
f.backend.reset ( ) ;
4464
let batch = w.begin_batch ( ) .unwrap ( ) ;
4465
for i in 0 .. = JOURNAL_FOLD_AT as u32 {
4466
let mut v = [ 0 u8 ; 32 ] ;
4467
v[ .. 4 ] .copy_from_slice ( & i.to_le_bytes ( ) ) ;
4468
w.index_seal ( & key, & ObjectRef( v) ) .unwrap ( ) ;
4469
}
4470
assert_eq! ( f.backend.n ( " write_ref" ) , 0 , " nothing until the flush" ) ;
4471
batch.finish ( ) .unwrap ( ) ;
4472
let parts = f
4473
.backend
4474
.inner
4475
.list ( " pack-" )
4476
.unwrap ( )
4477
.into_iter ( )
4478
.filter ( | e | e.key.ends_with ( PART_SUFFIX ) )
4479
.count ( ) ;
4480
assert_eq! ( parts, 1 ) ;
4481
assert! ( journal ( & w) .values ( ) .all ( | t | * t ! = 0 ) , " all folded" ) ;
4482
let r = f.open ( ) ;
4483
assert_eq! ( r.seals_for ( & key) .unwrap ( ) .len ( ) , JOURNAL_FOLD_AT + 1 ) ;
4484
4485
assert! ( fold ( & w) ) ;
4486
let lists: Vec< String> = f.open ( ) .entry_lists.borrow ( ) .clone ( ) ;
4487
assert_eq! ( lists.len ( ) , 1 ) ;
4488
assert! ( lists[ 0 ] .ends_with ( LIST_SUFFIX ) ) ;
4489
assert_eq! ( f.open ( ) .seals_for ( & key) .unwrap ( ) .len ( ) , JOURNAL_FOLD_AT + 1 ) ;
4490
}
4491
4492
4493
4494
# [ test ]
4495
fn pruned_objects_leave_the_journal ( ) {
4496
let f = Fixture:: new( ) ;
4497
let w = f.open ( ) ;
4498
let gone = w.put ( ObjectType:: Chunk, b " gone" ) .unwrap ( ) ;
4499
let kept = w.put ( ObjectType:: Chunk, b " kept" ) .unwrap ( ) ;
4500
sign ( & w, & gone, 1 ) ;
4501
let s = sign ( & w, & kept, 2 ) ;
4502
assert! ( fold ( & w) ) ;
4503
let keep: std:: collections:: HashSet< ObjectRef> = w
4504
.list ( )
4505
.unwrap ( )
4506
.into_iter ( )
4507
.filter ( | r | * r ! = gone)
4508
.collect ( ) ;
4509
w.prune ( & keep, std:: time:: Duration:: ZERO ) .unwrap ( ) ;
4510
assert! ( journal ( & w) .keys ( ) .all ( | k | ! k.contains ( & gone.to_hex ( ) [ 2 .. ] ) ) ) ;
4511
fold ( & w) ;
4512
let r = f.open ( ) ;
4513
assert! ( r.signatures ( & gone) .unwrap ( ) .is_empty ( ) ) ;
4514
assert_eq! ( r.signatures ( & kept) .unwrap ( ) , vec! [ s] ) ;
4515
let all = r.with_entries ( | e | e.clone ( ) ) .unwrap ( ) .unwrap ( ) ;
4516
assert! (
4517
all.iter ( ) .all ( | k | ! k.contains ( & gone.to_hex ( ) [ 2 .. ] ) ) ,
4518
" {all:?}"
4519
) ;
4520
}
4521
4522
4523
4524
4525
# [ test ]
4526
fn a_folded_store_looks_up_entries_without_listing ( ) {
4527
let f = Fixture:: new( ) ;
4528
let w = f.open ( ) ;
4529
let refs: Vec< ObjectRef> = ( 0 .. 20 )
4530
.map ( | i | {
4531
w.put ( ObjectType:: Chunk, format! ( " o {i} " ) .as_bytes ( ) )
4532
.unwrap ( )
4533
} )
4534
.collect ( ) ;
4535
for r in & refs[ .. 5 ] {
4536
sign ( & w, r, 1 ) ;
4537
}
4538
let lookups = | s : & Store| {
4539
for r in & refs {
4540
s.signatures ( r) .unwrap ( ) ;
4541
s.seals_for ( r) .unwrap ( ) ;
4542
}
4543
} ;
4544
let before = f.open ( ) ;
4545
f.backend.reset ( ) ;
4546
lookups ( & before) ;
4547
let ( before_total, before_list) = ( f.backend.total ( ) , f.backend.n ( " list" ) ) ;
4548
eprintln! ( " 40 lookups before the fold: {}" , f.backend.summary ( ) ) ;
4549
4550
assert! ( fold ( & w) ) ;
4551
let after = f.open ( ) ;
4552
f.backend.reset ( ) ;
4553
lookups ( & after) ;
4554
eprintln! ( " 40 lookups after the fold: {}" , f.backend.summary ( ) ) ;
4555
assert_eq! ( before_list, 40 ) ;
4556
assert_eq! ( f.backend.n ( " list" ) , 0 ) ;
8156967b Andy McCall 16 days ago ↶
4557
assert_eq! ( f.backend.n ( " get_legacy" ) , 0 , " the older lists are folded" ) ;
ef7d4ea6 Andy McCall 16 days ago ↶
4558
assert_eq! ( f.backend.n ( " read_journal" ) , 1 ) ;
4559
assert! (
8156967b Andy McCall 16 days ago ↶
4560
f.backend.total ( ) < before_total / 10 ,
ef7d4ea6 Andy McCall 16 days ago ↶
4561
" {}" ,
4562
f.backend.summary ( )
4563
) ;
8156967b Andy McCall 16 days ago ↶
4564
}
4565
4566
4567
4568
4569
# [ test ]
4570
fn the_legacy_marker_stops_reads_of_the_older_lists ( ) {
4571
let f = Fixture:: new( ) ;
4572
let w = f.open ( ) ;
4573
let r = w.put ( ObjectType:: Chunk, b " old" ) .unwrap ( ) ;
4574
let sig = SecretKey {
4575
ed_seed: [ 4 ; 32 ] ,
4576
ml_seed: [ 5 ; 32 ] ,
4577
}
4578
.sign ( Domain:: Change, & ObjectRef( [ 4 ; 32 ] ) , & r) ;
4579
f.backend
4580
.put_new (
4581
& legacy_key ( " sigs" , & r) ,
4582
& Signature:: encode_list( std:: slice:: from_ref( & sig) ) ,
4583
)
4584
.unwrap ( ) ;
4585
for ( legacy, v) in [ ( " seals" , 9 u8 ) , ( " certs" , 8 ) , ( " accepted-lists" , 6 ) ] {
4586
f.backend
4587
.put_new (
4588
& legacy_key ( legacy, & r) ,
4589
format! ( " {} \n " , ObjectRef( [ v; 32 ] ) .to_hex ( ) ) .as_bytes ( ) ,
4590
)
4591
.unwrap ( ) ;
4592
}
4593
let check = | s : & Store| {
4594
assert_eq! ( s.signatures ( & r) .unwrap ( ) , vec! [ sig.clone ( ) ] ) ;
4595
assert_eq! ( s.seals_for ( & r) .unwrap ( ) , vec! [ ObjectRef( [ 9 ; 32 ] ) ] ) ;
4596
assert_eq! (
4597
s.index_get ( " cert" , " certs" , & r) .unwrap ( ) ,
4598
vec! [ ObjectRef( [ 8 ; 32 ] ) ]
4599
) ;
4600
assert_eq! (
4601
s.index_get_pub ( " accepted" , & r) .unwrap ( ) ,
4602
vec! [ ObjectRef( [ 6 ; 32 ] ) ]
4603
) ;
4604
} ;
4605
let before = f.open ( ) ;
4606
f.backend.reset ( ) ;
4607
check ( & before) ;
4608
assert_eq! ( f.backend.n ( " get_legacy" ) , 4 , " {}" , f.backend.summary ( ) ) ;
4609
4610
assert! ( fold ( & w) ) ;
4611
let folded = f.open ( ) ;
4612
f.backend.reset ( ) ;
4613
check ( & folded) ;
4614
assert_eq! ( f.backend.n ( " get_legacy" ) + f.backend.n ( " list" ) , 0 ) ;
4615
4616
4617
4618
for e in f.backend.inner.list ( " pack-" ) .unwrap ( ) {
4619
if is_entry_list ( & e.key) {
4620
f.backend.inner.delete ( & e.key) .unwrap ( ) ;
4621
}
4622
}
4623
let marked = f.open ( ) ;
4624
assert! ( ! marked.folded.get ( ) & & marked.legacy_folded.get ( ) ) ;
4625
f.backend.reset ( ) ;
4626
check ( & marked) ;
4627
assert_eq! ( f.backend.n ( " get_legacy" ) , 0 , " {}" , f.backend.summary ( ) ) ;
4628
assert_eq! ( f.backend.n ( " list" ) , 4 ) ;
771661aa Andy McCall 16 days ago ↶
4629
}
4630
4631
4632
4633
4634
# [ test ]
4635
fn a_long_lived_handle_sees_new_entries_within_the_interval ( ) {
4636
let f = Fixture:: new( ) ;
4637
let w = f.open ( ) ;
4638
let r1 = w.put ( ObjectType:: Chunk, b " one" ) .unwrap ( ) ;
4639
let s1 = sign ( & w, & r1, 1 ) ;
4640
assert! ( fold ( & w) ) ;
4641
let a = f.open ( ) ;
4642
assert_eq! ( a.signatures ( & r1) .unwrap ( ) , vec! [ s1] ) ;
4643
4644
let b = f.open ( ) ;
4645
let r2 = b.put ( ObjectType:: Chunk, b " two" ) .unwrap ( ) ;
4646
let s2 = sign ( & b, & r2, 2 ) ;
4647
b.index_approval ( & r2, & ObjectRef( [ 3 ; 32 ] ) ) .unwrap ( ) ;
4648
4649
assert! ( a.signatures ( & r2) .unwrap ( ) .is_empty ( ) ) ;
4650
4651
4652
let t = a.entries_read.get ( ) .unwrap ( ) ;
4653
a.entries_read.set ( t.checked_sub ( ENTRIES_FRESH ) ) ;
4654
f.backend.reset ( ) ;
4655
assert_eq! ( a.signatures ( & r2) .unwrap ( ) , vec! [ s2] ) ;
4656
assert_eq! ( a.approvals_for ( & r2) .unwrap ( ) , vec! [ ObjectRef( [ 3 ; 32 ] ) ] ) ;
4657
assert_eq! ( f.backend.n ( " read_journal" ) , 1 , " {}" , f.backend.summary ( ) ) ;
4658
assert_eq! ( f.backend.n ( " list_packs" ) , 1 , " {}" , f.backend.summary ( ) ) ;
4659
assert_eq! ( f.backend.n ( " list" ) , 0 , " {}" , f.backend.summary ( ) ) ;
4660
assert_eq! (
4661
f.backend.n ( " get" ) ,
4662
1 ,
4663
" the signature; the list already read is not read again: {}" ,
4664
f.backend.summary ( )
4665
) ;
8f10a07a Andy McCall 1 month ago ↶
4666
}
ff0af1ee unknown 1 month ago
4667
}