Debian Codegraph @

rust/hg-core/src/revlog/file_io.rs

raw
1 //! Helpers for revlog file reading and writing.
2
3 use std::cell::Ref;
4 use std::cell::RefCell;
5 use std::io::Read;
6 use std::io::Seek;
7 use std::io::SeekFrom;
8 use std::io::Write;
9 use std::os::unix::fs::FileExt;
10 use std::path::Path;
11 use std::path::PathBuf;
12 use std::sync::Arc;
13 use std::sync::Mutex;
14
15 use crate::errors::HgError;
16 use crate::errors::IoResultExt;
17 use crate::vfs::Vfs;
18 use crate::vfs::VfsFile;
19
20 /// Wraps accessing arbitrary chunks of data within a file and reusing handles.
21 /// This is currently useful for accessing a revlog's data file, only reading
22 /// the ranges that are currently relevant, like a sort of basic and manual
23 /// file-based mmap.
24 ///
25 /// XXX should this just be replaced with `mmap` + `madvise` ranges?
26 /// The upcoming `UncompressedChunkCache` will make up for most of the slowness
27 /// of re-reading the same chunks, so this might not be as useful. Aside from
28 /// the major benefit of having less code to take care of, using `mmap` will
29 /// allow multiple processes to share the same pages, especially for the
30 /// changelog and manifest, which would make a difference in server contexts.
31 pub struct RandomAccessFile {
32 /// The current store VFS to pass it to [`FileHandle`]
33 vfs: Box<dyn Vfs>,
34 /// Filename of the open file, relative to the vfs root
35 pub filename: PathBuf,
36 /// The current read-only handle on the file, if any.
37 /// Specific to the current thread, since we don't want seeks to overlap
38 pub reading_handle: thread_local::ThreadLocal<RefCell<Option<FileHandle>>>,
39 /// The current read-write handle on the file, if any.
40 /// Specific to the current thread, since we don't want seeks to overlap,
41 /// and we can re-use the write handle for reading in certain contexts.
42 /// Logically, two concurrent writes are impossible because they are only
43 /// accessible through `&mut self` methods, which take a lock.
44 pub writing_handle: thread_local::ThreadLocal<RefCell<Option<FileHandle>>>,
45 }
46
47 impl RandomAccessFile {
48 /// Wrap a file for random access
49 pub fn new(vfs: Box<dyn Vfs>, filename: PathBuf) -> Self {
50 assert!(filename.is_relative());
51 Self {
52 vfs,
53 filename,
54 reading_handle: thread_local::ThreadLocal::new(),
55 writing_handle: thread_local::ThreadLocal::new(),
56 }
57 }
58
59 /// Read a chunk of bytes from the file.
60 pub fn read_chunk(
61 &self,
62 offset: usize,
63 length: usize,
64 ) -> Result<Vec<u8>, HgError> {
65 let handle = self.get_read_handle()?;
66 handle.read_exact_at(length, offset).when_reading_file(&self.filename)
67 }
68
69 /// `pub` only for hg-pyo3
70 #[doc(hidden)]
71 pub fn get_read_handle(&self) -> Result<Ref<FileHandle>, HgError> {
72 let write_handle = self.writing_handle.get_or_default().borrow();
73 if let Ok(handle) = Ref::filter_map(write_handle, Option::as_ref) {
74 // Use a file handle being actively used for writes, if available.
75 // There is some danger to doing this because reads will seek the
76 // file.
77 // However, [`Revlog::write_entry`] performs a `SeekFrom::End(0)`
78 // before all writes, so we should be safe.
79 return Ok(handle);
80 }
81 let read_handle = self.reading_handle.get_or_default().borrow();
82 if let Ok(handle) = Ref::filter_map(read_handle, Option::as_ref) {
83 // Use a file handle being actively used for writes, if available.
84 // There is some danger to doing this because reads will seek the
85 // file.
86 // However, [`Revlog::write_entry`] performs a `SeekFrom::End(0)`
87 // before all writes, so we should be safe.
88 return Ok(handle);
89 }
90 // early returns done to work around borrowck being overzealous
91 // See https://github.com/rust-lang/rust/issues/103108
92 let new_handle = FileHandle::new(
93 dyn_clone::clone_box(&*self.vfs),
94 &self.filename,
95 false,
96 false,
97 )?;
98 let read_handle = self.reading_handle.get_or_default();
99 *read_handle.borrow_mut() = Some(new_handle);
100 Ok(Ref::map(read_handle.borrow(), |h| h.as_ref().expect("just set")))
101 }
102
103 /// `pub` only for hg-pyo3
104 #[doc(hidden)]
105 pub fn exit_reading_context(&self) {
106 self.reading_handle.get().map(|h| h.take());
107 }
108
109 // Returns whether this file currently open
110 pub fn is_open(&self) -> bool {
111 self.reading_handle.get_or_default().borrow().is_some()
112 || self.writing_handle.get_or_default().borrow().is_some()
113 }
114 }
115
116 /// A buffer that holds new changelog index data that needs to be written
117 /// after the manifest and filelogs so that the repo is updated atomically to
118 /// external processes.
119 #[derive(Clone, Debug, Default)]
120 pub struct DelayedBuffer {
121 // The actual in-memory bytes storing the delayed writes
122 pub(super) buffer: Vec<u8>,
123 /// The current offset into the virtual file composed of file + buffer
124 offset: u64,
125 /// The size of the file at the time of opening
126 file_size: u64,
127 }
128
129 impl DelayedBuffer {
130 /// Returns the length of the full data (on-disk + buffer length).
131 pub fn len(&self) -> u64 {
132 self.buffer.len() as u64 + self.file_size
133 }
134
135 pub fn is_empty(&self) -> bool {
136 self.len() == 0
137 }
138 }
139
140 /// Holds an open [`VfsFile`] and the related data. This can be used for
141 /// reading and writing. Writes can be delayed to a buffer before touching
142 /// the disk, if relevant (in the changelog case), but reads are transparent.
143 pub struct FileHandle {
144 /// The actual open file
145 pub file: VfsFile,
146 /// The VFS with which the file was opened
147 vfs: Box<dyn Vfs>,
148 /// Filename of the open file, relative to the repo root
149 filename: PathBuf,
150 /// Buffer of delayed entry writes to the changelog index. This points
151 /// back to the buffer inside the revlog this handle refers to.
152 delayed_buffer: Option<Arc<Mutex<DelayedBuffer>>>,
153 }
154
155 impl Seek for FileHandle {
156 /// Move the position of the handle to `pos`,
157 /// spanning the [`DelayedBuffer`] if defined. Will return an error if
158 /// an invalid seek position is asked, or for any standard io error.
159 fn seek(&mut self, pos: SeekFrom) -> Result<u64, std::io::Error> {
160 if let Some(delay_buf) = &self.delayed_buffer {
161 let mut delay_buf = delay_buf.lock().unwrap();
162 // Virtual file offset spans real file and data
163 match pos {
164 SeekFrom::Start(offset) => delay_buf.offset = offset,
165 SeekFrom::End(offset) => {
166 delay_buf.offset =
167 delay_buf.len().saturating_add_signed(offset)
168 }
169 SeekFrom::Current(offset) => {
170 delay_buf.offset =
171 delay_buf.offset.saturating_add_signed(offset);
172 }
173 }
174 if delay_buf.offset < delay_buf.file_size {
175 self.file.seek(pos)
176 } else {
177 Ok(delay_buf.offset)
178 }
179 } else {
180 self.file.seek(pos)
181 }
182 }
183 }
184
185 impl std::fmt::Debug for FileHandle {
186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187 f.debug_struct("FileHandle")
188 .field("filename", &self.filename)
189 .field("delayed_buffer", &self.delayed_buffer)
190 .field("file", &self.file)
191 .finish()
192 }
193 }
194
195 impl FileHandle {
196 /// Get a (read or write) file handle to `filename`. Only creates the file
197 /// if `create` is `true`.
198 pub fn new(
199 vfs: Box<dyn Vfs>,
200 filename: impl AsRef<Path>,
201 create: bool,
202 write: bool,
203 ) -> Result<Self, HgError> {
204 let file = if create {
205 vfs.create(filename.as_ref(), false)?
206 } else if write {
207 vfs.open_write(filename.as_ref())?
208 } else {
209 vfs.open(filename.as_ref())?
210 };
211 Ok(Self {
212 vfs,
213 filename: filename.as_ref().to_owned(),
214 delayed_buffer: None,
215 file,
216 })
217 }
218
219 /// Get a file handle to `filename`, but writes go to a [`DelayedBuffer`].
220 pub fn new_delayed(
221 vfs: Box<dyn Vfs>,
222 filename: impl AsRef<Path>,
223 create: bool,
224 delayed_buffer: Arc<Mutex<DelayedBuffer>>,
225 ) -> Result<Self, HgError> {
226 let mut file = if create {
227 vfs.create(filename.as_ref(), false)?
228 } else {
229 vfs.open_write(filename.as_ref())?
230 };
231 let size = vfs.file_size(&file)?;
232 let offset =
233 file.stream_position().when_reading_file(filename.as_ref())?;
234
235 {
236 let mut buf = delayed_buffer.lock().unwrap();
237 buf.file_size = size;
238 buf.offset = offset;
239 }
240
241 Ok(Self {
242 vfs,
243 filename: filename.as_ref().to_owned(),
244 delayed_buffer: Some(delayed_buffer),
245 file,
246 })
247 }
248
249 /// Wrap an existing [`VfsFile`]
250 pub fn from_file(
251 file: VfsFile,
252 vfs: Box<dyn Vfs>,
253 filename: impl AsRef<Path>,
254 ) -> Self {
255 Self {
256 vfs,
257 filename: filename.as_ref().to_owned(),
258 delayed_buffer: None,
259 file,
260 }
261 }
262
263 /// Wrap an existing [`VfsFile`], but writes go to a [`DelayedBuffer`].
264 pub fn from_file_delayed(
265 mut file: VfsFile,
266 vfs: Box<dyn Vfs>,
267 filename: impl AsRef<Path>,
268 delayed_buffer: Arc<Mutex<DelayedBuffer>>,
269 ) -> Result<Self, HgError> {
270 let size = vfs.file_size(&file)?;
271 let offset =
272 file.stream_position().when_reading_file(filename.as_ref())?;
273
274 {
275 let mut buf = delayed_buffer.lock().unwrap();
276 buf.file_size = size;
277 buf.offset = offset;
278 }
279
280 Ok(Self {
281 vfs,
282 filename: filename.as_ref().to_owned(),
283 delayed_buffer: Some(delayed_buffer),
284 file,
285 })
286 }
287
288 /// Read exactly `length` bytes from `offset`.
289 /// Does not affect the file position.
290 /// Errors are the same as [`std::io::Read::read_exact`].
291 pub fn read_exact_at(
292 &self,
293 length: usize,
294 offset: usize,
295 ) -> Result<Vec<u8>, std::io::Error> {
296 let offset: u64 = offset.try_into().expect("offset too large");
297 if let Some(delay_buf) = self.delayed_buffer.as_ref() {
298 let mut delay_buf = delay_buf.lock().unwrap();
299 let mut buf = vec![0; length];
300 let file_size: isize =
301 delay_buf.file_size.try_into().expect("file size too large");
302 let signed_offset: isize =
303 offset.try_into().expect("offset too large");
304 let span: isize = signed_offset - file_size;
305 let length = length.try_into().expect("too large of a length");
306 let absolute_span: u64 =
307 span.unsigned_abs().try_into().expect("length too large");
308 if span < 0 {
309 if length <= absolute_span {
310 // We're only in the file
311 self.file.read_exact_at(&mut buf, offset)?;
312 } else {
313 // We're spanning file and buffer
314 self.file.read_exact_at(
315 &mut buf[..absolute_span as usize],
316 offset,
317 )?;
318 delay_buf
319 .buffer
320 .take(length - absolute_span)
321 .read_exact(&mut buf[absolute_span as usize..])?;
322 }
323 } else {
324 // We're only in the buffer
325 delay_buf.buffer[absolute_span as usize..]
326 .take(length)
327 .read_exact(&mut buf)?;
328 }
329 delay_buf.offset += length;
330 Ok(buf.to_owned())
331 } else {
332 let mut buf = vec![0; length];
333 self.file.read_exact_at(&mut buf, offset)?;
334 Ok(buf)
335 }
336 }
337
338 /// Flush the in-memory changes to disk. This does *not* write the
339 /// delayed buffer, only the pending file changes.
340 pub fn flush(&mut self) -> Result<(), HgError> {
341 self.file.flush().when_writing_file(&self.filename)
342 }
343
344 /// Return the current position in the file
345 pub fn position(&mut self) -> Result<u64, HgError> {
346 self.file.stream_position().when_reading_file(&self.filename)
347 }
348
349 /// Append `data` to the file, or to the [`DelayedBuffer`], if any.
350 pub fn write_all(&mut self, data: &[u8]) -> Result<(), HgError> {
351 if let Some(buf) = &mut self.delayed_buffer {
352 let mut delayed_buffer = buf.lock().expect("propagate the panic");
353 assert_eq!(delayed_buffer.offset, delayed_buffer.len());
354 delayed_buffer.buffer.extend_from_slice(data);
355 delayed_buffer.offset += data.len() as u64;
356 Ok(())
357 } else {
358 self.file.write_all(data).when_writing_file(&self.filename)?;
359 Ok(())
360 }
361 }
362
363 pub fn try_clone(&self) -> Result<Self, HgError> {
364 Ok(Self {
365 vfs: dyn_clone::clone_box(&*self.vfs),
366 filename: self.filename.clone(),
367 delayed_buffer: self.delayed_buffer.clone(),
368 file: self.file.try_clone()?,
369 })
370 }
371 }
372
373 /// Write handles to a given revlog (index + maybe data)
374 #[derive(Debug)]
375 pub struct WriteHandles {
376 /// Handle to the index file
377 pub index_handle: FileHandle,
378 /// Handle to the data file, if the revlog is non-inline
379 pub data_handle: Option<FileHandle>,
380 }
381
382 #[cfg(test)]
383 mod tests {
384 use std::io::ErrorKind;
385
386 use super::*;
387 use crate::revlog::path_encode::PathEncoding;
388 use crate::vfs::VfsImpl;
389
390 #[test]
391 fn test_random_access_file() {
392 let base = tempfile::tempdir().unwrap().into_path();
393 let filename = Path::new("a");
394 let file_path = base.join(filename);
395 let raf = RandomAccessFile::new(
396 Box::new(VfsImpl::new(base.clone(), true, PathEncoding::None)),
397 filename.to_owned(),
398 );
399
400 assert!(!raf.is_open());
401 assert_eq!(&raf.filename, &filename);
402 // Should fail to read a non-existing file
403 match raf.get_read_handle().unwrap_err() {
404 HgError::IoError { error, .. } => match error.kind() {
405 std::io::ErrorKind::NotFound => {}
406 _ => panic!("should be not found"),
407 },
408 e => panic!("{}", e.to_string()),
409 }
410
411 std::fs::write(file_path, b"1234567890").unwrap();
412
413 // Should be able to open an existing file
414 let handle = raf.get_read_handle().unwrap();
415 assert!(raf.is_open());
416 assert_eq!(
417 handle.read_exact_at(10, 0).unwrap(),
418 b"1234567890".to_vec()
419 );
420 }
421
422 #[test]
423 fn test_file_handle() {
424 let base = tempfile::tempdir().unwrap().into_path();
425 let filename = base.join("a");
426 // No `create` should fail
427 FileHandle::new(
428 Box::new(VfsImpl::new(base.clone(), false, PathEncoding::None)),
429 &filename,
430 false,
431 false,
432 )
433 .unwrap_err();
434 std::fs::write(&filename, b"1234567890").unwrap();
435
436 let mut read_handle = FileHandle::new(
437 Box::new(VfsImpl::new(base.clone(), true, PathEncoding::None)),
438 &filename,
439 false,
440 false,
441 )
442 .unwrap();
443 assert_eq!(&read_handle.filename, &filename);
444 assert_eq!(read_handle.position().unwrap(), 0);
445
446 // Writing to an explicit read handle should fail
447 read_handle.write_all(b"some data").unwrap_err();
448
449 // reading exactly n bytes should work
450 assert_eq!(read_handle.read_exact_at(3, 0).unwrap(), b"123".to_vec());
451 // and the position shouldn't be remembered
452 assert_eq!(read_handle.read_exact_at(2, 0).unwrap(), b"12".to_vec());
453 // offset works
454 assert_eq!(read_handle.read_exact_at(2, 3).unwrap(), b"45".to_vec());
455
456 // Seeking should work
457 let position = read_handle.position().unwrap();
458 read_handle.seek(SeekFrom::Current(2)).unwrap();
459 assert_eq!(position + 2, read_handle.position().unwrap());
460
461 // Seeking too much data should fail
462 read_handle.read_exact_at(1000, 0).unwrap_err();
463
464 // Open a write handle
465 let mut handle = FileHandle::new(
466 Box::new(VfsImpl::new(base.clone(), false, PathEncoding::None)),
467 &filename,
468 false,
469 true,
470 )
471 .unwrap();
472
473 // Now writing should succeed
474 handle.write_all(b"new data").unwrap();
475 // Opening or writing does not seek, so we should be at the start
476 assert_eq!(handle.position().unwrap(), 8);
477 // We can still read
478 assert_eq!(handle.read_exact_at(2, 8).unwrap(), b"90".to_vec());
479
480 let mut read_handle = FileHandle::new(
481 Box::new(VfsImpl::new(base.clone(), true, PathEncoding::None)),
482 &filename,
483 false,
484 false,
485 )
486 .unwrap();
487 read_handle.seek(SeekFrom::Start(0)).unwrap();
488 // On-disk file contents should be changed
489 assert_eq!(
490 &read_handle.read_exact_at(10, 0).unwrap(),
491 &b"new data90".to_vec(),
492 );
493 // Flushing doesn't do anything unexpected
494 handle.flush().unwrap();
495
496 let delayed_buffer = Arc::new(Mutex::new(DelayedBuffer::default()));
497 let mut handle = FileHandle::new_delayed(
498 Box::new(VfsImpl::new(base.clone(), false, PathEncoding::None)),
499 &filename,
500 false,
501 delayed_buffer,
502 )
503 .unwrap();
504
505 assert_eq!(
506 handle.delayed_buffer.as_ref().unwrap().lock().unwrap().file_size,
507 10
508 );
509 handle.seek(SeekFrom::End(0)).unwrap();
510 handle.write_all(b"should go to buffer").unwrap();
511 assert_eq!(
512 handle.delayed_buffer.as_ref().unwrap().lock().unwrap().len(),
513 29
514 );
515 read_handle.seek(SeekFrom::Start(0)).unwrap();
516 // On-disk file contents should be unchanged
517 assert_eq!(
518 read_handle.read_exact_at(10, 0).unwrap(),
519 b"new data90".to_vec(),
520 );
521
522 assert_eq!(
523 read_handle.read_exact_at(1, 10).unwrap_err().kind(),
524 ErrorKind::UnexpectedEof
525 );
526
527 handle.flush().unwrap();
528 // On-disk file contents should still be unchanged after a flush
529 assert_eq!(
530 read_handle.read_exact_at(1, 10).unwrap_err().kind(),
531 ErrorKind::UnexpectedEof
532 );
533
534 // Read from the buffer only
535 assert_eq!(handle.read_exact_at(6, 23).unwrap(), b"buffer".to_vec());
536
537 // Read from an overlapping section of file and buffer
538 assert_eq!(
539 handle.read_exact_at(20, 6).unwrap(),
540 b"ta90should go to buf".to_vec()
541 );
542
543 // Read from file only
544 assert_eq!(handle.read_exact_at(8, 0).unwrap(), b"new data".to_vec());
545 }
546 }