Debian Codegraph @

rust/hg-core/src/file_index/mod.rs

raw
1 //! The file index maps file paths in a repository to integer tokens.
2 //! See `mercurial/helptext/internals/fileindex.txt` for more details.
3
4 use std::collections::HashSet;
5 use std::io::BufWriter;
6 use std::io::Seek;
7 use std::io::SeekFrom;
8 use std::io::Write;
9 use std::ops::Deref;
10 use std::path::Path;
11 use std::path::PathBuf;
12
13 use bytes_cast::BytesCast;
14 use indexmap::IndexSet;
15 use mutable_tree::MutableTree;
16 use mutable_tree::SerializeMode;
17 pub use on_disk::DebugTreeChild;
18 pub use on_disk::DebugTreeNode;
19 pub use on_disk::DebugTreeNodeIter;
20 use on_disk::Docket;
21 pub use on_disk::Error;
22 use on_disk::FileIndexView;
23 use on_disk::GarbageEntry;
24 use on_disk::Metadata;
25 use on_disk::OwnedDataFiles;
26 use on_disk::OwnedFileIndexView;
27 pub use on_disk::PathInfo;
28 use on_disk::EMPTY_META_BYTES;
29
30 use crate::errors::HgError;
31 use crate::errors::IoResultExt;
32 use crate::transaction::Transaction;
33 use crate::utils::docket::FileUid;
34 use crate::utils::hg_path::HgPath;
35 use crate::utils::hg_path::HgPathBuf;
36 use crate::utils::u32_u;
37 use crate::utils::u_u32;
38 use crate::vfs::is_on_nfs_mount;
39 use crate::vfs::Vfs;
40 use crate::vfs::VfsFile;
41 use crate::vfs::VfsImpl;
42
43 mod mutable_tree;
44 mod on_disk;
45
46 #[cfg(test)]
47 mod tests;
48
49 /// Minimum size of the tree file in bytes before auto-vacuuming starts.
50 ///
51 /// The value was picked by adding files one by one in individual transaction.
52 /// 16K allows for adding 100 files before tree file is shrink down to 1.5K
53 const AUTO_VACUUM_MIN_SIZE: u32 = 16 * 1024;
54
55 /// Initial TTL when adding a file to garbage_entries. Each hg transaction that
56 /// follows will decrement it by 1, and will not delete it until it reaches 0.
57 const INITIAL_GARBAGE_TTL: u16 = 2;
58
59 /// An integer that represents a file path in the repository.
60 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
61 pub struct FileToken(pub u32);
62
63 impl FileToken {
64 /// Returns a special token for the root node.
65 fn root() -> Self {
66 Self(0)
67 }
68
69 /// Returns true if this is a valid token.
70 fn is_valid(&self) -> bool {
71 self.0 >> 31 == 0
72 }
73 }
74
75 /// Values of the config `devel.fileindex.vacuum-mode`.
76 #[derive(Debug, Copy, Clone, Default)]
77 pub enum VacuumMode {
78 #[default]
79 Auto,
80 Never,
81 Always,
82 }
83
84 impl VacuumMode {
85 pub fn parse(value: &[u8]) -> Option<Self> {
86 match value {
87 b"auto" => Some(VacuumMode::Auto),
88 b"never" => Some(VacuumMode::Never),
89 b"always" => Some(VacuumMode::Always),
90 _ => None,
91 }
92 }
93 }
94
95 /// Configuration for the file index.
96 pub struct Config {
97 /// Value of config `devel.fileindex.vacuum-mode`.
98 pub vacuum_mode: VacuumMode,
99 /// Value of config `storage.fileindex.max-unused-percentage`, converted to
100 /// a ratio from 0 to 1.
101 pub max_unused_ratio: f64,
102 /// Value of the config `storage.fileindex.gc-retention-seconds`.
103 pub gc_retention_s: u32,
104 /// Value of the config `devel.fileindex.garbage-timestamp`.
105 pub garbage_timestamp: Option<u32>,
106 }
107
108 /// The main file index object. It provides a high level interface that
109 /// abstracts over data on disk and pending changes in memory.
110 pub struct FileIndex {
111 /// VFS for reading the docket and data files.
112 vfs: VfsImpl,
113 /// Docket read from disk, or [`Docket::default()`] if there is none.
114 docket: Docket,
115 /// Read-only view of the file index on disk.
116 on_disk: OwnedFileIndexView,
117 /// Configuration values.
118 config: Config,
119 /// Whether to force a vacuum on the next write.
120 force_vacuum: bool,
121 /// Paths to be added on the next write.
122 add_paths: IndexSet<HgPathBuf>,
123 /// Tokens to be removed on the next write.
124 remove_tokens: HashSet<FileToken>,
125 }
126
127 impl FileIndex {
128 /// Opens the file index from the given store VFS.
129 /// If `try_pending` is true, tries reading the pending docket first.
130 /// Calls `devel_sync_point` in between reading the docket and data files.
131 pub fn open(
132 vfs: VfsImpl,
133 try_pending: bool,
134 config: Config,
135 devel_sync_point: impl FnOnce(),
136 ) -> Result<Self, HgError> {
137 let docket = Self::read_docket(&vfs, try_pending)?;
138 devel_sync_point();
139 let on_disk = Self::load(&docket, &vfs)?;
140 Ok(Self {
141 vfs,
142 docket,
143 on_disk,
144 config,
145 force_vacuum: false,
146 add_paths: IndexSet::new(),
147 remove_tokens: HashSet::new(),
148 })
149 }
150
151 /// Loads an [`OwnedFileIndexView`] from disk.
152 fn load(
153 docket: &Docket,
154 vfs: &VfsImpl,
155 ) -> Result<OwnedFileIndexView, HgError> {
156 let list_file = Self::read_file(vfs, docket.list_file_path())?;
157 let meta_file = Self::read_file(vfs, docket.meta_file_path())?;
158 let tree_file = Self::read_file(vfs, docket.tree_file_path())?;
159 let files = OwnedDataFiles { list_file, meta_file, tree_file };
160 Ok(OwnedFileIndexView::open(docket, files)?)
161 }
162
163 /// Returns the file index docket.
164 pub fn docket(&self) -> &Docket {
165 &self.docket
166 }
167
168 /// Reads the docket from disk, trying the pending version first if
169 /// `try_pending` is true. Returns a default docket if there's none on disk.
170 fn read_docket(
171 vfs: &VfsImpl,
172 try_pending: bool,
173 ) -> Result<Docket, HgError> {
174 let mut data = None;
175 if try_pending {
176 data = vfs.try_read(Docket::pending_path())?;
177 }
178 if data.is_none() {
179 data = vfs.try_read(Docket::path())?;
180 }
181 Ok(match data {
182 Some(data) => Docket::read(&data)?,
183 None => Docket::default(),
184 })
185 }
186
187 /// Reads a file from disk using mmap if possible.
188 /// Returns empty bytes if the file does not exist.
189 fn read_file(
190 vfs: &VfsImpl,
191 path: Option<PathBuf>,
192 ) -> Result<Box<dyn Deref<Target = [u8]> + Send + Sync>, HgError> {
193 let Some(path) = path else {
194 return Ok(Box::new(b"".as_slice()));
195 };
196 if is_on_nfs_mount(&vfs.base) {
197 Ok(Box::new(vfs.read(&path)?))
198 } else {
199 Ok(Box::new(vfs.mmap_open(&path)?))
200 }
201 }
202
203 fn on_disk(&self) -> &FileIndexView {
204 self.on_disk.borrow_dependent()
205 }
206
207 /// Returns the number of tokens in the file index.
208 /// This is also the value to be used for the next token.
209 fn token_count(&self) -> u32 {
210 u_u32(self.on_disk().token_count() + self.add_paths.len())
211 }
212
213 /// Returns true if `token` exists in the file index.
214 pub fn has_token(&self, token: FileToken) -> bool {
215 // Start at 1 to exclude root.
216 let in_range = token.0 >= 1 && token.0 < self.token_count();
217 in_range && !self.remove_tokens.contains(&token)
218 }
219
220 /// Returns true if `path` exists in the file index.
221 pub fn has_path(&self, path: &HgPath) -> Result<bool, Error> {
222 Ok(self.get_token(path)?.is_some())
223 }
224
225 /// Looks up a path by token.
226 pub fn get_path(&self, token: FileToken) -> Result<Option<&HgPath>, Error> {
227 if !self.has_token(token) {
228 return Ok(None);
229 }
230 let index = u32_u(token.0);
231 let count = self.on_disk().token_count();
232 if index < count {
233 return self.on_disk().get_path(token);
234 }
235 Ok(Some(
236 self.add_paths
237 .get_index(index - count)
238 .expect("should exist since has_token returned true"),
239 ))
240 }
241
242 /// Looks up a token by path.
243 pub fn get_token(&self, path: &HgPath) -> Result<Option<FileToken>, Error> {
244 if let Some(index) = self.add_paths.get_index_of(path) {
245 let count = self.on_disk().token_count();
246 return Ok(Some(FileToken(u_u32(count + index))));
247 };
248 Ok(self
249 .on_disk()
250 .get_token(path)?
251 .filter(|token| !self.remove_tokens.contains(token)))
252 }
253
254 /// Returns the number of paths in the file index.
255 pub fn len(&self) -> usize {
256 // Subtract 1 to exclude root.
257 u32_u(self.token_count()) - self.remove_tokens.len() - 1
258 }
259
260 /// Returns true if the file index is empty.
261 pub fn is_empty(&self) -> bool {
262 self.len() == 0
263 }
264
265 /// Returns an iterator over `(path, token)` pairs in the file index.
266 pub fn iter(&self) -> PathTokenIter<'_> {
267 PathTokenIter { inner: self, index: 0 }
268 }
269
270 /// Adds a path to the file index. Returns its token and a boolean which is
271 /// true if the file was added and false if it was already present.
272 pub fn add(&mut self, path: &HgPath) -> Result<(FileToken, bool), Error> {
273 assert!(
274 self.remove_tokens.is_empty(),
275 "cannot add and remove in same txn"
276 );
277 if let Some(token) = self.get_token(path)? {
278 return Ok((token, false));
279 }
280 let token = FileToken(self.token_count());
281 self.add_paths.insert(path.to_owned());
282 Ok((token, true))
283 }
284
285 /// Removes a path from the file index.
286 /// Returns true if the path was present in the file index.
287 pub fn remove(&mut self, path: &HgPath) -> Result<bool, Error> {
288 assert!(self.add_paths.is_empty(), "cannot add and remove in same txn");
289 if let Some(token) = self.get_token(path)? {
290 self.remove_tokens.insert(token);
291 Ok(true)
292 } else {
293 Ok(false)
294 }
295 }
296
297 /// Ensures the next write will vacuum the tree file.
298 pub fn vacuum(&mut self) {
299 self.force_vacuum = true;
300 }
301
302 /// Flush changes from [`Self::add`] or [`Self::remove`] to disk.
303 /// Writes the data files, but only updates [`Self::docket`] in memory.
304 /// It is the caller's responsibility to write the docket to disk.
305 pub fn write(&mut self, tr: &mut impl Transaction) -> Result<(), HgError> {
306 let clean = self.add_paths.is_empty() && self.remove_tokens.is_empty();
307 if !clean || self.force_vacuum {
308 let serialize_mode = if self.should_vacuum() {
309 SerializeMode::Vacuum
310 } else {
311 SerializeMode::Append
312 };
313 Self::write_data(
314 &mut self.docket,
315 &self.vfs,
316 tr,
317 &self.config,
318 self.on_disk.borrow_dependent(),
319 &self.add_paths,
320 &self.remove_tokens,
321 serialize_mode,
322 )?;
323 self.force_vacuum = false;
324 self.add_paths.clear();
325 self.remove_tokens.clear();
326 self.on_disk = Self::load(&self.docket, &self.vfs)?;
327 }
328 Ok(())
329 }
330
331 /// Returns the current Unix timestamp in seconds, for garbage collection
332 /// bookkeeping. Returns 0 if the system time is before the Unix epoch.
333 fn unix_timestamp() -> u32 {
334 std::time::SystemTime::now()
335 .duration_since(std::time::UNIX_EPOCH)
336 .unwrap_or(std::time::Duration::ZERO)
337 .as_secs()
338 .try_into()
339 .expect("u32 is good until 2106")
340 }
341
342 /// Return True if the current write should vacuum the tree file.
343 fn should_vacuum(&self) -> bool {
344 match self.config.vacuum_mode {
345 _ if self.force_vacuum => true,
346 VacuumMode::Always => true,
347 VacuumMode::Never => false,
348 VacuumMode::Auto => {
349 let size = self.docket.header.tree_file_size.get();
350 if size < AUTO_VACUUM_MIN_SIZE {
351 false
352 } else {
353 let unused = self.docket.header.tree_unused_bytes.get();
354 let ratio = unused as f64 / size as f64;
355 ratio >= self.config.max_unused_ratio
356 }
357 }
358 }
359 }
360
361 /// Deletes data files eligible for garbage collection.
362 ///
363 /// When the file index writes a new data file instead of appending to an
364 /// existing one, it adds the old file to the garbage list. That file
365 /// becomes eligible for garbage collection once the retention period has
366 /// elapsed (configured by storage.fileindex.gc-retention-seconds) and a
367 /// certain number of transactions have occurred.
368 ///
369 /// If force is True, deletes all files in the garbage list unconditionally.
370 ///
371 /// Returns true if any change was made to the docket's garbage list.
372 pub fn garbage_collect(&mut self, force: bool) -> bool {
373 let entries = &mut self.docket.garbage_entries;
374 if entries.is_empty() {
375 return false;
376 }
377 let now = Self::unix_timestamp();
378 let eligible_for_gc = |entry: &GarbageEntry| -> bool {
379 if entry.ttl > 0 {
380 return false;
381 }
382 // Make zero a special case so timing never affects it.
383 if self.config.gc_retention_s == 0 {
384 return true;
385 }
386 now > entry.timestamp + self.config.gc_retention_s
387 };
388 let mut changed = false;
389 entries.retain_mut(|entry| {
390 if entry.ttl > 0 {
391 entry.ttl -= 1;
392 changed = true;
393 }
394 let delete = force || eligible_for_gc(entry);
395 if delete {
396 let _ = self.vfs.unlink(&entry.path); // best effort
397 changed = true;
398 }
399 !delete
400 });
401 changed
402 }
403
404 pub fn data_files(&self) -> Vec<PathBuf> {
405 [
406 Some(Docket::path().to_owned()),
407 self.docket.list_file_path(),
408 self.docket.meta_file_path(),
409 self.docket.tree_file_path(),
410 ]
411 .into_iter()
412 .flatten()
413 .collect()
414 }
415
416 pub fn debug_iter_tree_nodes(&self) -> DebugTreeNodeIter<'_> {
417 self.on_disk().debug_iter_tree_nodes()
418 }
419
420 /// Writes all data files and updates `docket`.
421 // Have to use lots of arguments to avoid lifetime issues with `&mut self`.
422 #[allow(clippy::too_many_arguments)]
423 fn write_data(
424 docket: &mut Docket,
425 vfs: &VfsImpl,
426 tr: &mut impl Transaction,
427 config: &Config,
428 on_disk: &FileIndexView<'_>,
429 add_paths: &IndexSet<HgPathBuf>,
430 remove_tokens: &HashSet<FileToken>,
431 mode: SerializeMode,
432 ) -> Result<(), HgError> {
433 let removing = !remove_tokens.is_empty();
434 let new_list = docket.header.list_file_id.is_unset() || removing;
435 let new_meta = docket.header.meta_file_id.is_unset() || removing;
436 let new_tree = docket.header.tree_file_id.is_unset() || removing;
437 let new_tree = new_tree || mode == SerializeMode::Vacuum;
438 let timestamp =
439 config.garbage_timestamp.unwrap_or_else(Self::unix_timestamp);
440 let mut opener = FileOpener { docket, vfs, tr, timestamp };
441 let list_file = opener.open_list_file(new_list)?;
442 let meta_file = opener.open_meta_file(new_meta)?;
443 let tree_file = opener.open_tree_file(new_tree)?;
444 let files = VfsDataFiles { list_file, meta_file, tree_file };
445 if removing {
446 assert!(add_paths.is_empty(), "cannot add and remove in same txn");
447 let num_paths = on_disk.token_count() - remove_tokens.len();
448 let tree = MutableTree::empty(num_paths)?;
449 let add_paths = on_disk.iter().filter_map(|result| match result {
450 Ok((_, token)) if remove_tokens.contains(&token) => None,
451 Ok((info, _)) => Some(Ok(info.path())),
452 Err(err) => Some(Err(err)),
453 });
454 Self::write_data_impl(docket, tree, add_paths, files, mode)
455 } else {
456 let tree = MutableTree::with_base(*on_disk, add_paths.len())?;
457 let add_paths = add_paths.iter().map(|path| Ok(path.deref()));
458 Self::write_data_impl(docket, tree, add_paths, files, mode)
459 }
460 }
461
462 /// Helper function for [`Self::write_data`] to allow the `add_paths`
463 /// iterator to take on different concrete types.
464 fn write_data_impl<'a>(
465 docket: &mut Docket,
466 mut tree: MutableTree<'a>,
467 add_paths: impl Iterator<Item = Result<&'a HgPath, Error>>,
468 VfsDataFiles { list_file, meta_file, mut tree_file }: VfsDataFiles,
469 mode: SerializeMode,
470 ) -> Result<(), HgError> {
471 let list_file_path = normal_path(&list_file).to_owned();
472 let meta_file_path = normal_path(&meta_file).to_owned();
473 let tree_file_path = normal_path(&tree_file).to_owned();
474 // The tree file doesn't need buffering since we write it all at once.
475 let mut list_file = BufWriter::new(list_file);
476 let mut meta_file = BufWriter::new(meta_file);
477 let token_start = tree.token_count();
478 let mut list_file_size = docket.header.list_file_size.get();
479 let mut meta_file_size = docket.header.meta_file_size.get();
480 if meta_file_size == 0 {
481 meta_file
482 .write(&EMPTY_META_BYTES)
483 .when_writing_file(&meta_file_path)?;
484 meta_file_size = u_u32(EMPTY_META_BYTES.len());
485 }
486 for (i, path_result) in (token_start..).zip(add_paths) {
487 let path = path_result?;
488 let metadata = Metadata::new(path, list_file_size);
489 list_file
490 .write_all(path.as_bytes())
491 .when_writing_file(&list_file_path)?;
492 list_file.write_all(b"\x00").when_writing_file(&list_file_path)?;
493 meta_file
494 .write_all(metadata.as_bytes())
495 .when_writing_file(&meta_file_path)?;
496 tree.insert(path, FileToken(u_u32(i)))?;
497 list_file_size += u_u32(path.len() + 1);
498 meta_file_size += u_u32(std::mem::size_of::<Metadata>());
499 }
500 docket.header.list_file_size = list_file_size.into();
501 docket.header.meta_file_size = meta_file_size.into();
502 if let Some(out) = tree.serialize(mode)? {
503 tree_file
504 .write_all(&out.bytes)
505 .when_writing_file(&tree_file_path)?;
506 docket.header.tree_file_size = out.tree_file_size.into();
507 docket.header.tree_root_pointer = out.tree_root_pointer.into();
508 docket.header.tree_unused_bytes = out.tree_unused_bytes.into();
509 }
510 docket.header.reserved_flags = [0; 4];
511 Ok(())
512 }
513 }
514
515 /// VFS file handles for the file index data files.
516 struct VfsDataFiles {
517 list_file: VfsFile,
518 meta_file: VfsFile,
519 tree_file: VfsFile,
520 }
521
522 /// Helper for [`FileIndex::write_data_impl`] to open files for writing.
523 struct FileOpener<'a, Tr> {
524 docket: &'a mut Docket,
525 vfs: &'a VfsImpl,
526 tr: &'a mut Tr,
527 timestamp: u32,
528 }
529
530 impl<Tr> FileOpener<'_, Tr>
531 where
532 Tr: Transaction,
533 {
534 fn open_list_file(&mut self, new: bool) -> Result<VfsFile, HgError> {
535 let path = self.docket.list_file_path();
536 if new {
537 self.add_to_garbage(path);
538 self.docket.header.list_file_id = FileUid::random();
539 self.docket.header.list_file_size = 0.into();
540 let path = self.docket.list_file_path().expect("just set the id");
541 return self.open_new(&path);
542 }
543 let path = path.expect("should exist if new is false");
544 self.open_for_appending(&path, self.docket.header.list_file_size.get())
545 }
546
547 fn open_meta_file(&mut self, new: bool) -> Result<VfsFile, HgError> {
548 let path = self.docket.meta_file_path();
549 if new {
550 self.add_to_garbage(path);
551 self.docket.header.meta_file_id = FileUid::random();
552 self.docket.header.meta_file_size = 0.into();
553 let path = self.docket.meta_file_path().expect("just set the id");
554 return self.open_new(&path);
555 }
556 let path = path.expect("should exist if new is false");
557 self.open_for_appending(&path, self.docket.header.meta_file_size.get())
558 }
559
560 fn open_tree_file(&mut self, new: bool) -> Result<VfsFile, HgError> {
561 let path = self.docket.tree_file_path();
562 if new {
563 self.add_to_garbage(path);
564 self.docket.header.tree_file_id = FileUid::random();
565 self.docket.header.tree_file_size = 0.into();
566 self.docket.header.tree_root_pointer = 0.into();
567 self.docket.header.tree_unused_bytes = 0.into();
568 let path = self.docket.tree_file_path().expect("just set the id");
569 return self.open_new(&path);
570 }
571 let path = path.expect("should exist if new is false");
572 self.open_for_appending(&path, self.docket.header.tree_file_size.get())
573 }
574
575 /// If `path` is not `None`, adds it to the docket's garbage list.
576 fn add_to_garbage(&mut self, path: Option<PathBuf>) {
577 if let Some(path) = path {
578 self.docket.garbage_entries.push(GarbageEntry {
579 ttl: INITIAL_GARBAGE_TTL,
580 timestamp: self.timestamp,
581 path: path.to_owned(),
582 });
583 }
584 }
585
586 /// Open a new file for writing.
587 ///
588 /// This adds the file to the transaction so that it will be removed if we
589 /// later abort or rollback.
590 fn open_new(&mut self, path: &Path) -> Result<VfsFile, HgError> {
591 self.tr.add(path, 0);
592 self.vfs.create(path, false)
593 }
594
595 /// Open a file for appending past `used_size`.
596 ///
597 /// Despite "appending", this doesn't open in append mode because the
598 /// physical size of the file may be larger than `used_size`.
599 ///
600 /// Unlike [`Self::open_new`], this doesn't add the file to the transaction.
601 /// If we rollback, there's no need to truncate since the docket stores
602 /// `used_size`.
603 fn open_for_appending(
604 &mut self,
605 path: &Path,
606 used_size: u32,
607 ) -> Result<VfsFile, HgError> {
608 let mut file = self.vfs.open_write(path)?;
609 file.seek(SeekFrom::Start(used_size as u64))
610 .when_reading_file(normal_path(&file))?;
611 Ok(file)
612 }
613 }
614
615 /// Returns the path of a [`VfsFile`], assuming it is normal not atomic.
616 fn normal_path(file: &VfsFile) -> &Path {
617 match file {
618 VfsFile::Normal { path, .. } => path,
619 VfsFile::Atomic(..) => unreachable!("unexpected atomic file"),
620 }
621 }
622
623 /// An iterator over `(path, token)` in the file index.
624 pub struct PathTokenIter<'a> {
625 inner: &'a FileIndex,
626 index: u32,
627 }
628
629 impl<'a> Iterator for PathTokenIter<'a> {
630 type Item = Result<(&'a HgPath, FileToken), Error>;
631
632 fn next(&mut self) -> Option<Self::Item> {
633 let count = self.inner.token_count();
634 while self.index < count {
635 let token = FileToken(self.index);
636 self.index += 1;
637 match self.inner.get_path(token) {
638 Ok(None) => {}
639 Ok(Some(path)) => return Some(Ok((path, token))),
640 Err(err) => return Some(Err(err)),
641 }
642 }
643 None
644 }
645 }