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