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