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