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