d02e545d Andy McCall 1 month ago ↶
1
2
3
4
5
6
7
8
9
ff0af1ee unknown 1 month ago
10
5b9c6ad4 Andy McCall 1 month ago ↶
11
use crate :: attest:: Attest;
ff0af1ee unknown 1 month ago
12
use crate :: hash:: { hash_object, header, ObjectRef, ObjectType} ;
1983686f Andy McCall 1 month ago ↶
13
use crate :: identity:: { Identity, Signature} ;
6f8aeb99 Andy McCall 1 month ago ↶
14
use crate :: objects:: { Blob, Change, ObjectError, StateObject} ;
fc1a466a Andy McCall 1 month ago ↶
15
use crate :: receipt:: Receipt;
ff0af1ee unknown 1 month ago
16
use rand:: RngCore;
d02e545d Andy McCall 1 month ago ↶
17
use std:: cell:: RefCell;
ff0af1ee unknown 1 month ago
18
use std:: fs;
d02e545d Andy McCall 1 month ago ↶
19
use std:: io:: { self , Read, Seek, SeekFrom, Write} ;
ff0af1ee unknown 1 month ago
20
use std:: path:: { Path, PathBuf} ;
21
d02e545d Andy McCall 1 month ago ↶
22
const PACK_MAGIC : & [ u8 ; 8 ] = b " OXYPACK1" ;
23
const IDX_MAGIC : & [ u8 ; 8 ] = b " OXYIDX01" ;
24
const IDX_ENTRY : usize = 32 + 8 + 4 + 4 + 1 + 1 ;
25
const FLAG_ZSTD : u8 = 1 ;
a17fc622 Andy McCall 1 month ago ↶
26
27
28
29
const FLAG_DICT : u8 = 2 ;
30
31
32
const DICT_BYTES : usize = 110 < < 10 ;
33
const DICT_MIN_OBJECTS : usize = 1000 ;
34
35
const DICT_OBJECT_MAX : usize = 64 < < 10 ;
d02e545d Andy McCall 1 month ago ↶
36
const ZSTD_LEVEL : i32 = 3 ;
da652d63 Andy McCall 1 month ago ↶
37
38
pub const REPACK_ZSTD_LEVEL : i32 = 9 ;
2b872d07 Andy McCall 1 month ago ↶
39
40
41
const MAX_OBJECT_LEN : u32 = 1 < < 30 ;
d02e545d Andy McCall 1 month ago ↶
42
afaba5f1 Andy McCall 1 month ago ↶
43
44
pub type Object = ( ObjectType, Vec< u8 > ) ;
45
d02e545d Andy McCall 1 month ago ↶
46
# [ derive ( Clone, Copy, Debug ) ]
47
struct PackEntry {
48
offset : u64 ,
49
stored_len : u32 ,
50
raw_len : u32 ,
51
ty : ObjectType,
52
flags : u8 ,
53
}
54
55
56
struct PackIndex {
57
path : PathBuf,
58
refs : Vec< ObjectRef> ,
59
entries : Vec< PackEntry> ,
a17fc622 Andy McCall 1 month ago ↶
60
61
dict : Option< std:: sync:: Arc< zstd:: dict:: DecoderDictionary< 'static > > > ,
d02e545d Andy McCall 1 month ago ↶
62
}
63
a17fc622 Andy McCall 1 month ago ↶
64
impl std:: fmt:: Debug for PackIndex {
65
fn fmt ( & self , f : & mut std:: fmt:: Formatter< '_ > ) -> std:: fmt:: Result {
66
f.debug_struct ( " PackIndex" )
67
.field ( " path" , & self .path)
68
.field ( " objects" , & self .refs.len ( ) )
69
.field ( " dict" , & self .dict.is_some ( ) )
70
.finish ( )
71
}
72
}
73
d02e545d Andy McCall 1 month ago ↶
74
impl PackIndex {
75
fn load ( idx_path : & Path, pack_path : & Path) -> Result< PackIndex> {
76
let data = fs:: read( idx_path) ? ;
75167672 Andy McCall 1 month ago
77
let bad =
78
| m : & str | StoreError:: Corrupt( ObjectRef:: ZERO , format! ( " {} : {m} " , idx_path.display ( ) ) ) ;
d02e545d Andy McCall 1 month ago ↶
79
if data.len ( ) < 12 | | & data[ .. 8 ] ! = IDX_MAGIC {
80
return Err ( bad ( " bad index header" ) ) ;
81
}
82
let count = u32 :: from_le_bytes( data[ 8 .. 12 ] .try_into ( ) .unwrap ( ) ) as usize ;
83
if data.len ( ) ! = 12 + count * IDX_ENTRY {
84
return Err ( bad ( " index length mismatch" ) ) ;
85
}
2b872d07 Andy McCall 1 month ago ↶
86
let pack_len = fs:: metadata( pack_path) ? .len ( ) ;
d02e545d Andy McCall 1 month ago ↶
87
let mut refs = Vec :: with_capacity( count) ;
88
let mut entries = Vec :: with_capacity( count) ;
89
for i in 0 .. count {
90
let e = & data[ 12 + i * IDX_ENTRY .. 12 + ( i + 1 ) * IDX_ENTRY ] ;
91
let r = ObjectRef:: from_slice( & e[ .. 32 ] ) .unwrap ( ) ;
92
if let Some ( prev) = refs.last ( ) {
93
if r < = * prev {
94
return Err ( bad ( " index not sorted" ) ) ;
95
}
96
}
97
refs.push ( r) ;
2b872d07 Andy McCall 1 month ago ↶
98
let entry = PackEntry {
d02e545d Andy McCall 1 month ago ↶
99
offset: u64 :: from_le_bytes( e[ 32 .. 40 ] .try_into ( ) .unwrap ( ) ) ,
100
stored_len: u32 :: from_le_bytes( e[ 40 .. 44 ] .try_into ( ) .unwrap ( ) ) ,
101
raw_len: u32 :: from_le_bytes( e[ 44 .. 48 ] .try_into ( ) .unwrap ( ) ) ,
75167672 Andy McCall 1 month ago
102
ty: ObjectType:: ALL
103
.get ( e[ 48 ] as usize )
104
.copied ( )
105
.ok_or_else ( | | bad ( " unknown object type" ) ) ? ,
d02e545d Andy McCall 1 month ago ↶
106
flags: e[ 49 ] ,
2b872d07 Andy McCall 1 month ago ↶
107
} ;
a9f686ed Andy McCall 1 month ago ↶
108
if entry.stored_len > MAX_OBJECT_LEN | | entry.raw_len > MAX_OBJECT_LEN {
109
return Err ( StoreError:: Corrupt(
110
r,
111
format! (
112
" {} : the index claims an object of {} bytes ({} stored), more than the {MAX_OBJECT_LEN} an object may be" ,
113
idx_path.display ( ) ,
114
entry.raw_len,
115
entry.stored_len
116
) ,
117
) ) ;
118
}
119
if entry.offset.saturating_add ( entry.stored_len as u64 ) > pack_len {
2b872d07 Andy McCall 1 month ago ↶
120
return Err ( bad ( " index entry points outside the pack" ) ) ;
121
}
122
entries.push ( entry) ;
d02e545d Andy McCall 1 month ago ↶
123
}
a17fc622 Andy McCall 1 month ago ↶
124
let dict = match fs:: read( pack_path.with_extension ( " dict" ) ) {
125
Ok ( d) => Some ( std:: sync:: Arc:: new( zstd:: dict:: DecoderDictionary:: copy( & d) ) ) ,
126
Err ( e) if e.kind ( ) = = io:: ErrorKind:: NotFound => None ,
127
Err ( e) => return Err ( e.into ( ) ) ,
128
} ;
75167672 Andy McCall 1 month ago
129
Ok ( PackIndex {
130
path: pack_path.to_path_buf ( ) ,
131
refs,
132
entries,
a17fc622 Andy McCall 1 month ago ↶
133
dict,
75167672 Andy McCall 1 month ago
134
} )
d02e545d Andy McCall 1 month ago ↶
135
}
136
137
fn find ( & self , r : & ObjectRef) -> Option< PackEntry> {
138
self .refs.binary_search ( r) .ok ( ) .map ( | i | self .entries[ i] )
139
}
140
141
fn read ( & self , r : & ObjectRef, e : PackEntry) -> Result< ( ObjectType, Vec< u8 > ) > {
142
let mut f = fs:: File:: open( & self .path) ? ;
143
f.seek ( SeekFrom:: Start( e.offset) ) ? ;
144
let mut stored = vec! [ 0 u8 ; e.stored_len as usize ] ;
145
f.read_exact ( & mut stored) ? ;
a17fc622 Andy McCall 1 month ago ↶
146
let body = if e.flags & FLAG_DICT ! = 0 {
147
let dict = self .dict.as_ref ( ) .ok_or_else ( | | {
148
StoreError:: Corrupt( * r, " packed with a dictionary the pack lacks" .into ( ) )
149
} ) ? ;
150
zstd:: bulk:: Decompressor:: with_prepared_dictionary( dict)
151
.and_then ( | mut d | d.decompress ( & stored, e.raw_len as usize ) )
152
.map_err ( | err | StoreError:: Corrupt( * r, format! ( " zstd: {err} " ) ) ) ?
153
} else if e.flags & FLAG_ZSTD ! = 0 {
75167672 Andy McCall 1 month ago
154
zstd:: bulk:: decompress( & stored, e.raw_len as usize )
155
.map_err ( | err | StoreError:: Corrupt( * r, format! ( " zstd: {err} " ) ) ) ?
d02e545d Andy McCall 1 month ago ↶
156
} else {
157
stored
158
} ;
159
if body.len ( ) ! = e.raw_len as usize | | hash_object ( e.ty, & body) ! = * r {
75167672 Andy McCall 1 month ago
160
return Err ( StoreError:: Corrupt(
161
* r,
162
" packed object does not match its reference" .into ( ) ,
163
) ) ;
d02e545d Andy McCall 1 month ago ↶
164
}
165
Ok ( ( e.ty, body) )
166
}
167
}
168
169
fn type_index ( ty : ObjectType) -> u8 {
170
ObjectType:: ALL .iter ( ) .position ( | t | * t = = ty) .unwrap ( ) as u8
171
}
172
173
174
# [ derive ( Debug, Clone, Default, PartialEq, Eq ) ]
175
pub struct PackReport {
176
pub objects : usize ,
177
pub raw_bytes : u64 ,
178
pub packed_bytes : u64 ,
179
}
180
135212de Andy McCall 1 month ago ↶
181
182
pub const MAX_PACKS : usize = 16 ;
183
ba160f60 Andy McCall 1 month ago ↶
184
185
# [ derive ( Debug, Clone, Default, PartialEq, Eq ) ]
186
pub struct PruneReport {
187
pub objects : usize ,
188
pub bytes : u64 ,
189
190
pub deferred : usize ,
191
}
192
ff0af1ee unknown 1 month ago
193
# [ derive ( Debug, thiserror::Error ) ]
194
pub enum StoreError {
195
# [ error ( " io: {0}" ) ]
196
Io( # [ from ] io:: Error) ,
197
# [ error ( " corrupt object {0}: {1}" ) ]
198
Corrupt( ObjectRef, String ) ,
199
# [ error ( " object {0}" ) ]
200
Object( # [ from ] ObjectError) ,
201
# [ error ( " object {0} is a {1}, expected {2}" ) ]
202
WrongType( ObjectRef, & 'static str , & 'static str ) ,
203
# [ error ( " object {0} not found" ) ]
204
NotFound( ObjectRef) ,
6f8aeb99 Andy McCall 1 month ago ↶
205
# [ 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 ↶
206
TooLarge {
207
kind: & 'static str ,
208
size: usize ,
209
limit: u32 ,
210
} ,
ff0af1ee unknown 1 month ago
211
}
212
213
pub type Result < T> = std:: result:: Result< T, StoreError> ;
214
d02e545d Andy McCall 1 month ago ↶
215
# [ derive ( Debug ) ]
ff0af1ee unknown 1 month ago
216
pub struct Store {
217
dir : PathBuf,
d02e545d Andy McCall 1 month ago ↶
218
packs : RefCell< Vec< PackIndex> > ,
8f10a07a Andy McCall 1 month ago ↶
219
220
221
pending : RefCell< Option< Pending> > ,
222
batch_depth : std:: cell:: Cell< u32 > ,
ce14f0d6 Andy McCall 1 month ago ↶
223
224
metas : RefCell< Option< crate:: fasthash:: FastMap< ObjectRef, crate:: state:: ChangeMeta> > > ,
8f10a07a Andy McCall 1 month ago ↶
225
}
226
227
228
229
230
# [ derive ( Debug ) ]
231
struct Pending {
232
buffered : Vec< ( ObjectType, Vec< u8 > ) > ,
233
buffered_bytes : usize ,
234
lookup : std:: collections:: HashMap< ObjectRef, PendingEntry> ,
235
pack : Option< PendingPack> ,
236
report : PackReport,
ff0af1ee unknown 1 month ago
237
}
238
8f10a07a Andy McCall 1 month ago ↶
239
# [ derive ( Debug, Clone, Copy ) ]
240
enum PendingEntry {
241
Buffered( usize ) ,
242
Packed( PackEntry) ,
243
}
244
245
# [ derive ( Debug ) ]
246
struct PendingPack {
247
id : String,
248
tmp_path : PathBuf,
249
writer : io:: BufWriter< fs:: File> ,
250
offset : u64 ,
251
index : Vec< ( ObjectRef, PackEntry) > ,
252
}
253
254
const SPILL_OBJECTS : usize = 256 ;
255
const SPILL_BYTES : usize = 8 < < 20 ;
256
257
258
pub struct Batch < 'a > {
259
store : & 'a Store,
260
done : bool ,
261
}
262
263
impl Batch < '_ > {
264
pub fn finish ( mut self ) -> Result< ( ) > {
265
self .done = true ;
266
self .store.finish_batch ( )
267
}
268
}
269
270
impl Drop for Batch < '_ > {
271
fn drop ( & mut self ) {
272
if ! self .done {
273
let _ = self .store.finish_batch ( ) ;
274
}
275
}
276
}
277
192fad1e Andy McCall 1 month ago ↶
278
279
fn write_pack_entry (
280
pack : & mut PendingPack,
281
r : & ObjectRef,
282
ty : ObjectType,
283
raw_len : usize ,
284
flags : u8 ,
285
stored : & [u8 ],
286
report : & mut PackReport,
287
) -> Result< PackEntry> {
288
let header_len = 1 + 1 + 4 + 4 + 32 ;
289
pack.writer.write_all ( & [ type_index ( ty) , flags] ) ? ;
290
pack.writer
291
.write_all ( & ( stored.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
292
pack.writer.write_all ( & ( raw_len as u32 ) .to_le_bytes ( ) ) ? ;
293
pack.writer.write_all ( & r.0 ) ? ;
294
pack.writer.write_all ( stored) ? ;
295
let entry = PackEntry {
296
offset: pack.offset + header_len,
297
stored_len: stored.len ( ) as u32 ,
298
raw_len: raw_len as u32 ,
299
ty,
300
flags,
301
} ;
302
pack.offset + = header_len + stored.len ( ) as u64 ;
303
pack.index.push ( ( * r, entry) ) ;
304
report.objects + = 1 ;
305
report.raw_bytes + = raw_len as u64 ;
306
report.packed_bytes + = stored.len ( ) as u64 ;
307
Ok ( entry)
308
}
309
ff0af1ee unknown 1 month ago
310
impl Store {
311
pub fn open ( dir : impl Into< PathBuf> ) -> io:: Result< Store> {
312
let dir = dir.into ( ) ;
313
fs:: create_dir_all( dir.join ( " loose" ) ) ? ;
75167672 Andy McCall 1 month ago
314
let store = Store {
315
dir,
316
packs: RefCell:: new( Vec :: new( ) ) ,
317
pending: RefCell:: new( None ) ,
318
batch_depth: std:: cell:: Cell:: new( 0 ) ,
ce14f0d6 Andy McCall 1 month ago ↶
319
metas: RefCell:: new( None ) ,
75167672 Andy McCall 1 month ago
320
} ;
321
store
322
.reload_packs ( )
323
.map_err ( | e | io:: Error:: other( e.to_string ( ) ) ) ? ;
d02e545d Andy McCall 1 month ago ↶
324
Ok ( store)
325
}
326
327
fn reload_packs ( & self ) -> Result< ( ) > {
328
let mut packs = Vec :: new( ) ;
329
let mut names: Vec< PathBuf> = fs:: read_dir( & self .dir) ?
330
.filter_map ( | e | e.ok ( ) .map ( | e | e.path ( ) ) )
75167672 Andy McCall 1 month ago
331
.filter ( | p | {
332
p.extension ( ) .is_some_and ( | x | x = = " idx" )
333
& & p.file_name ( )
334
.is_some_and ( | n | n.to_string_lossy ( ) .starts_with ( " pack-" ) )
335
} )
d02e545d Andy McCall 1 month ago ↶
336
.collect ( ) ;
337
names.sort ( ) ;
338
for idx in names {
339
let pack = idx.with_extension ( " pack" ) ;
340
if pack.is_file ( ) {
341
packs.push ( PackIndex:: load( & idx, & pack) ? ) ;
342
}
343
}
344
* self .packs.borrow_mut ( ) = packs;
345
Ok ( ( ) )
346
}
347
348
pub fn pack_count ( & self ) -> usize {
349
self .packs.borrow ( ) .len ( )
350
}
351
352
fn find_packed ( & self , r : & ObjectRef) -> Option< ( usize , PackEntry) > {
75167672 Andy McCall 1 month ago
353
self .packs
354
.borrow ( )
355
.iter ( )
356
.enumerate ( )
357
.find_map ( | ( i , p ) | p.find ( r) .map ( | e | ( i, e) ) )
d02e545d Andy McCall 1 month ago ↶
358
}
359
360
361
fn loose_objects ( & self ) -> io:: Result< Vec< ( ObjectRef, PathBuf) > > {
362
let mut out = Vec :: new( ) ;
363
let loose = self .dir.join ( " loose" ) ;
364
for d in fs:: read_dir( & loose) ? {
365
let d = d? ;
366
if ! d.file_type ( ) ? .is_dir ( ) {
367
continue ;
368
}
369
let prefix = d.file_name ( ) .to_string_lossy ( ) .to_string ( ) ;
370
for f in fs:: read_dir( d.path ( ) ) ? {
371
let f = f? ;
372
let name = f.file_name ( ) .to_string_lossy ( ) .to_string ( ) ;
373
if let Some ( r) = ObjectRef:: from_hex( & format! ( " {prefix} {name} " ) ) {
374
out.push ( ( r, f.path ( ) ) ) ;
375
}
376
}
377
}
378
out.sort ( ) ;
379
Ok ( out)
380
}
381
382
pub fn loose_count ( & self ) -> io:: Result< usize > {
383
Ok ( self .loose_objects ( ) ? .len ( ) )
384
}
385
386
387
388
pub fn pack_loose ( & self ) -> Result< PackReport> {
389
let loose = self .loose_objects ( ) ? ;
75167672 Andy McCall 1 month ago
390
self .write_pack (
391
& loose.iter ( ) .map ( | ( r , _) | * r) .collect:: < Vec< _ > > ( ) ,
392
& loose.iter ( ) .map ( | ( _, p ) | p.clone ( ) ) .collect:: < Vec< _ > > ( ) ,
393
& [ ] ,
da652d63 Andy McCall 1 month ago ↶
394
ZSTD_LEVEL ,
75167672 Andy McCall 1 month ago
395
)
da652d63 Andy McCall 1 month ago ↶
396
}
397
398
399
400
401
pub fn repack_all ( & self , level : i32 ) -> Result< ( PackReport, usize ) > {
402
let loose = self .loose_objects ( ) ? ;
403
let ( mut refs, paths) : ( Vec< ObjectRef> , Vec< PathBuf> ) = {
404
let packs = self .packs.borrow ( ) ;
405
(
406
packs.iter ( ) .flat_map ( | p | p.refs.iter ( ) .copied ( ) ) .collect ( ) ,
407
packs.iter ( ) .map ( | p | p.path.clone ( ) ) .collect ( ) ,
408
)
409
} ;
410
if loose.is_empty ( ) & & paths.len ( ) < = 1 & & level = = ZSTD_LEVEL {
411
return Ok ( ( PackReport:: default( ) , 0 ) ) ;
412
}
413
refs.extend ( loose.iter ( ) .map ( | ( r , _) | * r) ) ;
414
let loose_paths: Vec< PathBuf> = loose.into_iter ( ) .map ( | ( _, p ) | p ) .collect ( ) ;
415
let n = paths.len ( ) ;
416
let report = self .write_pack ( & refs, & loose_paths, & paths, level) ? ;
417
Ok ( ( report, n) )
ba160f60 Andy McCall 1 month ago ↶
418
}
419
135212de Andy McCall 1 month ago ↶
420
421
422
pub fn merge_packs ( & self ) -> Result< usize > {
423
let ( refs, paths) : ( Vec< ObjectRef> , Vec< PathBuf> ) = {
424
let packs = self .packs.borrow ( ) ;
425
if packs.len ( ) < = MAX_PACKS {
426
return Ok ( 0 ) ;
427
}
75167672 Andy McCall 1 month ago
428
(
429
packs.iter ( ) .flat_map ( | p | p.refs.iter ( ) .copied ( ) ) .collect ( ) ,
430
packs.iter ( ) .map ( | p | p.path.clone ( ) ) .collect ( ) ,
431
)
135212de Andy McCall 1 month ago ↶
432
} ;
433
let n = paths.len ( ) ;
da652d63 Andy McCall 1 month ago ↶
434
self .write_pack ( & refs, & [ ] , & paths, ZSTD_LEVEL ) ? ;
135212de Andy McCall 1 month ago ↶
435
Ok ( n)
436
}
437
ba160f60 Andy McCall 1 month ago ↶
438
439
440
441
442
75167672 Andy McCall 1 month ago
443
pub fn prune (
444
& self ,
445
keep : & std:: collections:: HashSet< ObjectRef> ,
446
grace : std:: time:: Duration,
447
) -> Result< PruneReport> {
ba160f60 Andy McCall 1 month ago ↶
448
let now = std:: time:: SystemTime:: now( ) ;
75167672 Andy McCall 1 month ago
449
let old_enough = | m : & fs:: Metadata| {
450
m.modified ( )
451
.map ( | t | now.duration_since ( t) .unwrap_or_default ( ) > = grace )
452
.unwrap_or ( true )
453
} ;
ba160f60 Andy McCall 1 month ago ↶
454
let mut report = PruneReport:: default( ) ;
455
456
for ( r, path) in self .loose_objects ( ) ? {
457
if keep.contains ( & r) {
458
continue ;
459
}
460
let meta = fs:: metadata( & path) ? ;
461
if ! old_enough ( & meta) {
462
report.deferred + = 1 ;
463
continue ;
464
}
465
report.bytes + = meta.len ( ) ;
466
report.objects + = 1 ;
467
fs:: remove_file( & path) ? ;
468
let _ = fs:: remove_dir( path.parent ( ) .unwrap ( ) ) ;
469
self .remove_sidecars ( & r) ? ;
470
}
471
472
let mut keep_refs: Vec< ObjectRef> = Vec :: new( ) ;
473
let mut old_paths: Vec< PathBuf> = Vec :: new( ) ;
474
let mut rewrite = false ;
475
for p in self .packs.borrow ( ) .iter ( ) {
476
let meta = fs:: metadata( & p.path) ? ;
477
let unreachable = p.refs.iter ( ) .filter ( | r | ! keep.contains ( r) ) .count ( ) ;
478
if unreachable = = 0 {
479
continue ;
480
}
481
if ! old_enough ( & meta) {
482
report.deferred + = unreachable;
483
continue ;
484
}
485
rewrite = true ;
486
old_paths.push ( p.path.clone ( ) ) ;
487
for ( r, e) in p.refs.iter ( ) .zip ( p.entries.iter ( ) ) {
488
if keep.contains ( r) {
489
keep_refs.push ( * r) ;
490
} else {
491
report.objects + = 1 ;
492
report.bytes + = e.stored_len as u64 ;
493
}
494
}
495
}
496
if rewrite {
497
let dropped: Vec< ObjectRef> = {
498
let packs = self .packs.borrow ( ) ;
75167672 Andy McCall 1 month ago
499
packs
500
.iter ( )
501
.filter ( | p | old_paths.contains ( & p.path) )
502
.flat_map ( | p | p.refs.iter ( ) .copied ( ) )
503
.filter ( | r | ! keep.contains ( r) )
504
.collect ( )
ba160f60 Andy McCall 1 month ago ↶
505
} ;
da652d63 Andy McCall 1 month ago ↶
506
self .write_pack ( & keep_refs, & [ ] , & old_paths, ZSTD_LEVEL ) ? ;
ba160f60 Andy McCall 1 month ago ↶
507
for r in dropped {
508
self .remove_sidecars ( & r) ? ;
509
}
510
}
511
Ok ( report)
512
}
513
514
fn remove_sidecars ( & self , r : & ObjectRef) -> Result< ( ) > {
fc1a466a Andy McCall 1 month ago ↶
515
let sidecars = [
516
self .sig_path ( r) ,
517
self .index_path ( " seals" , r) ,
518
self .index_path ( " receipts" , r) ,
519
] ;
520
for path in sidecars {
ba160f60 Andy McCall 1 month ago ↶
521
match fs:: remove_file( & path) {
522
Ok ( ( ) ) => {
523
let _ = fs:: remove_dir( path.parent ( ) .unwrap ( ) ) ;
524
}
525
Err ( e) if e.kind ( ) = = io:: ErrorKind:: NotFound => { }
526
Err ( e) => return Err ( e.into ( ) ) ,
527
}
528
}
529
Ok ( ( ) )
530
}
531
532
8f10a07a Andy McCall 1 month ago ↶
533
534
75167672 Andy McCall 1 month ago
535
fn finish_pack_files (
536
& self ,
537
id : & str ,
538
tmp_pack : & Path,
539
index : & [( ObjectRef , PackEntry ) ],
540
) -> Result< ( ) > {
8f10a07a Andy McCall 1 month ago ↶
541
let pack_path = self .dir.join ( format! ( " pack-{id} .pack" ) ) ;
542
let idx_path = self .dir.join ( format! ( " pack-{id} .idx" ) ) ;
543
let tmp_idx = self .dir.join ( format! ( " tmp-{id} .idx" ) ) ;
544
{
545
let mut f = io:: BufWriter:: new( fs:: File:: create( & tmp_idx) ? ) ;
546
f.write_all ( IDX_MAGIC ) ? ;
547
f.write_all ( & ( index.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
548
for ( r, e) in index {
549
f.write_all ( & r.0 ) ? ;
550
f.write_all ( & e.offset.to_le_bytes ( ) ) ? ;
551
f.write_all ( & e.stored_len.to_le_bytes ( ) ) ? ;
552
f.write_all ( & e.raw_len.to_le_bytes ( ) ) ? ;
553
f.write_all ( & [ type_index ( e.ty) , e.flags] ) ? ;
554
}
555
f.flush ( ) ? ;
556
f.get_ref ( ) .sync_all ( ) ? ;
557
}
4dcb8c09 Andy McCall 1 month ago ↶
558
559
crate :: durable:: rename( tmp_pack, & pack_path) ? ;
560
crate :: durable:: rename( & tmp_idx, & idx_path) ? ;
8f10a07a Andy McCall 1 month ago ↶
561
self .reload_packs ( )
562
}
563
75167672 Andy McCall 1 month ago
564
fn write_pack (
565
& self ,
566
refs : & [ObjectRef],
567
loose_paths : & [PathBuf],
568
old_packs : & [PathBuf],
da652d63 Andy McCall 1 month ago ↶
569
level : i32 ,
75167672 Andy McCall 1 month ago
570
) -> Result< PackReport> {
ba160f60 Andy McCall 1 month ago ↶
571
if refs.is_empty ( ) {
572
for p in old_packs {
a17fc622 Andy McCall 1 month ago ↶
573
remove_pack_files ( p) ? ;
ba160f60 Andy McCall 1 month ago ↶
574
}
575
self .reload_packs ( ) ? ;
d02e545d Andy McCall 1 month ago ↶
576
return Ok ( PackReport:: default( ) ) ;
577
}
ba160f60 Andy McCall 1 month ago ↶
578
let mut refs: Vec< ObjectRef> = refs.to_vec ( ) ;
579
refs.sort ( ) ;
580
refs.dedup ( ) ;
d02e545d Andy McCall 1 month ago ↶
581
let mut nonce = [ 0 u8 ; 8 ] ;
582
rand:: rngs:: OsRng.fill_bytes ( & mut nonce) ;
583
let id = hex:: encode( nonce) ;
584
let tmp_pack = self .dir.join ( format! ( " tmp-{id} .pack" ) ) ;
585
let mut report = PackReport:: default( ) ;
ba160f60 Andy McCall 1 month ago ↶
586
let mut index: Vec< ( ObjectRef, PackEntry) > = Vec :: with_capacity( refs.len ( ) ) ;
a17fc622 Andy McCall 1 month ago ↶
587
588
let dict = if level = = REPACK_ZSTD_LEVEL & & refs.len ( ) > = DICT_MIN_OBJECTS {
589
let _t = crate :: timing:: phase( " pack: train a dictionary" ) ;
590
self .train_dictionary ( & refs)
591
} else {
592
None
593
} ;
594
let encoder = dict
595
.as_ref ( )
596
.map ( | d | zstd:: dict:: EncoderDictionary:: copy( d, level) ) ;
d02e545d Andy McCall 1 month ago ↶
597
{
598
let mut f = io:: BufWriter:: new( fs:: File:: create( & tmp_pack) ? ) ;
599
f.write_all ( PACK_MAGIC ) ? ;
600
let mut offset = PACK_MAGIC .len ( ) as u64 ;
da652d63 Andy McCall 1 month ago ↶
601
602
603
let mut batches = refs.chunks ( 1024 ) ;
604
let mut compressed_batch = Vec :: new( ) ;
605
loop {
606
if compressed_batch.is_empty ( ) {
607
let Some ( batch) = batches.next ( ) else { break } ;
608
let mut read: Vec< ( ObjectRef, ObjectType, Vec< u8 > , bool ) > =
609
Vec :: with_capacity( batch.len ( ) ) ;
610
for r in batch {
611
let ( ty, body) = self .get ( r) ? ;
612
read.push ( ( * r, ty, body, self .is_nocompress ( r) ) ) ;
75167672 Andy McCall 1 month ago
613
}
da652d63 Andy McCall 1 month ago ↶
614
use rayon:: prelude:: * ;
615
compressed_batch = read
616
.into_par_iter ( )
a17fc622 Andy McCall 1 month ago ↶
617
.map_init (
618
| | {
619
encoder.as_ref ( ) .and_then ( | e | {
620
zstd:: bulk:: Compressor:: with_prepared_dictionary( e) .ok ( )
621
} )
622
} ,
623
| with_dict , ( r , ty , body , raw ) | {
624
let packed = if raw {
625
None
626
} else {
627
628
629
let dicted = with_dict
630
.as_mut ( )
631
.filter ( | _| body.len ( ) < = DICT_OBJECT_MAX )
632
.and_then ( | c | c.compress ( & body) .ok ( ) )
633
.map ( | c | ( FLAG_ZSTD | FLAG_DICT , c) ) ;
634
dicted
635
.or_else ( | | {
636
zstd:: bulk:: compress( & body, level)
637
.ok ( )
638
.map ( | c | ( FLAG_ZSTD , c) )
639
} )
640
.filter ( | ( _, c ) | c.len ( ) < body.len ( ) )
641
} ;
642
( r, ty, body, packed)
643
} ,
644
)
da652d63 Andy McCall 1 month ago ↶
645
.collect:: < Vec< _ > > ( ) ;
646
compressed_batch.reverse ( ) ;
647
}
648
let Some ( ( r, ty, body, packed) ) = compressed_batch.pop ( ) else {
649
continue ;
650
} ;
651
let r = & r;
652
let ( flags, stored) = match packed {
a17fc622 Andy McCall 1 month ago ↶
653
Some ( c) => c,
da652d63 Andy McCall 1 month ago ↶
654
None => ( 0 , body.clone ( ) ) ,
cdb5beba Andy McCall 1 month ago ↶
655
} ;
d02e545d Andy McCall 1 month ago ↶
656
let header_len = 1 + 1 + 4 + 4 + 32 ;
657
f.write_all ( & [ type_index ( ty) , flags] ) ? ;
658
f.write_all ( & ( stored.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
659
f.write_all ( & ( body.len ( ) as u32 ) .to_le_bytes ( ) ) ? ;
660
f.write_all ( & r.0 ) ? ;
661
f.write_all ( & stored) ? ;
75167672 Andy McCall 1 month ago
662
index.push ( (
663
* r,
664
PackEntry {
665
offset: offset + header_len,
666
stored_len: stored.len ( ) as u32 ,
667
raw_len: body.len ( ) as u32 ,
668
ty,
669
flags,
670
} ,
671
) ) ;
d02e545d Andy McCall 1 month ago ↶
672
offset + = header_len + stored.len ( ) as u64 ;
673
report.objects + = 1 ;
674
report.raw_bytes + = body.len ( ) as u64 ;
675
report.packed_bytes + = stored.len ( ) as u64 ;
676
}
677
f.flush ( ) ? ;
678
f.get_ref ( ) .sync_all ( ) ? ;
a17fc622 Andy McCall 1 month ago ↶
679
}
680
681
if let Some ( d) = & dict {
682
crate :: durable:: write_atomic( & self .dir.join ( format! ( " pack-{id} .dict" ) ) , d) ? ;
d02e545d Andy McCall 1 month ago ↶
683
}
8f10a07a Andy McCall 1 month ago ↶
684
self .finish_pack_files ( & id, & tmp_pack, & index) ? ;
ba160f60 Andy McCall 1 month ago ↶
685
for p in old_packs {
a17fc622 Andy McCall 1 month ago ↶
686
remove_pack_files ( p) ? ;
ba160f60 Andy McCall 1 month ago ↶
687
}
d02e545d Andy McCall 1 month ago ↶
688
self .reload_packs ( ) ? ;
ba160f60 Andy McCall 1 month ago ↶
689
for path in loose_paths {
d02e545d Andy McCall 1 month ago ↶
690
fs:: remove_file( path) ? ;
691
if let Some ( dir) = path.parent ( ) {
692
let _ = fs:: remove_dir( dir) ;
693
}
694
}
695
Ok ( report)
ff0af1ee unknown 1 month ago
696
}
697
a17fc622 Andy McCall 1 month ago ↶
698
699
700
fn train_dictionary ( & self , refs : & [ObjectRef]) -> Option< Vec< u8 > > {
701
let step = ( refs.len ( ) / 10_000 ) .max ( 1 ) ;
702
let mut samples: Vec< Vec< u8 > > = Vec :: new( ) ;
703
let mut total = 0 usize ;
704
for r in refs.iter ( ) .step_by ( step) {
705
if total > 32 < < 20 {
706
break ;
707
}
708
let Ok ( ( ty, body) ) = self .get ( r) else {
709
continue ;
710
} ;
711
if matches! (
712
ty,
713
ObjectType:: Chunk | ObjectType:: Blob | ObjectType:: Change
714
) & & ! body.is_empty ( )
715
& & body.len ( ) < 1 < < 20
716
{
717
total + = body.len ( ) ;
718
samples.push ( body) ;
719
}
720
}
721
zstd:: dict:: from_samples( & samples, DICT_BYTES ) .ok ( )
722
}
723
ff0af1ee unknown 1 month ago
724
pub fn dir ( & self ) -> & Path {
725
& self .dir
726
}
727
387335ff Andy McCall 1 month ago ↶
728
pub ( crate ) fn path_for ( & self , r : & ObjectRef) -> PathBuf {
ff0af1ee unknown 1 month ago
729
let h = r.to_hex ( ) ;
730
self .dir.join ( " loose" ) .join ( & h[ .. 2 ] ) .join ( & h[ 2 .. ] )
731
}
732
733
pub fn has ( & self , r : & ObjectRef) -> bool {
75167672 Andy McCall 1 month ago
734
self .path_for ( r) .is_file ( )
735
| | self .find_packed ( r) .is_some ( )
736
| | self
737
.pending
738
.borrow ( )
739
.as_ref ( )
740
.is_some_and ( | p | p.lookup.contains_key ( r) )
ff0af1ee unknown 1 month ago
741
}
742
8f10a07a Andy McCall 1 month ago ↶
743
744
745
746
747
pub fn begin_batch ( & self ) -> Result< Batch< '_ > > {
748
let depth = self .batch_depth.get ( ) ;
749
if depth = = 0 {
75167672 Andy McCall 1 month ago
750
* self .pending.borrow_mut ( ) = Some ( Pending {
751
buffered: vec! [ ] ,
752
buffered_bytes: 0 ,
753
lookup: Default :: default( ) ,
754
pack: None ,
755
report: PackReport:: default( ) ,
756
} ) ;
8f10a07a Andy McCall 1 month ago ↶
757
}
758
self .batch_depth.set ( depth + 1 ) ;
75167672 Andy McCall 1 month ago
759
Ok ( Batch {
760
store: self ,
761
done: false ,
762
} )
8f10a07a Andy McCall 1 month ago ↶
763
}
764
765
fn finish_batch ( & self ) -> Result< ( ) > {
766
let depth = self .batch_depth.get ( ) ;
767
if depth = = 0 {
768
return Ok ( ( ) ) ;
769
}
770
self .batch_depth.set ( depth - 1 ) ;
771
if depth > 1 {
772
return Ok ( ( ) ) ;
773
}
75167672 Andy McCall 1 month ago
774
let Some ( pending) = self .pending.borrow_mut ( ) .take ( ) else {
775
return Ok ( ( ) ) ;
776
} ;
4dcb8c09 Andy McCall 1 month ago ↶
777
self .write_pending ( pending)
778
}
779
780
781
782
783
pub fn flush ( & self ) -> Result< ( ) > {
784
let Some ( pending) = self .pending.borrow_mut ( ) .take ( ) else {
785
return Ok ( ( ) ) ;
786
} ;
787
self .write_pending ( pending) ? ;
788
* self .pending.borrow_mut ( ) = Some ( Pending {
789
buffered: vec! [ ] ,
790
buffered_bytes: 0 ,
791
lookup: Default :: default( ) ,
792
pack: None ,
793
report: PackReport:: default( ) ,
794
} ) ;
795
Ok ( ( ) )
796
}
797
798
fn write_pending ( & self , pending : Pending) -> Result< ( ) > {
8f10a07a Andy McCall 1 month ago ↶
799
match pending.pack {
800
None => {
801
for ( ty, body) in & pending.buffered {
802
self .put_loose ( * ty, body) ? ;
803
}
804
Ok ( ( ) )
805
}
806
Some ( mut pack) => {
807
pack.writer.flush ( ) ? ;
808
pack.writer.get_ref ( ) .sync_all ( ) ? ;
809
drop ( pack.writer) ;
810
pack.index.sort_by_key ( | ( r , _) | * r) ;
811
self .finish_pack_files ( & pack.id, & pack.tmp_path, & pack.index) ? ;
812
Ok ( ( ) )
813
}
814
}
815
}
816
817
818
fn pending_get ( & self , r : & ObjectRef) -> Option< Result< ( ObjectType, Vec< u8 > ) > > {
819
let mut guard = self .pending.borrow_mut ( ) ;
820
let pending = guard.as_mut ( ) ? ;
821
let entry = * pending.lookup.get ( r) ? ;
822
Some ( match entry {
823
PendingEntry:: Buffered( i) => {
824
let ( ty, body) = & pending.buffered[ i] ;
825
Ok ( ( * ty, body.clone ( ) ) )
826
}
827
PendingEntry:: Packed( e) => {
75167672 Andy McCall 1 month ago
828
let Some ( pack) = pending.pack.as_mut ( ) else {
829
return Some ( Err ( StoreError:: NotFound( * r) ) ) ;
830
} ;
8f10a07a Andy McCall 1 month ago ↶
831
match pack.writer.flush ( ) {
75167672 Andy McCall 1 month ago
832
Ok ( ( ) ) => PackIndex {
833
path: pack.tmp_path.clone ( ) ,
834
refs: vec! [ ] ,
835
entries: vec! [ ] ,
a17fc622 Andy McCall 1 month ago ↶
836
dict: None ,
75167672 Andy McCall 1 month ago
837
}
838
.read ( r, e) ,
8f10a07a Andy McCall 1 month ago ↶
839
Err ( err) => Err ( err.into ( ) ) ,
840
}
841
}
842
} )
843
}
844
845
75167672 Andy McCall 1 month ago
846
fn pending_pack_write (
847
& self ,
848
pack : & mut PendingPack,
849
r : & ObjectRef,
850
ty : ObjectType,
851
body : & [u8 ],
852
report : & mut PackReport,
853
) -> Result< PackEntry> {
8f10a07a Andy McCall 1 month ago ↶
854
let ( flags, stored) = if self .is_nocompress ( r) {
855
( 0 , body.to_vec ( ) )
856
} else {
75167672 Andy McCall 1 month ago
857
let compressed = zstd:: bulk:: compress( body, ZSTD_LEVEL )
858
.map_err ( | e | StoreError:: Corrupt( * r, format! ( " zstd: {e} " ) ) ) ? ;
859
if compressed.len ( ) < body.len ( ) {
860
( FLAG_ZSTD , compressed)
861
} else {
862
( 0 , body.to_vec ( ) )
863
}
8f10a07a Andy McCall 1 month ago ↶
864
} ;
192fad1e Andy McCall 1 month ago ↶
865
write_pack_entry ( pack, r, ty, body.len ( ) , flags, & stored, report)
8f10a07a Andy McCall 1 month ago ↶
866
}
867
868
fn put_pending ( & self , r : ObjectRef, ty : ObjectType, body : & [u8 ]) -> Result< ( ) > {
869
let mut guard = self .pending.borrow_mut ( ) ;
870
let pending = guard.as_mut ( ) .expect ( " batch open" ) ;
871
if pending.lookup.contains_key ( & r) {
872
return Ok ( ( ) ) ;
873
}
75167672 Andy McCall 1 month ago
874
if pending.pack.is_none ( )
875
& & pending.buffered.len ( ) < SPILL_OBJECTS
876
& & pending.buffered_bytes + body.len ( ) < = SPILL_BYTES
877
{
8f10a07a Andy McCall 1 month ago ↶
878
pending.buffered.push ( ( ty, body.to_vec ( ) ) ) ;
879
pending.buffered_bytes + = body.len ( ) ;
75167672 Andy McCall 1 month ago
880
pending
881
.lookup
882
.insert ( r, PendingEntry:: Buffered( pending.buffered.len ( ) - 1 ) ) ;
8f10a07a Andy McCall 1 month ago ↶
883
return Ok ( ( ) ) ;
884
}
192fad1e Andy McCall 1 month ago ↶
885
self .ensure_pack ( pending) ? ;
886
let mut report = std:: mem:: take( & mut pending.report) ;
887
let pack = pending.pack.as_mut ( ) .unwrap ( ) ;
888
let e = self .pending_pack_write ( pack, & r, ty, body, & mut report) ? ;
889
pending.report = report;
890
pending.lookup.insert ( r, PendingEntry:: Packed( e) ) ;
891
Ok ( ( ) )
892
}
893
894
895
896
fn ensure_pack ( & self , pending : & mut Pending) -> Result< ( ) > {
8f10a07a Andy McCall 1 month ago ↶
897
if pending.pack.is_none ( ) {
898
899
let mut nonce = [ 0 u8 ; 8 ] ;
900
rand:: rngs:: OsRng.fill_bytes ( & mut nonce) ;
901
let id = hex:: encode( nonce) ;
902
let tmp_path = self .dir.join ( format! ( " tmp-{id} .pack" ) ) ;
903
let mut writer = io:: BufWriter:: new( fs:: File:: create( & tmp_path) ? ) ;
904
writer.write_all ( PACK_MAGIC ) ? ;
75167672 Andy McCall 1 month ago
905
let mut pack = PendingPack {
906
id,
907
tmp_path,
908
writer,
909
offset: PACK_MAGIC .len ( ) as u64 ,
910
index: vec! [ ] ,
911
} ;
8f10a07a Andy McCall 1 month ago ↶
912
let buffered = std:: mem:: take( & mut pending.buffered) ;
913
pending.buffered_bytes = 0 ;
914
let mut report = std:: mem:: take( & mut pending.report) ;
915
for ( bty, bbody) in & buffered {
916
let br = hash_object ( * bty, bbody) ;
917
let e = self .pending_pack_write ( & mut pack, & br, * bty, bbody, & mut report) ? ;
918
pending.lookup.insert ( br, PendingEntry:: Packed( e) ) ;
919
}
920
pending.report = report;
921
pending.pack = Some ( pack) ;
192fad1e Andy McCall 1 month ago ↶
922
}
923
Ok ( ( ) )
924
}
925
926
927
928
929
pub fn put_many ( & self , objects : & [( ObjectType , &[u8 ]) ]) -> Result< Vec< ObjectRef> > {
930
use rayon:: prelude:: * ;
931
let total: usize = objects.iter ( ) .map ( | ( _, b ) | b.len ( ) ) .sum ( ) ;
932
if self .pending.borrow ( ) .is_none ( ) | | total < SPILL_BYTES {
933
return objects.iter ( ) .map ( | ( ty , b ) | self .put ( * ty, b) ) .collect ( ) ;
934
}
935
for ( ty, b) in objects {
936
if b.len ( ) > MAX_OBJECT_LEN as usize {
937
return Err ( StoreError:: TooLarge {
938
kind: ty.name ( ) ,
939
size: b.len ( ) ,
940
limit: MAX_OBJECT_LEN ,
941
} ) ;
942
}
8f10a07a Andy McCall 1 month ago ↶
943
}
192fad1e Andy McCall 1 month ago ↶
944
let refs: Vec< ObjectRef> = objects
945
.par_iter ( )
946
.map ( | ( ty , b ) | hash_object ( * ty, b) )
947
.collect ( ) ;
948
949
let mut seen: std:: collections:: HashSet< ObjectRef> = std:: collections:: HashSet:: new( ) ;
950
let mut todo: Vec< usize > = Vec :: new( ) ;
951
for ( i, r) in refs.iter ( ) .enumerate ( ) {
952
let known = self
953
.pending
954
.borrow ( )
955
.as_ref ( )
956
.is_some_and ( | p | p.lookup.contains_key ( r) ) ;
957
if seen.insert ( * r)
958
& & ! known
959
& & ! self .path_for ( r) .is_file ( )
960
& & self .find_packed ( r) .is_none ( )
961
{
962
todo.push ( i) ;
963
}
964
}
965
let raw: std:: collections:: HashSet< ObjectRef> =
966
match fs:: read_dir( self .dir.join ( " nocompress" ) ) {
967
Ok ( rd) => rd
968
.flatten ( )
969
.filter_map ( | e | ObjectRef:: from_hex( & e.file_name ( ) .to_string_lossy ( ) ) )
970
.collect ( ) ,
971
Err ( _ ) => std:: collections:: HashSet:: new( ) ,
972
} ;
973
let packed: Vec< ( u8 , Vec< u8 > ) > = todo
974
.par_iter ( )
975
.map ( | i | {
976
let body = objects[ * i] .1 ;
977
if raw.contains ( & refs[ * i] ) {
978
return ( 0 , body.to_vec ( ) ) ;
979
}
980
match zstd:: bulk:: compress( body, ZSTD_LEVEL ) {
981
Ok ( c) if c.len ( ) < body.len ( ) => ( FLAG_ZSTD , c) ,
982
_ => ( 0 , body.to_vec ( ) ) ,
983
}
984
} )
985
.collect ( ) ;
986
let mut guard = self .pending.borrow_mut ( ) ;
987
let pending = guard.as_mut ( ) .expect ( " batch open" ) ;
988
self .ensure_pack ( pending) ? ;
8f10a07a Andy McCall 1 month ago ↶
989
let mut report = std:: mem:: take( & mut pending.report) ;
990
let pack = pending.pack.as_mut ( ) .unwrap ( ) ;
192fad1e Andy McCall 1 month ago ↶
991
for ( i, ( flags, stored) ) in todo.iter ( ) .zip ( packed) {
992
let ( ty, body) = objects[ * i] ;
993
let e = write_pack_entry ( pack, & refs[ * i] , ty, body.len ( ) , flags, & stored, & mut report) ? ;
994
pending.lookup.insert ( refs[ * i] , PendingEntry:: Packed( e) ) ;
995
}
8f10a07a Andy McCall 1 month ago ↶
996
pending.report = report;
192fad1e Andy McCall 1 month ago ↶
997
Ok ( refs)
8f10a07a Andy McCall 1 month ago ↶
998
}
999
ff0af1ee unknown 1 month ago
1000
1001
pub fn put ( & self , ty : ObjectType, body : & [u8 ]) -> Result< ObjectRef> {
a9f686ed Andy McCall 1 month ago ↶
1002
1003
1004
1005
if body.len ( ) > MAX_OBJECT_LEN as usize {
1006
return Err ( StoreError:: TooLarge {
1007
kind: ty.name ( ) ,
1008
size: body.len ( ) ,
1009
limit: MAX_OBJECT_LEN ,
1010
} ) ;
1011
}
ff0af1ee unknown 1 month ago
1012
let r = hash_object ( ty, body) ;
1013
let path = self .path_for ( & r) ;
d02e545d Andy McCall 1 month ago ↶
1014
if path.is_file ( ) | | self .find_packed ( & r) .is_some ( ) {
ff0af1ee unknown 1 month ago
1015
return Ok ( r) ;
1016
}
8f10a07a Andy McCall 1 month ago ↶
1017
if self .pending.borrow ( ) .is_some ( ) {
1018
self .put_pending ( r, ty, body) ? ;
1019
return Ok ( r) ;
1020
}
1021
self .put_loose ( ty, body) ? ;
1022
Ok ( r)
1023
}
1024
1025
1026
fn put_loose ( & self , ty : ObjectType, body : & [u8 ]) -> Result< ObjectRef> {
1027
let r = hash_object ( ty, body) ;
1028
let path = self .path_for ( & r) ;
1029
if path.is_file ( ) {
1030
return Ok ( r) ;
1031
}
4dcb8c09 Andy McCall 1 month ago ↶
1032
let fanout = path.parent ( ) .unwrap ( ) ;
1033
if ! fanout.is_dir ( ) {
1034
fs:: create_dir_all( fanout) ? ;
1035
crate :: durable:: sync_dir( & self .dir.join ( " loose" ) ) ? ;
1036
}
ff0af1ee unknown 1 month ago
1037
let mut nonce = [ 0 u8 ; 8 ] ;
1038
rand:: rngs:: OsRng.fill_bytes ( & mut nonce) ;
75167672 Andy McCall 1 month ago
1039
let tmp = self
1040
.dir
1041
.join ( " loose" )
1042
.join ( format! ( " tmp-{} " , hex:: encode( nonce) ) ) ;
4dcb8c09 Andy McCall 1 month ago ↶
1043
crate :: durable:: step( " write loose object" ) ? ;
ff0af1ee unknown 1 month ago
1044
{
1045
let mut f = fs:: File:: create( & tmp) ? ;
1046
f.write_all ( & header ( ty, body.len ( ) ) ) ? ;
1047
f.write_all ( body) ? ;
1048
f.sync_all ( ) ? ;
1049
}
4dcb8c09 Andy McCall 1 month ago ↶
1050
crate :: durable:: rename( & tmp, & path) ? ;
ff0af1ee unknown 1 month ago
1051
Ok ( r)
1052
}
1053
8f10a07a Andy McCall 1 month ago ↶
1054
ff0af1ee unknown 1 month ago
1055
pub fn get ( & self , r : & ObjectRef) -> Result< ( ObjectType, Vec< u8 > ) > {
afaba5f1 Andy McCall 1 month ago ↶
1056
match read_loose_at ( & self .path_for ( r) , r) {
1057
Some ( found) => found,
1058
None => match self .find_packed ( r) {
1059
Some ( ( i, e) ) => self .packs.borrow ( ) [ i] .read ( r, e) ,
1060
None => self .pending_get ( r) .unwrap_or ( Err ( StoreError:: NotFound( * r) ) ) ,
1061
} ,
1062
}
1063
}
1064
1065
1066
1067
1068
pub fn get_many ( & self , refs : & [ObjectRef]) -> Vec< Result< Object> > {
1069
use rayon:: prelude:: * ;
1070
let paths: Vec< ( ObjectRef, PathBuf) > =
1071
refs.iter ( ) .map ( | r | ( * r, self .path_for ( r) ) ) .collect ( ) ;
1072
let mut found: Vec< Option< Result< Object> > > =
1073
paths.par_iter ( ) .map ( | ( r , p ) | read_loose_at ( p, r) ) .collect ( ) ;
1074
1075
let packs = self .packs.borrow ( ) ;
1076
let packed: Vec< ( usize , usize , PackEntry) > = found
75167672 Andy McCall 1 month ago
1077
.iter ( )
afaba5f1 Andy McCall 1 month ago ↶
1078
.enumerate ( )
1079
.filter ( | ( _, f ) | f.is_none ( ) )
1080
.filter_map ( | ( i , _) | {
1081
packs
1082
.iter ( )
1083
.enumerate ( )
1084
.find_map ( | ( p , pack ) | pack.find ( & refs[ i] ) .map ( | e | ( i, p, e) ) )
1085
} )
1086
.collect ( ) ;
1087
let indexes: & [ PackIndex] = & packs;
1088
let read: Vec< ( usize , Result< Object> ) > = packed
1089
.par_iter ( )
1090
.map ( | ( i , p , e ) | ( * i, indexes[ * p] .read ( & refs[ * i] , * e) ) )
1091
.collect ( ) ;
1092
drop ( packs) ;
1093
for ( i, r) in read {
1094
found[ i] = Some ( r) ;
ff0af1ee unknown 1 month ago
1095
}
afaba5f1 Andy McCall 1 month ago ↶
1096
found
1097
.into_iter ( )
1098
.zip ( refs)
1099
.map ( | ( f , r ) | match f {
1100
Some ( f) => f,
1101
None => self .get ( r) ,
1102
} )
1103
.collect ( )
ff0af1ee unknown 1 month ago
1104
}
1105
1106
pub fn get_typed ( & self , r : & ObjectRef, want : ObjectType) -> Result< Vec< u8 > > {
1107
let ( ty, body) = self .get ( r) ? ;
1108
if ty ! = want {
1109
return Err ( StoreError:: WrongType( * r, ty.name ( ) , want.name ( ) ) ) ;
1110
}
1111
Ok ( body)
1112
}
1113
6f8aeb99 Andy McCall 1 month ago ↶
1114
1115
ff0af1ee unknown 1 month ago
1116
pub fn put_change ( & self , c : & Change) -> Result< ObjectRef> {
17f94b13 Andy McCall 1 month ago ↶
1117
let bytes = c.encode_streaming ( | batch | self .put_texts ( & batch) ) ? ;
1118
self .put ( ObjectType:: Change, & bytes)
6f8aeb99 Andy McCall 1 month ago ↶
1119
}
1120
17f94b13 Andy McCall 1 month ago ↶
1121
1122
1123
pub fn put_texts ( & self , texts : & [crate:: objects:: StoredText]) -> Result< ( ) > {
192fad1e Andy McCall 1 month ago ↶
1124
let mut chunks: Vec< ( ObjectType, & [u8 ]) > = Vec :: new( ) ;
1125
for t in texts {
1126
if ! self .has ( & t.blob.hash ( ) ) {
1127
chunks.extend (
1128
crate :: chunk:: chunks( & t.content)
1129
.into_iter ( )
1130
.map ( | c | ( ObjectType:: Chunk, c) ) ,
1131
) ;
1132
}
6f8aeb99 Andy McCall 1 month ago ↶
1133
}
192fad1e Andy McCall 1 month ago ↶
1134
self .put_many ( & chunks) ? ;
1135
for t in texts {
1136
self .put ( ObjectType:: Blob, & t.blob.encode ( ) ) ? ;
6f8aeb99 Andy McCall 1 month ago ↶
1137
}
17f94b13 Andy McCall 1 month ago ↶
1138
Ok ( ( ) )
ff0af1ee unknown 1 month ago
1139
}
1140
1141
pub fn get_change ( & self , r : & ObjectRef) -> Result< Change> {
6f8aeb99 Andy McCall 1 month ago ↶
1142
Ok ( self .get_change_parts ( r) ? .0 )
1143
}
1144
1145
1146
1147
pub fn get_change_parts ( & self , r : & ObjectRef) -> Result< ( Change, Vec< ObjectRef> ) > {
1148
let bytes = self .get_typed ( r, ObjectType:: Change) ? ;
1149
let mut parts = Vec :: new( ) ;
1150
let mut failed = None ;
0f93f49c Andy McCall 1 month ago ↶
1151
let decoded = Change:: decode_with( & bytes, & mut | text, count, form| match self
1152
.read_text ( text)
1153
{
6f8aeb99 Andy McCall 1 month ago ↶
1154
Ok ( ( blob, content) ) => {
1155
parts.push ( * text) ;
1156
parts.extend ( blob.chunks) ;
0f93f49c Andy McCall 1 month ago ↶
1157
crate :: objects:: text_lines( & content, count, form)
6f8aeb99 Andy McCall 1 month ago ↶
1158
}
1159
Err ( e) => {
1160
let why = e.to_string ( ) ;
1161
failed = Some ( e) ;
1162
Err ( ObjectError:: Schema( format! (
1163
" text blob {} : {why} " ,
1164
text.short ( 12 )
1165
) ) )
1166
}
1167
} ) ;
1168
match ( decoded, failed) {
1169
( Ok ( c) , _ ) => Ok ( ( c, parts) ) ,
1170
( Err ( _ ) , Some ( StoreError:: NotFound( t) ) ) => Err ( StoreError:: Corrupt(
1171
* r,
1172
format! ( " its text blob {} is missing" , t.short ( 12 ) ) ,
1173
) ) ,
1174
( Err ( e) , _ ) => Err ( StoreError:: Corrupt( * r, e.to_string ( ) ) ) ,
1175
}
1176
}
1177
a4fad5b0 Andy McCall 1 month ago ↶
1178
1179
1180
1181
1182
pub fn get_change_lazy ( & self , r : & ObjectRef) -> Result< ( Change, Vec< crate:: objects:: TextRef> ) > {
86e1824f Andy McCall 1 month ago ↶
1183
let bytes = self .get_typed ( r, ObjectType:: Change) ? ;
a4fad5b0 Andy McCall 1 month ago ↶
1184
Change:: decode_skeleton( & bytes, * r) .map_err ( | e | StoreError:: Corrupt( * r, e.to_string ( ) ) )
86e1824f Andy McCall 1 month ago ↶
1185
}
1186
69816d68 Andy McCall 1 month ago ↶
1187
1188
1189
ce14f0d6 Andy McCall 1 month ago ↶
1190
1191
1192
1193
69816d68 Andy McCall 1 month ago ↶
1194
pub fn get_change_meta ( & self , r : & ObjectRef) -> Result< crate:: state:: ChangeMeta> {
ce14f0d6 Andy McCall 1 month ago ↶
1195
if self .metas.borrow ( ) .is_none ( ) {
1196
* self .metas.borrow_mut ( ) = Some ( self .read_metas_cache ( ) ) ;
1197
}
1198
let cached = self .metas.borrow ( ) .as_ref ( ) .and_then ( | m | m.get ( r) .cloned ( ) ) ;
1199
if let Some ( meta) = cached {
1200
if self .has ( r) {
1201
# [ cfg ( test ) ]
1202
assert_eq! (
1203
meta,
1204
Change:: decode_meta( & self .get_typed ( r, ObjectType:: Change) ? ) .unwrap ( ) ,
1205
" the metadata cache holds a change's metadata"
1206
) ;
1207
return Ok ( meta) ;
1208
}
1209
}
4d6c9c1b Andy McCall 1 month ago ↶
1210
let bytes = self .get_typed ( r, ObjectType:: Change) ? ;
ce14f0d6 Andy McCall 1 month ago ↶
1211
let meta =
1212
Change:: decode_meta( & bytes) .map_err ( | e | StoreError:: Corrupt( * r, e.to_string ( ) ) ) ? ;
1213
self .remember_meta ( r, & meta) ;
1214
Ok ( meta)
1215
}
1216
1217
1218
1219
1220
1221
fn read_metas_cache ( & self ) -> crate:: fasthash:: FastMap< ObjectRef, crate:: state:: ChangeMeta> {
1222
let mut out = crate :: fasthash:: FastMap:: default( ) ;
1223
let Ok ( bytes) = fs:: read( self .dir.join ( " metas" ) ) else {
1224
return out;
1225
} ;
1226
let mut r = crate :: flat:: Reader:: new( & bytes) ;
1227
let mut good = 0 ;
1228
while ! r.at_end ( ) {
1229
let mut record = | | -> std:: result:: Result< _ , ObjectError> {
1230
let h = r.object ( ) ? ;
1231
let body = r.bytes ( ) ? ;
1232
let check = r.fixed:: < 8> ( ) ? ;
1233
Ok ( ( h, body, check) )
1234
} ;
1235
let Ok ( ( h, body, check) ) = record ( ) else {
1236
break ;
1237
} ;
1238
let mut sum = blake3:: Hasher:: new( ) ;
1239
sum.update ( & h.0 ) .update ( body) ;
1240
if sum.finalize ( ) .as_bytes ( ) [ .. 8 ] ! = check {
1241
break ;
1242
}
1243
match crate :: state:: ChangeMeta:: read_flat( & mut crate :: flat:: Reader:: new( body) ) {
1244
Ok ( m) => out.insert ( h, m) ,
1245
Err ( _ ) => break ,
1246
} ;
1247
good + = 32 + 4 + body.len ( ) + 8 ;
1248
}
1249
1250
if good < bytes.len ( ) {
1251
let _ = fs:: OpenOptions:: new( )
1252
.write ( true )
1253
.open ( self .dir.join ( " metas" ) )
1254
.and_then ( | f | f.set_len ( good as u64 ) ) ;
1255
}
1256
out
1257
}
1258
1259
1260
1261
fn remember_meta ( & self , r : & ObjectRef, meta : & crate:: state:: ChangeMeta) {
1262
let mut body = crate :: flat:: Writer:: default( ) ;
1263
meta.write_flat ( & mut body) ;
1264
let mut w = crate :: flat:: Writer:: default( ) ;
1265
w.object ( r) ;
1266
w.bytes ( & body.0 ) ;
1267
let mut sum = blake3:: Hasher:: new( ) ;
1268
sum.update ( & r.0 ) .update ( & body.0 ) ;
1269
w.fixed ( & sum.finalize ( ) .as_bytes ( ) [ .. 8 ] ) ;
1270
let _ = fs:: OpenOptions:: new( )
1271
.create ( true )
1272
.append ( true )
1273
.open ( self .dir.join ( " metas" ) )
1274
.and_then ( | mut f | f.write_all ( & w.0 ) ) ;
1275
if let Some ( m) = self .metas.borrow_mut ( ) .as_mut ( ) {
1276
m.insert ( * r, meta.clone ( ) ) ;
1277
}
69816d68 Andy McCall 1 month ago ↶
1278
}
1279
6f8aeb99 Andy McCall 1 month ago ↶
1280
fn read_text ( & self , r : & ObjectRef) -> Result< ( Blob, Vec< u8 > ) > {
1281
let blob = Blob:: decode( & self .get_typed ( r, ObjectType:: Blob) ? ) ? ;
1282
let mut content = Vec :: with_capacity( blob.length as usize ) ;
1283
for c in & blob.chunks {
1284
content.extend ( self .get_typed ( c, ObjectType:: Chunk) ? ) ;
1285
}
1286
Ok ( ( blob, content) )
ff0af1ee unknown 1 month ago
1287
}
1288
1289
pub fn put_chunk ( & self , bytes : & [u8 ]) -> Result< ObjectRef> {
1290
self .put ( ObjectType:: Chunk, bytes)
1291
}
1292
cdb5beba Andy McCall 1 month ago ↶
1293
1294
pub fn put_chunk_nocompress ( & self , bytes : & [u8 ]) -> Result< ObjectRef> {
8f10a07a Andy McCall 1 month ago ↶
1295
let r = hash_object ( ObjectType:: Chunk, bytes) ;
cdb5beba Andy McCall 1 month ago ↶
1296
let dir = self .dir.join ( " nocompress" ) ;
1297
fs:: create_dir_all( & dir) ? ;
1298
let _ = fs:: File:: create( dir.join ( r.to_hex ( ) ) ) ;
8f10a07a Andy McCall 1 month ago ↶
1299
self .put ( ObjectType:: Chunk, bytes)
cdb5beba Andy McCall 1 month ago ↶
1300
}
1301
1302
fn is_nocompress ( & self , r : & ObjectRef) -> bool {
1303
self .dir.join ( " nocompress" ) .join ( r.to_hex ( ) ) .exists ( )
1304
}
1305
86e682c2 Andy McCall 1 month ago ↶
1306
pub fn put_state ( & self , st : & StateObject) -> Result< ObjectRef> {
1307
self .put ( ObjectType:: State, & st.encode ( ) )
1308
}
1309
1310
pub fn get_state ( & self , r : & ObjectRef) -> Result< StateObject> {
1311
Ok ( StateObject:: decode( & self .get_typed ( r, ObjectType:: State) ? ) ? )
1312
}
1313
5b9c6ad4 Andy McCall 1 month ago ↶
1314
pub fn put_attest ( & self , a : & Attest) -> Result< ObjectRef> {
1315
self .put ( ObjectType:: Attest, & a.encode ( ) )
1316
}
1317
1318
pub fn get_attest ( & self , r : & ObjectRef) -> Result< Attest> {
1319
Ok ( Attest:: decode( & self .get_typed ( r, ObjectType:: Attest) ? ) ? )
fc1a466a Andy McCall 1 month ago ↶
1320
}
1321
1322
pub fn put_receipt ( & self , r : & Receipt) -> Result< ObjectRef> {
1323
self .put ( ObjectType:: Receipt, & r.encode ( ) )
5b9c6ad4 Andy McCall 1 month ago ↶
1324
}
1325
fc1a466a Andy McCall 1 month ago ↶
1326
pub fn get_receipt ( & self , r : & ObjectRef) -> Result< Receipt> {
1327
Ok ( Receipt:: decode( & self .get_typed ( r, ObjectType:: Receipt) ? ) ? )
5b9c6ad4 Andy McCall 1 month ago ↶
1328
}
1329
fc1a466a Andy McCall 1 month ago ↶
1330
fn index_path ( & self , index : & str , key : & ObjectRef) -> PathBuf {
1331
let h = key.to_hex ( ) ;
1332
self .dir.join ( index) .join ( & h[ .. 2 ] ) .join ( & h[ 2 .. ] )
1333
}
1334
1335
1336
fn index_add ( & self , index : & str , key : & ObjectRef, value : & ObjectRef) -> Result< ( ) > {
1337
let mut values = self .index_get ( index, key) ? ;
1338
if values.contains ( value) {
5b9c6ad4 Andy McCall 1 month ago ↶
1339
return Ok ( ( ) ) ;
1340
}
fc1a466a Andy McCall 1 month ago ↶
1341
values.push ( * value) ;
1342
values.sort ( ) ;
1343
let path = self .index_path ( index, key) ;
5b9c6ad4 Andy McCall 1 month ago ↶
1344
fs:: create_dir_all( path.parent ( ) .unwrap ( ) ) ? ;
fc1a466a Andy McCall 1 month ago ↶
1345
let text: String = values.iter ( ) .map ( | s | format! ( " {} \n " , s.to_hex ( ) ) ) .collect ( ) ;
4dcb8c09 Andy McCall 1 month ago ↶
1346
crate :: durable:: write_atomic( & path, text.as_bytes ( ) ) ? ;
5b9c6ad4 Andy McCall 1 month ago ↶
1347
Ok ( ( ) )
1348
}
1349
fc1a466a Andy McCall 1 month ago ↶
1350
fn index_get ( & self , index : & str , key : & ObjectRef) -> Result< Vec< ObjectRef> > {
1351
match fs:: read_to_string( self .index_path ( index, key) ) {
5b9c6ad4 Andy McCall 1 month ago ↶
1352
Ok ( t) => Ok ( t.lines ( ) .filter_map ( ObjectRef:: from_hex) .collect ( ) ) ,
1353
Err ( e) if e.kind ( ) = = io:: ErrorKind:: NotFound => Ok ( vec! [ ] ) ,
1354
Err ( e) => Err ( e.into ( ) ) ,
1355
}
fc1a466a Andy McCall 1 month ago ↶
1356
}
1357
1358
1359
pub fn index_seal ( & self , change : & ObjectRef, attest : & ObjectRef) -> Result< ( ) > {
1360
self .index_add ( " seals" , change, attest)
1361
}
1362
1363
1364
pub fn seals_for ( & self , change : & ObjectRef) -> Result< Vec< ObjectRef> > {
1365
self .index_get ( " seals" , change)
1366
}
1367
1368
1369
pub fn index_receipt ( & self , state : & ObjectRef, attest : & ObjectRef) -> Result< ( ) > {
1370
self .index_add ( " receipts" , state, attest)
1371
}
1372
1373
1374
pub fn receipts_for ( & self , state : & ObjectRef) -> Result< Vec< ObjectRef> > {
1375
self .index_get ( " receipts" , state)
1376
}
1377
1378
1379
pub fn receipt_states ( & self ) -> Result< Vec< ObjectRef> > {
1380
let mut out = Vec :: new( ) ;
1381
let dir = self .dir.join ( " receipts" ) ;
1382
let top = match fs:: read_dir( & dir) {
1383
Ok ( d) => d,
1384
Err ( e) if e.kind ( ) = = io:: ErrorKind:: NotFound => return Ok ( out) ,
1385
Err ( e) => return Err ( e.into ( ) ) ,
1386
} ;
1387
for d in top {
1388
let d = d? ;
1389
let prefix = d.file_name ( ) .to_string_lossy ( ) .into_owned ( ) ;
1390
for f in fs:: read_dir( d.path ( ) ) ? {
1391
let name = f? .file_name ( ) .to_string_lossy ( ) .into_owned ( ) ;
1392
if let Some ( r) = ObjectRef:: from_hex( & format! ( " {prefix} {name} " ) ) {
1393
out.push ( r) ;
1394
}
1395
}
1396
}
1397
out.sort ( ) ;
1398
Ok ( out)
5b9c6ad4 Andy McCall 1 month ago ↶
1399
}
1400
1983686f Andy McCall 1 month ago ↶
1401
pub fn put_identity ( & self , id : & Identity) -> Result< ObjectRef> {
1402
self .put ( ObjectType:: Identity, & id.encode ( ) )
1403
}
1404
1405
pub fn get_identity ( & self , r : & ObjectRef) -> Result< Identity> {
1406
Ok ( Identity:: decode( & self .get_typed ( r, ObjectType:: Identity) ? ) ? )
1407
}
1408
1409
fn sig_path ( & self , r : & ObjectRef) -> PathBuf {
1410
let h = r.to_hex ( ) ;
1411
self .dir.join ( " sigs" ) .join ( & h[ .. 2 ] ) .join ( & h[ 2 .. ] )
1412
}
1413
1414
1415
pub fn signatures ( & self , r : & ObjectRef) -> Result< Vec< Signature> > {
1416
match fs:: read( self .sig_path ( r) ) {
1417
Ok ( b) => Ok ( Signature:: decode_list( & b) ? ) ,
1418
Err ( e) if e.kind ( ) = = io:: ErrorKind:: NotFound => Ok ( vec! [ ] ) ,
1419
Err ( e) => Err ( e.into ( ) ) ,
1420
}
1421
}
1422
1423
1424
pub fn put_signature ( & self , r : & ObjectRef, sig : & Signature) -> Result< ( ) > {
1425
let mut sigs = self .signatures ( r) ? ;
1426
sigs.retain ( | s | s.key ! = sig.key ) ;
1427
sigs.push ( sig.clone ( ) ) ;
5b1114a0 Andy McCall 1 month ago ↶
1428
sigs.sort_by_key ( | s | s.key ) ;
1983686f Andy McCall 1 month ago ↶
1429
let path = self .sig_path ( r) ;
1430
fs:: create_dir_all( path.parent ( ) .unwrap ( ) ) ? ;
1431
let mut nonce = [ 0 u8 ; 8 ] ;
1432
rand:: rngs:: OsRng.fill_bytes ( & mut nonce) ;
1433
let tmp = self .dir.join ( format! ( " sigs-tmp-{} " , hex:: encode( nonce) ) ) ;
1434
{
1435
let mut f = fs:: File:: create( & tmp) ? ;
1436
f.write_all ( & Signature:: encode_list( & sigs) ) ? ;
1437
f.sync_all ( ) ? ;
1438
}
4dcb8c09 Andy McCall 1 month ago ↶
1439
crate :: durable:: rename( & tmp, & path) ? ;
1983686f Andy McCall 1 month ago ↶
1440
Ok ( ( ) )
1441
}
1442
d02e545d Andy McCall 1 month ago ↶
1443
ff0af1ee unknown 1 month ago
1444
pub fn list ( & self ) -> io:: Result< Vec< ObjectRef> > {
d02e545d Andy McCall 1 month ago ↶
1445
let mut out: Vec< ObjectRef> = self .loose_objects ( ) ? .into_iter ( ) .map ( | ( r , _) | r ) .collect ( ) ;
1446
for p in self .packs.borrow ( ) .iter ( ) {
1447
out.extend ( p.refs.iter ( ) .copied ( ) ) ;
ff0af1ee unknown 1 month ago
1448
}
1449
out.sort ( ) ;
d02e545d Andy McCall 1 month ago ↶
1450
out.dedup ( ) ;
ff0af1ee unknown 1 month ago
1451
Ok ( out)
1452
}
afaba5f1 Andy McCall 1 month ago ↶
1453
}
1454
1455
1456
1457
fn read_loose_at ( path : & Path, r : & ObjectRef) -> Option< Result< Object> > {
1458
let data = match fs:: read( path) {
1459
Ok ( d) => d,
1460
Err ( e) if e.kind ( ) = = io:: ErrorKind:: NotFound => return None ,
1461
Err ( e) => return Some ( Err ( e.into ( ) ) ) ,
1462
} ;
1463
Some ( ( | | {
1464
let nul = data
1465
.iter ( )
1466
.position ( | & b | b = = 0 )
1467
.ok_or_else ( | | StoreError:: Corrupt( * r, " no header" .into ( ) ) ) ? ;
1468
let head = std:: str:: from_utf8( & data[ .. nul] )
1469
.map_err ( | _| StoreError:: Corrupt( * r, " header not UTF-8" .into ( ) ) ) ? ;
1470
let mut parts = head.split ( ' ' ) ;
1471
let ( Some ( " oxy1" ) , Some ( ty) , Some ( len) , None ) =
1472
( parts.next ( ) , parts.next ( ) , parts.next ( ) , parts.next ( ) )
1473
else {
1474
return Err ( StoreError:: Corrupt( * r, format! ( " bad header {head:?} " ) ) ) ;
1475
} ;
1476
let ty = ObjectType:: from_name( ty)
1477
.ok_or_else ( | | StoreError:: Corrupt( * r, format! ( " unknown type {ty} " ) ) ) ? ;
1478
let len: usize = len
1479
.parse ( )
1480
.map_err ( | _| StoreError:: Corrupt( * r, " bad length" .into ( ) ) ) ? ;
1481
let body = & data[ nul + 1 .. ] ;
1482
if body.len ( ) ! = len {
1483
return Err ( StoreError:: Corrupt(
1484
* r,
1485
format! ( " length {} != header {len} " , body.len ( ) ) ,
1486
) ) ;
1487
}
1488
if hash_object ( ty, body) ! = * r {
1489
return Err ( StoreError:: Corrupt( * r, " hash mismatch" .into ( ) ) ) ;
1490
}
1491
Ok ( ( ty, body.to_vec ( ) ) )
1492
} ) ( ) )
ff0af1ee unknown 1 month ago
1493
}
1494
1495
# [ cfg ( test ) ]
1496
mod tests {
1497
use super :: * ;
1498
1499
# [ test ]
1500
fn put_get_verify ( ) {
1501
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1502
let s = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
1503
let r = s.put ( ObjectType:: Chunk, b " hello" ) .unwrap ( ) ;
1504
assert! ( s.has ( & r) ) ;
1505
assert_eq! ( s.get ( & r) .unwrap ( ) , ( ObjectType:: Chunk, b " hello" .to_vec ( ) ) ) ;
1506
assert_eq! ( s.put ( ObjectType:: Chunk, b " hello" ) .unwrap ( ) , r) ;
1507
assert_eq! ( s.list ( ) .unwrap ( ) , vec! [ r] ) ;
75167672 Andy McCall 1 month ago
1508
assert! ( matches! (
1509
s.get_typed ( & r, ObjectType:: Blob) ,
1510
Err ( StoreError:: WrongType( .. ) )
1511
) ) ;
1512
assert! ( matches! (
1513
s.get ( & ObjectRef( [ 9 ; 32 ] ) ) ,
1514
Err ( StoreError:: NotFound( _ ) )
1515
) ) ;
ff0af1ee unknown 1 month ago
1516
1517
1518
let path = s.path_for ( & r) ;
1519
let mut data = fs:: read( & path) .unwrap ( ) ;
1520
let last = data.len ( ) - 1 ;
1521
data[ last] ^ = 1 ;
1522
fs:: write( & path, data) .unwrap ( ) ;
1523
assert! ( matches! ( s.get ( & r) , Err ( StoreError:: Corrupt( .. ) ) ) ) ;
1524
}
1525
1526
# [ test ]
d02e545d Andy McCall 1 month ago ↶
1527
fn packing_keeps_every_object_readable ( ) {
1528
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1529
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1530
let mut refs = Vec :: new( ) ;
1531
for i in 0 .. 300 u32 {
1532
let body = format! ( " object {i} " ) .repeat ( 1 + ( i % 7 ) as usize ) ;
1533
refs.push ( ( s.put ( ObjectType:: Chunk, body.as_bytes ( ) ) .unwrap ( ) , body) ) ;
1534
}
1535
let c = crate :: objects:: tests:: sample_change( ) ;
1536
let cr = s.put_change ( & c) .unwrap ( ) ;
1537
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 301 ) ;
1538
let report = s.pack_loose ( ) .unwrap ( ) ;
1539
assert_eq! ( report.objects, 301 ) ;
1540
assert! ( report.packed_bytes < report.raw_bytes, " {report:?}" ) ;
1541
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 0 ) ;
1542
assert_eq! ( s.pack_count ( ) , 1 ) ;
1543
for ( r, body) in & refs {
1544
assert! ( s.has ( r) ) ;
75167672 Andy McCall 1 month ago
1545
assert_eq! (
1546
s.get ( r) .unwrap ( ) ,
1547
( ObjectType:: Chunk, body.as_bytes ( ) .to_vec ( ) )
1548
) ;
d02e545d Andy McCall 1 month ago ↶
1549
}
1550
assert_eq! ( s.get_change ( & cr) .unwrap ( ) , c) ;
1551
assert_eq! ( s.list ( ) .unwrap ( ) .len ( ) , 301 ) ;
1552
1553
75167672 Andy McCall 1 month ago
1554
assert_eq! (
1555
s.put ( ObjectType:: Chunk, refs[ 0 ] .1. as_bytes ( ) ) .unwrap ( ) ,
1556
refs[ 0 ] .0
1557
) ;
d02e545d Andy McCall 1 month ago ↶
1558
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 0 ) ;
1559
let extra = s.put ( ObjectType:: Chunk, b " after packing" ) .unwrap ( ) ;
1560
s.pack_loose ( ) .unwrap ( ) ;
1561
assert_eq! ( s.pack_count ( ) , 2 ) ;
1562
assert_eq! ( s.get ( & extra) .unwrap ( ) .1 , b " after packing" ) ;
1563
1564
let s2 = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1565
assert_eq! ( s2.pack_count ( ) , 2 ) ;
1566
assert_eq! ( s2.get ( & refs[ 5 ] .0 ) .unwrap ( ) .1 , refs[ 5 ] .1. as_bytes ( ) ) ;
75167672 Andy McCall 1 month ago
1567
assert! ( matches! (
1568
s2.get ( & ObjectRef( [ 9 ; 32 ] ) ) ,
1569
Err ( StoreError:: NotFound( _ ) )
1570
) ) ;
d02e545d Andy McCall 1 month ago ↶
1571
1572
let target = refs[ 5 ] .0 ;
1573
let ( pack_path, offset) = {
1574
let packs = s2.packs.borrow ( ) ;
1575
let ( i, e) = s2.find_packed ( & target) .unwrap ( ) ;
1576
( packs[ i] .path.clone ( ) , e.offset as usize )
1577
} ;
1578
let mut data = fs:: read( & pack_path) .unwrap ( ) ;
1579
data[ offset] ^ = 0xff ;
1580
fs:: write( & pack_path, data) .unwrap ( ) ;
1581
let s3 = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1582
assert! ( matches! ( s3.get ( & target) , Err ( StoreError:: Corrupt( .. ) ) ) ) ;
75167672 Andy McCall 1 month ago
1583
assert_eq! (
1584
s3.get ( & refs[ 6 ] .0 ) .unwrap ( ) .1 ,
1585
refs[ 6 ] .1. as_bytes ( ) ,
1586
" other objects are unaffected"
1587
) ;
a17fc622 Andy McCall 1 month ago ↶
1588
}
1589
1590
# [ test ]
1591
fn a_full_repack_trains_a_dictionary_and_reads_back ( ) {
1592
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1593
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1594
1595
let bodies: Vec< Vec< u8 > > = ( 0 .. 1500 )
1596
.map ( | i | {
1597
format! (
1598
" // SPDX-License-Identifier: GPL-2.0\n #include <linux/module.h>\n \
1599
static int probe_{i} (struct device *dev)\n {{ \n \t return {i} ;\n }} \n "
1600
)
1601
.into_bytes ( )
1602
} )
1603
.collect ( ) ;
1604
let refs: Vec< ObjectRef> = bodies
1605
.iter ( )
1606
.map ( | b | s.put ( ObjectType:: Chunk, b) .unwrap ( ) )
1607
.collect ( ) ;
1608
s.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
1609
let dicts = fs:: read_dir( dir.path ( ) )
1610
.unwrap ( )
1611
.flatten ( )
1612
.filter ( | e | e.path ( ) .extension ( ) .is_some_and ( | x | x = = " dict" ) )
1613
.count ( ) ;
1614
assert_eq! ( dicts, 1 , " the pack has a dictionary" ) ;
1615
let with_dict = refs
1616
.iter ( )
1617
.filter ( | r | s.find_packed ( r) .unwrap ( ) .1. flags & FLAG_DICT ! = 0 )
1618
.count ( ) ;
1619
assert! ( with_dict > 1000 , " most use it: {with_dict}" ) ;
1620
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1621
for ( r, b) in refs.iter ( ) .zip ( & bodies) {
1622
assert_eq! ( & again.get ( r) .unwrap ( ) .1 , b) ;
1623
}
1624
1625
again.repack_all ( REPACK_ZSTD_LEVEL ) .unwrap ( ) ;
1626
let files: Vec< String> = fs:: read_dir( dir.path ( ) )
1627
.unwrap ( )
1628
.flatten ( )
1629
.map ( | e | e.file_name ( ) .to_string_lossy ( ) .into_owned ( ) )
1630
.filter ( | n | n.starts_with ( " pack-" ) )
1631
.collect ( ) ;
1632
assert_eq! ( files.len ( ) , 3 , " one pack, index and dictionary: {files:?}" ) ;
1633
assert_eq! ( & again.get ( & refs[ 7 ] ) .unwrap ( ) .1 , & bodies[ 7 ] ) ;
d02e545d Andy McCall 1 month ago ↶
1634
}
1635
1636
# [ test ]
cdb5beba Andy McCall 1 month ago ↶
1637
fn nocompress_chunks_pack_raw ( ) {
1638
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1639
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1640
let body = vec! [ b ' a' ; 10_000 ] ;
1641
let raw = s.put_chunk_nocompress ( & body) .unwrap ( ) ;
1642
let compressible = s.put ( ObjectType:: Chunk, & vec! [ b ' b' ; 10_000 ] ) .unwrap ( ) ;
1643
s.pack_loose ( ) .unwrap ( ) ;
1644
let packs = s.packs.borrow ( ) ;
1645
let ( i, e) = s.find_packed ( & raw) .unwrap ( ) ;
1646
assert_eq! ( ( e.flags, e.stored_len as usize ) , ( 0 , 10_000 ) ) ;
1647
let ( _ , c) = s.find_packed ( & compressible) .unwrap ( ) ;
1648
assert_eq! ( c.flags, FLAG_ZSTD ) ;
1649
assert! ( c.stored_len < 10_000 ) ;
1650
assert_eq! ( packs[ i] .read ( & raw, e) .unwrap ( ) .1 , body) ;
1651
}
1652
1653
# [ test ]
135212de Andy McCall 1 month ago ↶
1654
fn many_packs_merge_into_one ( ) {
1655
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1656
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1657
let mut refs = Vec :: new( ) ;
1658
for i in 0 .. ( MAX_PACKS + 2 ) {
75167672 Andy McCall 1 month ago
1659
refs.push (
1660
s.put ( ObjectType:: Chunk, format! ( " pack {i} " ) .as_bytes ( ) )
1661
.unwrap ( ) ,
1662
) ;
135212de Andy McCall 1 month ago ↶
1663
s.pack_loose ( ) .unwrap ( ) ;
1664
}
1665
assert_eq! ( s.pack_count ( ) , MAX_PACKS + 2 ) ;
1666
assert_eq! ( s.merge_packs ( ) .unwrap ( ) , MAX_PACKS + 2 ) ;
1667
assert_eq! ( s.pack_count ( ) , 1 ) ;
1668
assert_eq! ( s.merge_packs ( ) .unwrap ( ) , 0 ) ;
1669
for ( i, r) in refs.iter ( ) .enumerate ( ) {
1670
assert_eq! ( s.get ( r) .unwrap ( ) .1 , format! ( " pack {i} " ) .as_bytes ( ) ) ;
1671
}
1672
assert_eq! ( Store:: open( dir.path ( ) ) .unwrap ( ) .pack_count ( ) , 1 ) ;
1673
}
1674
1675
# [ test ]
ba160f60 Andy McCall 1 month ago ↶
1676
fn prune_removes_unreachable_loose_and_packed_objects ( ) {
1677
use std:: collections:: HashSet;
1678
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1679
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1680
let keep_a = s.put ( ObjectType:: Chunk, b " keep a" ) .unwrap ( ) ;
1681
let drop_a = s.put ( ObjectType:: Chunk, b " drop a" ) .unwrap ( ) ;
1682
s.pack_loose ( ) .unwrap ( ) ;
1683
let keep_b = s.put ( ObjectType:: Chunk, b " keep b" ) .unwrap ( ) ;
1684
let drop_b = s.put ( ObjectType:: Chunk, b " drop b" ) .unwrap ( ) ;
75167672 Andy McCall 1 month ago
1685
let sk = crate :: identity:: SecretKey {
1686
ed_seed: [ 1 ; 32 ] ,
1687
ml_seed: [ 2 ; 32 ] ,
1688
} ;
ba160f60 Andy McCall 1 month ago ↶
1689
let id = sk.identity ( " a" , " b" , 0 ) ;
1690
let key = s.put_identity ( & id) .unwrap ( ) ;
75167672 Andy McCall 1 month ago
1691
s.put_signature (
1692
& drop_b,
1693
& sk.sign ( crate :: identity:: Domain:: Change, & key, & drop_b) ,
1694
)
1695
.unwrap ( ) ;
ba160f60 Andy McCall 1 month ago ↶
1696
s.index_seal ( & drop_a, & ObjectRef( [ 3 ; 32 ] ) ) .unwrap ( ) ;
1697
let keep: HashSet< ObjectRef> = [ keep_a, keep_b, key] .into_iter ( ) .collect ( ) ;
1698
75167672 Andy McCall 1 month ago
1699
let r = s
1700
.prune ( & keep, std:: time:: Duration:: from_secs( 3600 ) )
1701
.unwrap ( ) ;
ba160f60 Andy McCall 1 month ago ↶
1702
assert_eq! ( ( r.objects, r.deferred) , ( 0 , 2 ) ) ;
1703
let r = s.prune ( & keep, std:: time:: Duration:: ZERO ) .unwrap ( ) ;
1704
assert_eq! ( r.objects, 2 , " {r:?}" ) ;
1705
assert! ( s.has ( & keep_a) & & s.has ( & keep_b) & & s.has ( & key) ) ;
1706
assert! ( ! s.has ( & drop_a) & & ! s.has ( & drop_b) ) ;
1707
assert! ( s.signatures ( & drop_b) .unwrap ( ) .is_empty ( ) ) ;
1708
assert! ( s.seals_for ( & drop_a) .unwrap ( ) .is_empty ( ) ) ;
1709
assert_eq! ( s.pack_count ( ) , 1 ) ;
1710
assert_eq! ( s.get ( & keep_a) .unwrap ( ) .1 , b " keep a" ) ;
1711
assert_eq! ( s.list ( ) .unwrap ( ) .len ( ) , 3 ) ;
1712
}
1713
1714
# [ test ]
1983686f Andy McCall 1 month ago ↶
1715
fn signatures_are_stored_beside_objects ( ) {
1716
use crate :: identity:: { Domain, SecretKey} ;
1717
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1718
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1719
let r = s.put ( ObjectType:: Chunk, b " x" ) .unwrap ( ) ;
1720
assert! ( s.signatures ( & r) .unwrap ( ) .is_empty ( ) ) ;
75167672 Andy McCall 1 month ago
1721
let sk = SecretKey {
1722
ed_seed: [ 1 ; 32 ] ,
1723
ml_seed: [ 2 ; 32 ] ,
1724
} ;
1983686f Andy McCall 1 month ago ↶
1725
let id = sk.identity ( " a" , " b" , 0 ) ;
1726
let key = s.put_identity ( & id) .unwrap ( ) ;
1727
assert_eq! ( s.get_identity ( & key) .unwrap ( ) , id) ;
1728
let sig = sk.sign ( Domain:: Change, & key, & r) ;
1729
s.put_signature ( & r, & sig) .unwrap ( ) ;
1730
s.put_signature ( & r, & sig) .unwrap ( ) ;
1731
assert_eq! ( s.signatures ( & r) .unwrap ( ) , vec! [ sig] ) ;
1732
1733
assert_eq! ( s.get ( & r) .unwrap ( ) .1 , b " x" ) ;
1734
}
1735
1736
# [ test ]
ff0af1ee unknown 1 month ago
1737
fn change_round_trip_through_store ( ) {
1738
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1739
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1740
let c = crate :: objects:: tests:: sample_change( ) ;
1741
let r = s.put_change ( & c) .unwrap ( ) ;
1742
assert_eq! ( r, c.hash ( ) ) ;
1743
assert_eq! ( s.get_change ( & r) .unwrap ( ) , c) ;
1744
}
2b872d07 Andy McCall 1 month ago ↶
1745
1746
fn xorshift ( state : & mut u64 ) -> u64 {
1747
* state ^ = * state < < 13 ;
1748
* state ^ = * state > > 7 ;
1749
* state ^ = * state < < 17 ;
1750
* state
1751
}
1752
1753
1754
1755
1756
# [ test ]
1757
fn corrupted_packs_and_indexes_fail_cleanly ( ) {
1758
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1759
let objects = dir.path ( ) .join ( " objects" ) ;
1760
let s = Store:: open( & objects) .unwrap ( ) ;
1761
let mut refs = Vec :: new( ) ;
1762
let mut seed = 0x9e3779b97f4a7c15 u64 ;
1763
for i in 0 .. 40 u32 {
1764
let len = ( xorshift ( & mut seed) % 5000 ) as usize ;
1765
let mut body = vec! [ 0 u8 ; len] ;
1766
for b in body.iter_mut ( ) {
75167672 Andy McCall 1 month ago
1767
* b = if i % 2 = = 0 {
1768
( xorshift ( & mut seed) & 0xff ) as u8
1769
} else {
1770
b ' a' + ( i % 26 ) as u8
1771
} ;
2b872d07 Andy McCall 1 month ago ↶
1772
}
1773
refs.push ( s.put ( ObjectType:: Chunk, & body) .unwrap ( ) ) ;
1774
}
1775
s.pack_loose ( ) .unwrap ( ) ;
75167672 Andy McCall 1 month ago
1776
let pack = fs:: read_dir( & objects)
1777
.unwrap ( )
1778
.filter_map ( | e | e.ok ( ) .map ( | e | e.path ( ) ) )
1779
.find ( | p | p.extension ( ) .is_some_and ( | x | x = = " pack" ) )
1780
.unwrap ( ) ;
2b872d07 Andy McCall 1 month ago ↶
1781
let idx = pack.with_extension ( " idx" ) ;
1782
let pristine_pack = fs:: read( & pack) .unwrap ( ) ;
1783
let pristine_idx = fs:: read( & idx) .unwrap ( ) ;
1784
1785
for round in 0 .. 300 u32 {
75167672 Andy McCall 1 month ago
1786
let ( path, pristine) = if round % 2 = = 0 {
1787
( & pack, & pristine_pack)
1788
} else {
1789
( & idx, & pristine_idx)
1790
} ;
2b872d07 Andy McCall 1 month ago ↶
1791
let mut data = pristine.clone ( ) ;
1792
match xorshift ( & mut seed) % 4 {
1793
0 => {
1794
let at = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
1795
data[ at] ^ = 1 < < ( xorshift ( & mut seed) % 8 ) ;
1796
}
1797
1 => {
1798
let at = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
1799
data[ at] = ( xorshift ( & mut seed) & 0xff ) as u8 ;
1800
}
1801
2 => {
1802
let keep = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
1803
data.truncate ( keep) ;
1804
}
1805
_ => {
1806
let at = ( xorshift ( & mut seed) as usize ) % data.len ( ) ;
1807
let n = ( ( xorshift ( & mut seed) % 8 ) + 1 ) as usize ;
1808
for k in 0 .. n.min ( data.len ( ) - at) {
1809
data[ at + k] = 0xff ;
1810
}
1811
}
1812
}
1813
fs:: write( path, & data) .unwrap ( ) ;
1814
1815
1816
if let Ok ( s2) = Store:: open( & objects) {
1817
for r in & refs {
1818
match s2.get ( r) {
75167672 Andy McCall 1 month ago
1819
Ok ( ( ty, body) ) => assert_eq! (
1820
hash_object ( ty, & body) ,
1821
* r,
1822
" a returned object always matches its reference"
1823
) ,
1824
Err ( StoreError:: Corrupt( .. ) )
1825
| Err ( StoreError:: NotFound( _ ) )
1826
| Err ( StoreError:: Io( _ ) ) => { }
2b872d07 Andy McCall 1 month ago ↶
1827
Err ( e) => panic! ( " unexpected error {e}" ) ,
1828
}
1829
}
1830
}
1831
fs:: write( path, pristine) .unwrap ( ) ;
1832
}
1833
1834
let s3 = Store:: open( & objects) .unwrap ( ) ;
1835
for r in & refs {
1836
let ( ty, body) = s3.get ( r) .unwrap ( ) ;
1837
assert_eq! ( hash_object ( ty, & body) , * r) ;
1838
}
1839
}
8f10a07a Andy McCall 1 month ago ↶
1840
1841
1842
1843
# [ test ]
1844
fn batches_write_loose_or_one_pack ( ) {
1845
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1846
let s = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
1847
let outer = s.begin_batch ( ) .unwrap ( ) ;
1848
let a = s.put ( ObjectType:: Chunk, b " small a" ) .unwrap ( ) ;
1849
{
1850
let inner = s.begin_batch ( ) .unwrap ( ) ;
1851
let b = s.put ( ObjectType:: Chunk, b " small b" ) .unwrap ( ) ;
1852
assert! ( s.has ( & b) ) ;
1853
assert_eq! ( s.get ( & b) .unwrap ( ) .1 , b " small b" ) ;
1854
inner.finish ( ) .unwrap ( ) ;
75167672 Andy McCall 1 month ago
1855
assert_eq! (
1856
s.loose_count ( ) .unwrap ( ) ,
1857
0 ,
1858
" the inner batch defers to the outer one"
1859
) ;
8f10a07a Andy McCall 1 month ago ↶
1860
}
1861
assert_eq! ( s.get ( & a) .unwrap ( ) .1 , b " small a" ) ;
75167672 Andy McCall 1 month ago
1862
assert_eq! (
1863
s.put ( ObjectType:: Chunk, b " small a" ) .unwrap ( ) ,
1864
a,
1865
" idempotent while pending"
1866
) ;
8f10a07a Andy McCall 1 month ago ↶
1867
outer.finish ( ) .unwrap ( ) ;
1868
assert_eq! ( s.loose_count ( ) .unwrap ( ) , 2 ) ;
1869
assert_eq! ( s.pack_count ( ) , 0 ) ;
1870
assert_eq! ( s.get ( & a) .unwrap ( ) .1 , b " small a" ) ;
1871
1872
1873
let big = s.begin_batch ( ) .unwrap ( ) ;
1874
let mut refs = Vec :: new( ) ;
1875
let mut seed = 7 u64 ;
1876
for i in 0 .. 300 u32 {
1877
let mut body = vec! [ b ' z' ; 40_000 ] ;
1878
if i % 3 = = 0 {
1879
for b in body.iter_mut ( ) {
1880
* b = ( xorshift ( & mut seed) & 0xff ) as u8 ;
1881
}
1882
}
1883
body[ .. 4 ] .copy_from_slice ( & i.to_le_bytes ( ) ) ;
75167672 Andy McCall 1 month ago
1884
let r = if i % 5 = = 0 {
1885
s.put_chunk_nocompress ( & body) .unwrap ( )
1886
} else {
1887
s.put ( ObjectType:: Chunk, & body) .unwrap ( )
1888
} ;
1889
assert_eq! (
1890
s.get ( & r) .unwrap ( ) .1 ,
1891
body,
1892
" readable while pending (object {i})"
1893
) ;
8f10a07a Andy McCall 1 month ago ↶
1894
refs.push ( ( r, body) ) ;
1895
}
1896
assert! ( s.has ( & refs[ 0 ] .0 ) ) ;
1897
big.finish ( ) .unwrap ( ) ;
1898
assert_eq! ( s.pack_count ( ) , 1 ) ;
75167672 Andy McCall 1 month ago
1899
assert_eq! (
1900
s.loose_count ( ) .unwrap ( ) ,
1901
2 ,
1902
" nothing from the big batch is loose"
1903
) ;
1904
assert! ( fs:: read_dir( dir.path ( ) .join ( " objects" ) )
1905
.unwrap ( )
1906
.flatten ( )
1907
.all ( | e | ! e.file_name ( ) .to_string_lossy ( ) .starts_with ( " tmp-" ) ) ) ;
8f10a07a Andy McCall 1 month ago ↶
1908
let s2 = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
1909
for ( r, body) in & refs {
1910
assert_eq! ( s2.get ( r) .unwrap ( ) .1 , * body) ;
1911
}
1912
1913
{
1914
let _b = s2.begin_batch ( ) .unwrap ( ) ;
1915
s2.put ( ObjectType:: Chunk, b " dropped" ) .unwrap ( ) ;
1916
}
75167672 Andy McCall 1 month ago
1917
assert_eq! (
1918
s2.get ( & hash_object ( ObjectType:: Chunk, b " dropped" ) )
1919
.unwrap ( )
1920
.1 ,
1921
b " dropped"
1922
) ;
afaba5f1 Andy McCall 1 month ago ↶
1923
}
1924
1925
# [ test ]
1926
fn get_many_reads_loose_and_packed_objects_in_order ( ) {
1927
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1928
let s = Store:: open( dir.path ( ) .join ( " objects" ) ) .unwrap ( ) ;
1929
let packed: Vec< ObjectRef> = ( 0 .. 20 )
1930
.map ( | i | {
1931
s.put ( ObjectType:: Chunk, format! ( " packed {i} " ) .as_bytes ( ) )
1932
.unwrap ( )
1933
} )
1934
.collect ( ) ;
1935
s.pack_loose ( ) .unwrap ( ) ;
1936
let loose: Vec< ObjectRef> = ( 0 .. 20 )
1937
.map ( | i | {
1938
s.put ( ObjectType:: Chunk, format! ( " loose {i} " ) .as_bytes ( ) )
1939
.unwrap ( )
1940
} )
1941
.collect ( ) ;
1942
let missing = hash_object ( ObjectType:: Chunk, b " never stored" ) ;
1943
let mut refs: Vec< ObjectRef> = Vec :: new( ) ;
1944
for i in 0 .. 20 {
1945
refs.push ( loose[ i] ) ;
1946
refs.push ( packed[ i] ) ;
1947
}
1948
refs.push ( missing) ;
1949
let got = s.get_many ( & refs) ;
1950
assert_eq! ( got.len ( ) , refs.len ( ) ) ;
1951
for ( i, r) in refs.iter ( ) .enumerate ( ) .take ( 40 ) {
1952
let want = if i % 2 = = 0 {
1953
format! ( " loose {} " , i / 2 )
1954
} else {
1955
format! ( " packed {} " , i / 2 )
1956
} ;
1957
let ( ty, body) = got[ i] .as_ref ( ) .unwrap ( ) ;
1958
assert_eq! (
1959
( * ty, body.as_slice ( ) ) ,
1960
( ObjectType:: Chunk, want.as_bytes ( ) ) ,
1961
" {r:?}"
1962
) ;
1963
}
1964
assert! ( matches! ( got[ 40 ] , Err ( StoreError:: NotFound( _ ) ) ) ) ;
a9f686ed Andy McCall 1 month ago ↶
1965
}
1966
}
1967
1968
# [ cfg ( test ) ]
1969
mod batch_tests {
1970
use super :: * ;
1971
1972
# [ test ]
1973
fn a_large_batch_packs_every_object_and_indexes_them_all ( ) {
1974
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
1975
let store = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1976
let mut refs = Vec :: new( ) ;
1977
{
1978
let batch = store.begin_batch ( ) .unwrap ( ) ;
1979
for i in 0 .. 1000 u32 {
1980
let body = format! ( " object {i} {} " , " x" .repeat ( 20_000 + i as usize ) ) .into_bytes ( ) ;
1981
refs.push ( store.put ( ObjectType:: Blob, & body) .unwrap ( ) ) ;
1982
}
1983
batch.finish ( ) .unwrap ( ) ;
1984
}
1985
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
1986
for r in & refs {
1987
again
1988
.get ( r)
1989
.unwrap_or_else ( | e | panic! ( " {}: {e}" , r.short ( 12 ) ) ) ;
1990
}
1991
}
1992
}
1993
1994
# [ cfg ( test ) ]
1995
mod size_tests {
1996
use super :: * ;
1997
1998
# [ test ]
1999
fn an_object_over_the_limit_is_refused_and_nothing_is_written ( ) {
2000
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2001
let store = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2002
let big = vec! [ b ' x' ; MAX_OBJECT_LEN as usize + 1 ] ;
2003
{
2004
let batch = store.begin_batch ( ) .unwrap ( ) ;
2005
store.put ( ObjectType:: Blob, b " small" ) .unwrap ( ) ;
2006
let e = store.put ( ObjectType:: Change, & big) .unwrap_err ( ) ;
2007
assert! (
2008
matches! ( e, StoreError:: TooLarge { kind: " change" , .. } ) ,
2009
" {e}"
2010
) ;
2011
assert! ( e.to_string ( ) .contains ( " commit it in parts" ) , " {e}" ) ;
2012
batch.finish ( ) .unwrap ( ) ;
2013
}
2014
2015
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2016
again.get ( & hash_object ( ObjectType:: Blob, b " small" ) ) .unwrap ( ) ;
6f8aeb99 Andy McCall 1 month ago ↶
2017
}
2018
}
2019
2020
# [ cfg ( test ) ]
2021
mod text_tests {
2022
use super :: * ;
2023
use crate :: objects:: { AtomRef, Edit, CHANGE_VERSION } ;
2024
2025
fn large_change ( ) -> Change {
2026
let mut c = crate :: objects:: tests:: sample_change( ) ;
2027
assert_eq! ( c.version, CHANGE_VERSION ) ;
2028
c.edits[ 0 ] = Edit:: Insert {
2029
node: crate :: ids:: NodeId( [ 7 ; 16 ] ) ,
2030
after: AtomRef:: Start,
2031
before: AtomRef:: End,
2032
lines: ( 0 .. 2000 )
2033
.map ( | i | format! ( " line {i} \n " ) .into_bytes ( ) )
2034
.collect ( ) ,
2035
} ;
2036
c
2037
}
2038
2039
# [ test ]
2040
fn a_large_insert_is_stored_beside_its_change_and_read_back ( ) {
2041
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2042
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2043
let c = large_change ( ) ;
2044
let r = s.put_change ( & c) .unwrap ( ) ;
2045
assert_eq! ( r, c.hash ( ) ) ;
2046
let ( _ , body) = s.get ( & r) .unwrap ( ) ;
2047
assert! (
2048
body.len ( ) < 1024 ,
2049
" the change holds a reference, not {} bytes of lines" ,
2050
body.len ( )
2051
) ;
2052
let ( back, parts) = s.get_change_parts ( & r) .unwrap ( ) ;
2053
assert_eq! ( back, c) ;
2054
2055
assert_eq! ( parts.len ( ) , 2 ) ;
2056
for p in & parts {
2057
assert! ( s.has ( p) ) ;
2058
}
2059
2060
let n = s.list ( ) .unwrap ( ) .len ( ) ;
2061
s.put_change ( & c) .unwrap ( ) ;
2062
assert_eq! ( s.list ( ) .unwrap ( ) .len ( ) , n) ;
2063
}
2064
2065
# [ test ]
2066
fn a_change_whose_text_blob_is_missing_is_reported_not_misread ( ) {
2067
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2068
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2069
let c = large_change ( ) ;
2070
let r = s.put_change ( & c) .unwrap ( ) ;
2071
let ( _ , parts) = s.get_change_parts ( & r) .unwrap ( ) ;
2072
fs:: remove_file( s.path_for ( & parts[ 0 ] ) ) .unwrap ( ) ;
2073
let e = s.get_change ( & r) .unwrap_err ( ) ;
2074
assert! (
2075
matches! ( & e, StoreError:: Corrupt( h, why) if * h = = r & & why.contains ( " missing" ) ) ,
2076
" {e}"
2077
) ;
192fad1e Andy McCall 1 month ago ↶
2078
}
2079
}
2080
2081
# [ cfg ( test ) ]
2082
mod put_many_tests {
2083
use super :: * ;
2084
2085
# [ test ]
2086
fn many_objects_in_a_batch_are_compressed_together_and_all_read_back ( ) {
2087
let dir = tempfile:: tempdir( ) .unwrap ( ) ;
2088
let s = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2089
let before = s.put ( ObjectType:: Chunk, b " already here" ) .unwrap ( ) ;
2090
let bodies: Vec< Vec< u8 > > = ( 0 .. 200 u32 )
2091
.map ( | i | format! ( " chunk {i} " ) .repeat ( 6000 ) .into_bytes ( ) )
2092
.collect ( ) ;
2093
let mut objects: Vec< ( ObjectType, & [u8 ]) > = bodies
2094
.iter ( )
2095
.map ( | b | ( ObjectType:: Chunk, b.as_slice ( ) ) )
2096
.collect ( ) ;
2097
objects.push ( ( ObjectType:: Chunk, bodies[ 0 ] .as_slice ( ) ) ) ;
2098
objects.push ( ( ObjectType:: Chunk, b " already here" ) ) ;
2099
let refs = {
2100
let batch = s.begin_batch ( ) .unwrap ( ) ;
2101
let refs = s.put_many ( & objects) .unwrap ( ) ;
2102
batch.finish ( ) .unwrap ( ) ;
2103
refs
2104
} ;
2105
assert_eq! ( refs.len ( ) , objects.len ( ) ) ;
2106
assert_eq! ( refs[ 200 ] , refs[ 0 ] , " a repeat is the same object" ) ;
2107
assert_eq! ( refs[ 201 ] , before) ;
2108
let again = Store:: open( dir.path ( ) ) .unwrap ( ) ;
2109
for ( r, b) in refs.iter ( ) .zip ( & objects) {
2110
assert_eq! ( again.get ( r) .unwrap ( ) .1 , b.1 ) ;
2111
}
a17fc622 Andy McCall 1 month ago ↶
2112
}
2113
}
2114
2115
2116
fn remove_pack_files ( pack : & Path) -> io:: Result< ( ) > {
2117
fs:: remove_file( pack) ? ;
2118
fs:: remove_file( pack.with_extension ( " idx" ) ) ? ;
2119
match fs:: remove_file( pack.with_extension ( " dict" ) ) {
2120
Err ( e) if e.kind ( ) ! = io:: ErrorKind:: NotFound => Err ( e) ,
2121
_ => Ok ( ( ) ) ,
8f10a07a Andy McCall 1 month ago ↶
2122
}
ff0af1ee unknown 1 month ago
2123
}