pub fn resolve(
objects_directory: impl Into<PathBuf>,
current_dir: impl AsRef<Path>
) -> Result<Vec<PathBuf>, Error>
Expand description
Given an objects_directory
, try to resolve alternate object directories possibly located in the
./info/alternates
file into canonical paths and resolve relative paths with the help of the current_dir
.
If no alternate object database was resolved, the resulting Vec
is empty (it is not an error
if there are no alternates).
It is an error once a repository is seen again as it would lead to a cycle.
Examples found in repository?
src/store_impls/dynamic/init.rs (line 93)
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
pub fn at_opts(
objects_dir: impl Into<PathBuf>,
replacements: impl IntoIterator<Item = (git_hash::ObjectId, git_hash::ObjectId)>,
Options {
slots,
object_hash,
use_multi_pack_index,
current_dir,
}: Options,
) -> std::io::Result<Self> {
let objects_dir = objects_dir.into();
let current_dir = current_dir.map(Ok).unwrap_or_else(std::env::current_dir)?;
if !objects_dir.is_dir() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other, // TODO: use NotADirectory when stabilized
format!("'{}' wasn't a directory", objects_dir.display()),
));
}
let slot_count = match slots {
Slots::Given(n) => n as usize,
Slots::AsNeededByDiskState { multiplier, minimum } => {
let mut db_paths = crate::alternate::resolve(&objects_dir, ¤t_dir)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?;
db_paths.insert(0, objects_dir.clone());
let num_slots = super::Store::collect_indices_and_mtime_sorted_by_size(db_paths, None, None)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?
.len();
((num_slots as f32 * multiplier) as usize).max(minimum)
}
};
if slot_count > crate::store::types::PackId::max_indices() {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Cannot use more than 1^15 slots",
));
}
let mut replacements: Vec<_> = replacements.into_iter().collect();
replacements.sort_by(|a, b| a.0.cmp(&b.0));
Ok(Store {
current_dir,
write: Default::default(),
replacements,
path: objects_dir,
files: Vec::from_iter(std::iter::repeat_with(MutableIndexAndPack::default).take(slot_count)),
index: ArcSwap::new(Arc::new(SlotMapIndex::default())),
use_multi_pack_index,
object_hash,
num_handles_stable: Default::default(),
num_handles_unstable: Default::default(),
num_disk_state_consolidation: Default::default(),
})
}
More examples
src/store_impls/dynamic/load_index.rs (line 208)
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
pub(crate) fn consolidate_with_disk_state(
&self,
needs_init: bool,
load_new_index: bool,
) -> Result<Option<Snapshot>, Error> {
let index = self.index.load();
let previous_index_state = Arc::as_ptr(&index) as usize;
// IMPORTANT: get a lock after we recorded the previous state.
let write = self.write.lock();
let objects_directory = &self.path;
// Now we know the index isn't going to change anymore, even though threads might still load indices in the meantime.
let index = self.index.load();
if previous_index_state != Arc::as_ptr(&index) as usize {
// Someone else took the look before and changed the index. Return it without doing any additional work.
return Ok(Some(self.collect_snapshot()));
}
let was_uninitialized = !index.is_initialized();
// We might not be able to detect by pointer if the state changed, as this itself is racy. So we keep track of double-initialization
// using a flag, which means that if `needs_init` was true we saw the index uninitialized once, but now that we are here it's
// initialized meaning that somebody was faster and we couldn't detect it by comparisons to the index.
// If so, make sure we collect the snapshot instead of returning None in case nothing actually changed, which is likely with a
// race like this.
if !was_uninitialized && needs_init {
return Ok(Some(self.collect_snapshot()));
}
self.num_disk_state_consolidation.fetch_add(1, Ordering::Relaxed);
let db_paths: Vec<_> = std::iter::once(objects_directory.to_owned())
.chain(crate::alternate::resolve(objects_directory, &self.current_dir)?)
.collect();
// turn db paths into loose object databases. Reuse what's there, but only if it is in the right order.
let loose_dbs = if was_uninitialized
|| db_paths.len() != index.loose_dbs.len()
|| db_paths
.iter()
.zip(index.loose_dbs.iter().map(|ldb| &ldb.path))
.any(|(lhs, rhs)| lhs != rhs)
{
Arc::new(
db_paths
.iter()
.map(|path| crate::loose::Store::at(path, self.object_hash))
.collect::<Vec<_>>(),
)
} else {
Arc::clone(&index.loose_dbs)
};
let indices_by_modification_time = Self::collect_indices_and_mtime_sorted_by_size(
db_paths,
index.slot_indices.len().into(),
self.use_multi_pack_index.then(|| self.object_hash),
)?;
let mut idx_by_index_path: BTreeMap<_, _> = index
.slot_indices
.iter()
.filter_map(|&idx| {
let f = &self.files[idx];
Option::as_ref(&f.files.load()).map(|f| (f.index_path().to_owned(), idx))
})
.collect();
let mut new_slot_map_indices = Vec::new(); // these indices into the slot map still exist there/didn't change
let mut index_paths_to_add = was_uninitialized
.then(|| VecDeque::with_capacity(indices_by_modification_time.len()))
.unwrap_or_default();
// Figure out this number based on what we see while handling the existing indices
let mut num_loaded_indices = 0;
for (index_info, mtime) in indices_by_modification_time.into_iter().map(|(a, b, _)| (a, b)) {
match idx_by_index_path.remove(index_info.path()) {
Some(slot_idx) => {
let slot = &self.files[slot_idx];
let files_guard = slot.files.load();
let files =
Option::as_ref(&files_guard).expect("slot is set or we wouldn't know it points to this file");
if index_info.is_multi_index() && files.mtime() != mtime {
// we have a changed multi-pack index. We can't just change the existing slot as it may alter slot indices
// that are currently available. Instead we have to move what's there into a new slot, along with the changes,
// and later free the slot or dispose of the index in the slot (like we do for removed/missing files).
index_paths_to_add.push_back((index_info, mtime, Some(slot_idx)));
// If the current slot is loaded, the soon-to-be copied multi-index path will be loaded as well.
if files.index_is_loaded() {
num_loaded_indices += 1;
}
} else {
// packs and indices are immutable, so no need to check modification times. Unchanged multi-pack indices also
// are handled like this just to be sure they are in the desired state. For these, the only way this could happen
// is if somebody deletes and then puts back
if Self::assure_slot_matches_index(&write, slot, index_info, mtime, index.generation) {
num_loaded_indices += 1;
}
new_slot_map_indices.push(slot_idx);
}
}
None => index_paths_to_add.push_back((index_info, mtime, None)),
}
}
let needs_stable_indices = self.maintain_stable_indices(&write);
let mut next_possibly_free_index = index
.slot_indices
.iter()
.max()
.map(|idx| (idx + 1) % self.files.len())
.unwrap_or(0);
let mut num_indices_checked = 0;
let mut needs_generation_change = false;
let mut slot_indices_to_remove: Vec<_> = idx_by_index_path.into_values().collect();
while let Some((mut index_info, mtime, move_from_slot_idx)) = index_paths_to_add.pop_front() {
'increment_slot_index: loop {
if num_indices_checked == self.files.len() {
return Err(Error::InsufficientSlots {
current: self.files.len(),
needed: index_paths_to_add.len() + 1, /*the one currently popped off*/
});
}
let slot_index = next_possibly_free_index;
let slot = &self.files[slot_index];
next_possibly_free_index = (next_possibly_free_index + 1) % self.files.len();
num_indices_checked += 1;
match move_from_slot_idx {
Some(move_from_slot_idx) => {
debug_assert!(index_info.is_multi_index(), "only set for multi-pack indices");
if slot_index == move_from_slot_idx {
// don't try to move onto ourselves
continue 'increment_slot_index;
}
match Self::try_set_index_slot(
&write,
slot,
index_info,
mtime,
index.generation,
needs_stable_indices,
) {
Ok(dest_was_empty) => {
slot_indices_to_remove.push(move_from_slot_idx);
new_slot_map_indices.push(slot_index);
// To avoid handling out the wrong pack (due to reassigned pack ids), declare this a new generation.
if !dest_was_empty {
needs_generation_change = true;
}
break 'increment_slot_index;
}
Err(unused_index_info) => index_info = unused_index_info,
}
}
None => {
match Self::try_set_index_slot(
&write,
slot,
index_info,
mtime,
index.generation,
needs_stable_indices,
) {
Ok(dest_was_empty) => {
new_slot_map_indices.push(slot_index);
if !dest_was_empty {
needs_generation_change = true;
}
break 'increment_slot_index;
}
Err(unused_index_info) => index_info = unused_index_info,
}
}
}
// This isn't racy as it's only us who can change the Option::Some/None state of a slot.
}
}
assert_eq!(
index_paths_to_add.len(),
0,
"By this time we have assigned all new files to slots"
);
let generation = if needs_generation_change {
index.generation.checked_add(1).ok_or(Error::GenerationOverflow)?
} else {
index.generation
};
let index_unchanged = index.slot_indices == new_slot_map_indices;
if generation != index.generation {
assert!(
!index_unchanged,
"if the generation changed, the slot index must have changed for sure"
);
}
if !index_unchanged || loose_dbs != index.loose_dbs {
let new_index = Arc::new(SlotMapIndex {
slot_indices: new_slot_map_indices,
loose_dbs,
generation,
// if there was a prior generation, some indices might already be loaded. But we deal with it by trying to load the next index then,
// until we find one.
next_index_to_load: index_unchanged
.then(|| Arc::clone(&index.next_index_to_load))
.unwrap_or_default(),
loaded_indices: index_unchanged
.then(|| Arc::clone(&index.loaded_indices))
.unwrap_or_else(|| Arc::new(num_loaded_indices.into())),
num_indices_currently_being_loaded: Default::default(),
});
self.index.store(new_index);
}
// deleted items - remove their slots AFTER we have set the new index if we may alter indices, otherwise we only declare them garbage.
// removing slots may cause pack loading to fail, and they will then reload their indices.
for slot in slot_indices_to_remove.into_iter().map(|idx| &self.files[idx]) {
let _lock = slot.write.lock();
let mut files = slot.files.load_full();
let files_mut = Arc::make_mut(&mut files);
if needs_stable_indices {
if let Some(files) = files_mut.as_mut() {
files.trash();
// generation stays the same, as it's the same value still but scheduled for eventual removal.
}
} else {
*files_mut = None;
};
slot.files.store(files);
if !needs_stable_indices {
// Not racy due to lock, generation must be set after unsetting the slot value AND storing it.
slot.generation.store(generation, Ordering::SeqCst);
}
}
let new_index = self.index.load();
Ok(if index.state_id() == new_index.state_id() {
// there was no change, and nothing was loaded in the meantime, reflect that in the return value to not get into loops
None
} else {
if load_new_index {
self.load_next_index(new_index);
}
Some(self.collect_snapshot())
})
}