1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::{collections::HashSet, convert::TryInto, ops::Deref};
use git_hash::{oid, ObjectId};
use git_pack::{cache::DecodeEntry, data::entry::Location};
use crate::store::{handle, load_index};
mod error {
use crate::{loose, pack};
#[derive(thiserror::Error, Debug)]
#[allow(missing_docs)]
pub enum Error {
#[error("An error occurred while obtaining an object from the loose object store")]
Loose(#[from] loose::find::Error),
#[error("An error occurred looking up a prefix which requires iteration")]
LooseWalkDir(#[from] loose::iter::Error),
#[error("An error occurred while obtaining an object from the packed object store")]
Pack(#[from] pack::data::decode_entry::Error),
#[error(transparent)]
LoadIndex(#[from] crate::store::load_index::Error),
#[error(transparent)]
LoadPack(#[from] std::io::Error),
#[error("Object {} referred to its base object {} by its id but it's not within a multi-index", .id, .base_id)]
ThinPackAtRest {
base_id: git_hash::ObjectId,
id: git_hash::ObjectId,
},
#[error("Reached recursion limit of {} while resolving ref delta bases for {}", .max_depth, .id)]
DeltaBaseRecursionLimit {
max_depth: usize,
id: git_hash::ObjectId,
},
#[error("The base object {} could not be found but is required to decode {}", .base_id, .id)]
DeltaBaseMissing {
base_id: git_hash::ObjectId,
id: git_hash::ObjectId,
},
#[error("An error occurred when looking up a ref delta base object {} to decode {}", .base_id, .id)]
DeltaBaseLookup {
#[source]
err: Box<Self>,
base_id: git_hash::ObjectId,
id: git_hash::ObjectId,
},
}
#[derive(Copy, Clone)]
pub(crate) struct DeltaBaseRecursion<'a> {
pub depth: usize,
pub original_id: &'a git_hash::oid,
}
impl<'a> DeltaBaseRecursion<'a> {
pub fn new(id: &'a git_hash::oid) -> Self {
Self {
original_id: id,
depth: 0,
}
}
pub fn inc_depth(mut self) -> Self {
self.depth += 1;
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_size() {
let actual = std::mem::size_of::<Error>();
assert!(actual <= 88, "{} <= 88: should not grow without us noticing", actual);
}
}
}
pub use error::Error;
use crate::{
find::{PotentialPrefix, PrefixLookupResult},
store::types::PackId,
Find,
};
impl<S> super::Handle<S>
where
S: Deref<Target = super::Store> + Clone,
{
pub fn packed_object_count(&self) -> Result<u64, Error> {
let mut count = self.packed_object_count.borrow_mut();
match *count {
Some(count) => Ok(count),
None => {
let mut snapshot = self.snapshot.borrow_mut();
*snapshot = self.store.load_all_indices()?;
let mut obj_count = 0;
for index in &snapshot.indices {
obj_count += index.num_objects() as u64;
}
*count = Some(obj_count);
Ok(obj_count)
}
}
}
pub fn disambiguate_prefix(&self, mut candidate: PotentialPrefix) -> Result<Option<git_hash::Prefix>, Error> {
let max_hex_len = candidate.id().kind().len_in_hex();
if candidate.hex_len() == max_hex_len {
return Ok(self.contains(candidate.id()).then(|| candidate.to_prefix()));
}
while candidate.hex_len() != max_hex_len {
let res = self.lookup_prefix(candidate.to_prefix(), None)?;
match res {
Some(Ok(_id)) => return Ok(Some(candidate.to_prefix())),
Some(Err(())) => {
candidate.inc_hex_len();
continue;
}
None => return Ok(None),
}
}
Ok(Some(candidate.to_prefix()))
}
pub fn lookup_prefix(
&self,
prefix: git_hash::Prefix,
mut candidates: Option<&mut HashSet<git_hash::ObjectId>>,
) -> Result<Option<PrefixLookupResult>, Error> {
let mut candidate: Option<ObjectId> = None;
loop {
let snapshot = self.snapshot.borrow();
for index in snapshot.indices.iter() {
#[allow(clippy::needless_option_as_deref)] let lookup_result = index.lookup_prefix(prefix, candidates.as_deref_mut());
if candidates.is_none() && !check_candidate(lookup_result, &mut candidate) {
return Ok(Some(Err(())));
}
}
for lodb in snapshot.loose_dbs.iter() {
#[allow(clippy::needless_option_as_deref)] let lookup_result = lodb.lookup_prefix(prefix, candidates.as_deref_mut())?;
if candidates.is_none() && !check_candidate(lookup_result, &mut candidate) {
return Ok(Some(Err(())));
}
}
match self.store.load_one_index(self.refresh, snapshot.marker)? {
Some(new_snapshot) => {
drop(snapshot);
*self.snapshot.borrow_mut() = new_snapshot;
}
None => {
return match &candidates {
Some(candidates) => match candidates.len() {
0 => Ok(None),
1 => Ok(candidates.iter().cloned().next().map(Ok)),
_ => Ok(Some(Err(()))),
},
None => Ok(candidate.map(Ok)),
};
}
}
}
fn check_candidate(lookup_result: Option<PrefixLookupResult>, candidate: &mut Option<ObjectId>) -> bool {
match (lookup_result, &*candidate) {
(Some(Ok(oid)), Some(candidate)) if *candidate != oid => false,
(Some(Ok(_)), Some(_)) | (None, None) | (None, Some(_)) => true,
(Some(Err(())), _) => false,
(Some(Ok(oid)), None) => {
*candidate = Some(oid);
true
}
}
}
}
fn try_find_cached_inner<'a, 'b>(
&'b self,
mut id: &'b oid,
buffer: &'a mut Vec<u8>,
pack_cache: &mut impl DecodeEntry,
snapshot: &mut load_index::Snapshot,
recursion: Option<error::DeltaBaseRecursion<'_>>,
) -> Result<Option<(git_object::Data<'a>, Option<Location>)>, Error> {
if let Some(r) = recursion {
if r.depth >= self.max_recursion_depth {
return Err(Error::DeltaBaseRecursionLimit {
max_depth: self.max_recursion_depth,
id: r.original_id.to_owned(),
});
}
} else if !self.ignore_replacements {
if let Ok(pos) = self
.store
.replacements
.binary_search_by(|(map_this, _)| map_this.as_ref().cmp(id))
{
id = self.store.replacements[pos].1.as_ref();
}
}
'outer: loop {
{
let marker = snapshot.marker;
for (idx, index) in snapshot.indices.iter_mut().enumerate() {
if let Some(handle::index_lookup::Outcome {
object_index: handle::IndexForObjectInPack { pack_id, pack_offset },
index_file,
pack: possibly_pack,
}) = index.lookup(id)
{
let pack = match possibly_pack {
Some(pack) => pack,
None => match self.store.load_pack(pack_id, marker)? {
Some(pack) => {
*possibly_pack = Some(pack);
possibly_pack.as_deref().expect("just put it in")
}
None => {
match self.store.load_one_index(self.refresh, snapshot.marker)? {
Some(new_snapshot) => {
*snapshot = new_snapshot;
self.clear_cache();
continue 'outer;
}
None => {
return Ok(None);
}
}
}
},
};
let entry = pack.entry(pack_offset);
let header_size = entry.header_size();
let res = match pack.decode_entry(
entry,
buffer,
|id, _out| {
index_file
.pack_offset_by_id(id)
.map(|pack_offset| git_pack::data::ResolvedBase::InPack(pack.entry(pack_offset)))
},
pack_cache,
) {
Ok(r) => Ok((
git_object::Data {
kind: r.kind,
data: buffer.as_slice(),
},
Some(git_pack::data::entry::Location {
pack_id: pack.id,
pack_offset,
entry_size: r.compressed_size + header_size,
}),
)),
Err(git_pack::data::decode_entry::Error::DeltaBaseUnresolved(base_id)) => {
let mut buf = Vec::new();
let obj_kind = self
.try_find_cached_inner(
&base_id,
&mut buf,
pack_cache,
snapshot,
recursion
.map(|r| r.inc_depth())
.or_else(|| error::DeltaBaseRecursion::new(id).into()),
)
.map_err(|err| Error::DeltaBaseLookup {
err: Box::new(err),
base_id,
id: id.to_owned(),
})?
.ok_or_else(|| Error::DeltaBaseMissing {
base_id,
id: id.to_owned(),
})?
.0
.kind;
let handle::index_lookup::Outcome {
object_index:
handle::IndexForObjectInPack {
pack_id: _,
pack_offset,
},
index_file,
pack: possibly_pack,
} = match snapshot.indices[idx].lookup(id) {
Some(res) => res,
None => {
let mut out = None;
for index in snapshot.indices.iter_mut() {
out = index.lookup(id);
if out.is_some() {
break;
}
}
out.unwrap_or_else(|| {
panic!("could not find object {} in any index after looking up one of its base objects {}", id, base_id)
})
}
};
let pack = possibly_pack
.as_ref()
.expect("pack to still be available like just now");
let entry = pack.entry(pack_offset);
let header_size = entry.header_size();
pack.decode_entry(
entry,
buffer,
|id, out| {
index_file
.pack_offset_by_id(id)
.map(|pack_offset| {
git_pack::data::ResolvedBase::InPack(pack.entry(pack_offset))
})
.or_else(|| {
(id == base_id).then(|| {
out.resize(buf.len(), 0);
out.copy_from_slice(buf.as_slice());
git_pack::data::ResolvedBase::OutOfPack {
kind: obj_kind,
end: out.len(),
}
})
})
},
pack_cache,
)
.map(move |r| {
(
git_object::Data {
kind: r.kind,
data: buffer.as_slice(),
},
Some(git_pack::data::entry::Location {
pack_id: pack.id,
pack_offset,
entry_size: r.compressed_size + header_size,
}),
)
})
}
Err(err) => Err(err),
}?;
if idx != 0 {
snapshot.indices.swap(0, idx);
}
return Ok(Some(res));
}
}
}
for lodb in snapshot.loose_dbs.iter() {
if lodb.contains(id) {
return lodb
.try_find(id, buffer)
.map(|obj| obj.map(|obj| (obj, None)))
.map_err(Into::into);
}
}
match self.store.load_one_index(self.refresh, snapshot.marker)? {
Some(new_snapshot) => {
*snapshot = new_snapshot;
self.clear_cache();
}
None => return Ok(None),
}
}
}
fn clear_cache(&self) {
self.packed_object_count.borrow_mut().take();
}
}
impl<S> git_pack::Find for super::Handle<S>
where
S: Deref<Target = super::Store> + Clone,
{
type Error = Error;
fn contains(&self, id: impl AsRef<oid>) -> bool {
let id = id.as_ref();
let mut snapshot = self.snapshot.borrow_mut();
loop {
for (idx, index) in snapshot.indices.iter().enumerate() {
if index.contains(id) {
if idx != 0 {
snapshot.indices.swap(0, idx);
}
return true;
}
}
for lodb in snapshot.loose_dbs.iter() {
if lodb.contains(id) {
return true;
}
}
match self.store.load_one_index(self.refresh, snapshot.marker) {
Ok(Some(new_snapshot)) => {
*snapshot = new_snapshot;
self.clear_cache();
}
Ok(None) => return false, Err(_) => return false, }
}
}
fn try_find_cached<'a>(
&self,
id: impl AsRef<oid>,
buffer: &'a mut Vec<u8>,
pack_cache: &mut impl DecodeEntry,
) -> Result<Option<(git_object::Data<'a>, Option<Location>)>, Self::Error> {
let id = id.as_ref();
let mut snapshot = self.snapshot.borrow_mut();
self.try_find_cached_inner(id, buffer, pack_cache, &mut snapshot, None)
}
fn location_by_oid(&self, id: impl AsRef<oid>, buf: &mut Vec<u8>) -> Option<Location> {
assert!(
matches!(self.token.as_ref(), Some(handle::Mode::KeepDeletedPacksAvailable)),
"BUG: handle must be configured to `prevent_pack_unload()` before using this method"
);
assert!(self.store_ref().replacements.is_empty() || self.ignore_replacements, "Everything related to packing must not use replacements. These are not used here, but it should be turned off for good measure.");
let id = id.as_ref();
let mut snapshot = self.snapshot.borrow_mut();
'outer: loop {
{
let marker = snapshot.marker;
for (idx, index) in snapshot.indices.iter_mut().enumerate() {
if let Some(handle::index_lookup::Outcome {
object_index: handle::IndexForObjectInPack { pack_id, pack_offset },
index_file: _,
pack: possibly_pack,
}) = index.lookup(id)
{
let pack = match possibly_pack {
Some(pack) => pack,
None => match self.store.load_pack(pack_id, marker).ok()? {
Some(pack) => {
*possibly_pack = Some(pack);
possibly_pack.as_deref().expect("just put it in")
}
None => {
match self.store.load_one_index(self.refresh, snapshot.marker).ok()? {
Some(new_snapshot) => {
*snapshot = new_snapshot;
self.clear_cache();
continue 'outer;
}
None => {
return None;
}
}
}
},
};
let entry = pack.entry(pack_offset);
buf.resize(entry.decompressed_size.try_into().expect("representable size"), 0);
assert_eq!(pack.id, pack_id.to_intrinsic_pack_id(), "both ids must always match");
let res = pack.decompress_entry(&entry, buf).ok().map(|entry_size_past_header| {
git_pack::data::entry::Location {
pack_id: pack.id,
pack_offset,
entry_size: entry.header_size() + entry_size_past_header,
}
});
if idx != 0 {
snapshot.indices.swap(0, idx);
}
return res;
}
}
}
match self.store.load_one_index(self.refresh, snapshot.marker).ok()? {
Some(new_snapshot) => {
*snapshot = new_snapshot;
self.clear_cache();
}
None => return None,
}
}
}
fn pack_offsets_and_oid(&self, pack_id: u32) -> Option<Vec<(u64, git_hash::ObjectId)>> {
assert!(
matches!(self.token.as_ref(), Some(handle::Mode::KeepDeletedPacksAvailable)),
"BUG: handle must be configured to `prevent_pack_unload()` before using this method"
);
let pack_id = PackId::from_intrinsic_pack_id(pack_id);
loop {
let snapshot = self.snapshot.borrow();
{
for index in snapshot.indices.iter() {
if let Some(iter) = index.iter(pack_id) {
return Some(iter.map(|e| (e.pack_offset, e.oid)).collect());
}
}
}
match self.store.load_one_index(self.refresh, snapshot.marker).ok()? {
Some(new_snapshot) => {
drop(snapshot);
*self.snapshot.borrow_mut() = new_snapshot;
}
None => return None,
}
}
}
fn entry_by_location(&self, location: &Location) -> Option<git_pack::find::Entry> {
assert!(
matches!(self.token.as_ref(), Some(handle::Mode::KeepDeletedPacksAvailable)),
"BUG: handle must be configured to `prevent_pack_unload()` before using this method"
);
let pack_id = PackId::from_intrinsic_pack_id(location.pack_id);
let mut snapshot = self.snapshot.borrow_mut();
let marker = snapshot.marker;
loop {
{
for index in snapshot.indices.iter_mut() {
if let Some(possibly_pack) = index.pack(pack_id) {
let pack = match possibly_pack {
Some(pack) => pack,
None => {
let pack = self.store.load_pack(pack_id, marker).ok()?.expect(
"BUG: pack must exist from previous call to location_by_oid() and must not be unloaded",
);
*possibly_pack = Some(pack);
possibly_pack.as_deref().expect("just put it in")
}
};
return pack
.entry_slice(location.entry_range(location.pack_offset))
.map(|data| git_pack::find::Entry {
data: data.to_owned(),
version: pack.version(),
});
}
}
}
snapshot.indices.insert(
0,
self.store
.index_by_id(pack_id, marker)
.expect("BUG: index must always be present, must not be unloaded or overwritten"),
);
}
}
}
impl<S> crate::Find for super::Handle<S>
where
S: Deref<Target = super::Store> + Clone,
Self: git_pack::Find,
{
type Error = <Self as git_pack::Find>::Error;
fn contains(&self, id: impl AsRef<oid>) -> bool {
git_pack::Find::contains(self, id)
}
fn try_find<'a>(
&self,
id: impl AsRef<oid>,
buffer: &'a mut Vec<u8>,
) -> Result<Option<git_object::Data<'a>>, Self::Error> {
git_pack::Find::try_find(self, id, buffer).map(|t| t.map(|t| t.0))
}
}