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