Skip to main content

hermes_core/directories/
mmap.rs

1//! Memory-mapped directory for efficient access to large indices
2//!
3//! This module is only compiled with the "native" feature.
4
5use std::io;
6use std::ops::Range;
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9
10use async_trait::async_trait;
11use memmap2::Mmap;
12
13use super::{
14    Directory, DirectoryWriter, FileSlice, FileStreamingWriter, LazyFileHandle, OwnedBytes,
15    RangeReadFn, StreamingWriter,
16};
17
18/// Memory-mapped directory for efficient access to large index files
19///
20/// Uses memory-mapped files to avoid loading entire files into memory.
21/// The OS manages paging, making this ideal for indices larger than RAM.
22///
23/// Benefits:
24/// - Files are not fully loaded into memory
25/// - OS handles caching and paging automatically
26/// - Multiple processes can share the same mapped pages
27/// - Efficient random access patterns
28///
29/// Note: Write operations still use regular file I/O.
30/// No application-level cache - the OS page cache handles this efficiently.
31pub struct MmapDirectory {
32    root: PathBuf,
33}
34
35impl MmapDirectory {
36    /// Create a new MmapDirectory rooted at the given path
37    pub fn new(root: impl AsRef<Path>) -> Self {
38        Self {
39            root: root.as_ref().to_path_buf(),
40        }
41    }
42
43    fn resolve(&self, path: &Path) -> PathBuf {
44        self.root.join(path)
45    }
46
47    /// Memory-map a file (no application cache - OS page cache handles this)
48    fn mmap_file(&self, path: &Path) -> io::Result<Arc<Mmap>> {
49        let full_path = self.resolve(path);
50        let file = std::fs::File::open(&full_path)?;
51        let mmap = unsafe { Mmap::map(&file)? };
52        Ok(Arc::new(mmap))
53    }
54}
55
56impl Clone for MmapDirectory {
57    fn clone(&self) -> Self {
58        Self {
59            root: self.root.clone(),
60        }
61    }
62}
63
64#[async_trait]
65impl Directory for MmapDirectory {
66    async fn exists(&self, path: &Path) -> io::Result<bool> {
67        let full_path = self.resolve(path);
68        Ok(tokio::fs::try_exists(&full_path).await.unwrap_or(false))
69    }
70
71    async fn file_size(&self, path: &Path) -> io::Result<u64> {
72        let full_path = self.resolve(path);
73        let metadata = tokio::fs::metadata(&full_path).await?;
74        Ok(metadata.len())
75    }
76
77    async fn open_read(&self, path: &Path) -> io::Result<FileSlice> {
78        let mmap = self.mmap_file(path)?;
79        // Zero-copy: OwnedBytes references the mmap directly
80        Ok(FileSlice::new(OwnedBytes::from_mmap(mmap)))
81    }
82
83    async fn read_range(&self, path: &Path, range: Range<u64>) -> io::Result<OwnedBytes> {
84        let mmap = self.mmap_file(path)?;
85        let start = range.start as usize;
86        let end = range.end as usize;
87
88        if end > mmap.len() {
89            return Err(io::Error::new(
90                io::ErrorKind::InvalidInput,
91                format!("Range {}..{} exceeds file size {}", start, end, mmap.len()),
92            ));
93        }
94
95        // Zero-copy: slice references the mmap directly
96        Ok(OwnedBytes::from_mmap_range(mmap, start..end))
97    }
98
99    async fn list_files(&self, prefix: &Path) -> io::Result<Vec<PathBuf>> {
100        let full_path = self.resolve(prefix);
101        let mut entries = tokio::fs::read_dir(&full_path).await?;
102        let mut files = Vec::new();
103
104        while let Some(entry) = entries.next_entry().await? {
105            if entry.file_type().await?.is_file() {
106                files.push(entry.path().strip_prefix(&self.root).unwrap().to_path_buf());
107            }
108        }
109
110        Ok(files)
111    }
112
113    async fn open_lazy(&self, path: &Path) -> io::Result<LazyFileHandle> {
114        let mmap = self.mmap_file(path)?;
115        let file_size = mmap.len() as u64;
116
117        let read_fn: RangeReadFn = Arc::new(move |range: Range<u64>| {
118            let mmap = Arc::clone(&mmap);
119            Box::pin(async move {
120                let start = range.start as usize;
121                let end = range.end as usize;
122
123                if end > mmap.len() {
124                    return Err(io::Error::new(
125                        io::ErrorKind::InvalidInput,
126                        format!("Range {}..{} exceeds file size {}", start, end, mmap.len()),
127                    ));
128                }
129
130                // Zero-copy: slice references the mmap directly
131                Ok(OwnedBytes::from_mmap_range(mmap, start..end))
132            })
133        });
134
135        Ok(LazyFileHandle::new(file_size, read_fn))
136    }
137}
138
139#[async_trait]
140impl DirectoryWriter for MmapDirectory {
141    async fn write(&self, path: &Path, data: &[u8]) -> io::Result<()> {
142        let full_path = self.resolve(path);
143
144        // Ensure parent directory exists
145        if let Some(parent) = full_path.parent() {
146            tokio::fs::create_dir_all(parent).await?;
147        }
148
149        tokio::fs::write(&full_path, data).await
150    }
151
152    async fn delete(&self, path: &Path) -> io::Result<()> {
153        let full_path = self.resolve(path);
154        tokio::fs::remove_file(&full_path).await
155    }
156
157    async fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
158        let from_path = self.resolve(from);
159        let to_path = self.resolve(to);
160        tokio::fs::rename(&from_path, &to_path).await
161    }
162
163    async fn sync(&self) -> io::Result<()> {
164        // fsync the directory
165        let dir = std::fs::File::open(&self.root)?;
166        dir.sync_all()?;
167        Ok(())
168    }
169
170    async fn streaming_writer(&self, path: &Path) -> io::Result<Box<dyn StreamingWriter>> {
171        let full_path = self.resolve(path);
172        if let Some(parent) = full_path.parent() {
173            tokio::fs::create_dir_all(parent).await?;
174        }
175        let file = std::fs::File::create(&full_path)?;
176        Ok(Box::new(FileStreamingWriter::new(file)))
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use tempfile::TempDir;
184
185    #[tokio::test]
186    async fn test_mmap_directory_basic() {
187        let temp_dir = TempDir::new().unwrap();
188        let dir = MmapDirectory::new(temp_dir.path());
189
190        // Write a file
191        let test_data = b"Hello, mmap world!";
192        dir.write(Path::new("test.txt"), test_data).await.unwrap();
193
194        // Check exists
195        assert!(dir.exists(Path::new("test.txt")).await.unwrap());
196        assert!(!dir.exists(Path::new("nonexistent.txt")).await.unwrap());
197
198        // Check file size
199        assert_eq!(
200            dir.file_size(Path::new("test.txt")).await.unwrap(),
201            test_data.len() as u64
202        );
203
204        // Read full file
205        let slice = dir.open_read(Path::new("test.txt")).await.unwrap();
206        let bytes = slice.read_bytes().await.unwrap();
207        assert_eq!(bytes.as_slice(), test_data);
208
209        // Read range
210        let range_bytes = dir.read_range(Path::new("test.txt"), 7..12).await.unwrap();
211        assert_eq!(range_bytes.as_slice(), b"mmap ");
212    }
213
214    #[tokio::test]
215    async fn test_mmap_directory_lazy_handle() {
216        use crate::directories::AsyncFileRead;
217
218        let temp_dir = TempDir::new().unwrap();
219        let dir = MmapDirectory::new(temp_dir.path());
220
221        // Write a larger file
222        let data: Vec<u8> = (0..1000).map(|i| (i % 256) as u8).collect();
223        dir.write(Path::new("large.bin"), &data).await.unwrap();
224
225        // Open lazy handle
226        let handle = dir.open_lazy(Path::new("large.bin")).await.unwrap();
227        assert_eq!(handle.len(), 1000);
228
229        // Read ranges
230        let range1 = handle.read_bytes_range(0..100).await.unwrap();
231        assert_eq!(range1.len(), 100);
232        assert_eq!(range1.as_slice(), &data[0..100]);
233
234        let range2 = handle.read_bytes_range(500..600).await.unwrap();
235        assert_eq!(range2.as_slice(), &data[500..600]);
236    }
237}