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