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