ipfrs-interface 0.1.0

HTTP, gRPC, GraphQL and Python interfaces for IPFRS distributed storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Memory-Mapped File Serving
//!
//! Provides zero-copy file serving using memory-mapped I/O for improved performance
//! with large tensor files. This module enables efficient serving of tensors without
//! loading the entire file into memory.
//!
//! # Features
//!
//! - **Zero-copy serving** - Direct memory mapping without buffer allocation
//! - **Lazy loading** - Map files only when accessed
//! - **Range request support** - Efficient partial file serving
//! - **Platform optimizations** - Uses OS-level optimizations (sendfile, etc.)
//!
//! # Safety
//!
//! Memory mapping is inherently unsafe as it involves raw pointer access. This module
//! provides a safe wrapper that ensures proper lifetime management and error handling.

use bytes::Bytes;
use memmap2::Mmap;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use thiserror::Error;

// ============================================================================
// Error Types
// ============================================================================

/// Errors that can occur during memory-mapped operations
#[derive(Debug, Error)]
pub enum MmapError {
    #[error("Failed to open file: {0}")]
    FileOpen(#[from] io::Error),

    #[error("Failed to create memory map: {0}")]
    MmapCreation(String),

    #[error("Invalid range: {0}")]
    InvalidRange(String),

    #[error("File not found: {0}")]
    FileNotFound(String),
}

// ============================================================================
// Memory-Mapped File Handle
// ============================================================================

/// A handle to a memory-mapped file
///
/// This structure provides safe access to memory-mapped files with proper
/// lifetime management and error handling.
pub struct MmapFile {
    /// The memory-mapped region
    mmap: Arc<Mmap>,
    /// Original file path (for debugging)
    path: PathBuf,
    /// Total file size
    size: usize,
}

impl MmapFile {
    /// Create a new memory-mapped file from a path
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the file to be memory-mapped
    ///
    /// # Returns
    ///
    /// A `Result` containing the `MmapFile` or an error
    ///
    /// # Safety
    ///
    /// This function is safe because it ensures:
    /// - File handle is valid
    /// - Memory map is created successfully
    /// - Lifetime of the mmap is tied to the struct
    pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, MmapError> {
        let path = path.as_ref();

        // Open the file
        let file = File::open(path).map_err(|e| {
            if e.kind() == io::ErrorKind::NotFound {
                MmapError::FileNotFound(path.display().to_string())
            } else {
                MmapError::FileOpen(e)
            }
        })?;

        // Get file size
        let metadata = file.metadata()?;
        let size = metadata.len() as usize;

        // Create memory map
        // SAFETY: The file is opened successfully and we have a valid file handle
        let mmap = unsafe { Mmap::map(&file).map_err(|e| MmapError::MmapCreation(e.to_string()))? };

        Ok(MmapFile {
            mmap: Arc::new(mmap),
            path: path.to_path_buf(),
            size,
        })
    }

    /// Get the full file contents as a Bytes object (zero-copy)
    ///
    /// This returns a `Bytes` object that references the memory-mapped region
    /// without copying the data.
    pub fn bytes(&self) -> Bytes {
        Bytes::copy_from_slice(&self.mmap[..])
    }

    /// Get a range of bytes from the file (zero-copy slice)
    ///
    /// # Arguments
    ///
    /// * `range` - The byte range to retrieve (start..end)
    ///
    /// # Returns
    ///
    /// A `Bytes` object containing the requested range
    pub fn range(&self, range: std::ops::Range<usize>) -> Result<Bytes, MmapError> {
        if range.start > self.size {
            return Err(MmapError::InvalidRange(format!(
                "Start {} exceeds file size {}",
                range.start, self.size
            )));
        }

        if range.end > self.size {
            return Err(MmapError::InvalidRange(format!(
                "End {} exceeds file size {}",
                range.end, self.size
            )));
        }

        if range.start >= range.end {
            return Err(MmapError::InvalidRange(format!(
                "Invalid range: {}..{}",
                range.start, range.end
            )));
        }

        Ok(Bytes::copy_from_slice(&self.mmap[range]))
    }

    /// Get the file size in bytes
    pub fn size(&self) -> usize {
        self.size
    }

    /// Get the file path
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Check if the file is empty
    pub fn is_empty(&self) -> bool {
        self.size == 0
    }

    /// Get multiple ranges efficiently (for HTTP multi-range requests)
    ///
    /// # Arguments
    ///
    /// * `ranges` - Vector of byte ranges to retrieve
    ///
    /// # Returns
    ///
    /// A vector of `Bytes` objects, one for each range
    pub fn multi_range(&self, ranges: &[std::ops::Range<usize>]) -> Result<Vec<Bytes>, MmapError> {
        let mut results = Vec::with_capacity(ranges.len());

        for range in ranges {
            results.push(self.range(range.clone())?);
        }

        Ok(results)
    }
}

// Implement Clone for MmapFile (cheap because of Arc)
impl Clone for MmapFile {
    fn clone(&self) -> Self {
        MmapFile {
            mmap: Arc::clone(&self.mmap),
            path: self.path.clone(),
            size: self.size,
        }
    }
}

// ============================================================================
// Memory-Mapped File Cache
// ============================================================================

/// A simple cache for memory-mapped files
///
/// This cache stores recently accessed memory-mapped files to avoid
/// repeated file opening and mapping operations.
#[allow(dead_code)]
pub struct MmapCache {
    /// Maximum number of cached files
    max_entries: usize,
    /// Cache storage (simple LRU would be better in production)
    cache: dashmap::DashMap<PathBuf, Arc<MmapFile>>,
}

impl MmapCache {
    /// Create a new mmap cache
    ///
    /// # Arguments
    ///
    /// * `max_entries` - Maximum number of files to keep in cache
    pub fn new(max_entries: usize) -> Self {
        MmapCache {
            max_entries,
            cache: dashmap::DashMap::new(),
        }
    }

    /// Get or create a memory-mapped file
    ///
    /// If the file is in cache, return the cached version. Otherwise,
    /// create a new mmap and cache it.
    pub fn get_or_create<P: AsRef<Path>>(&self, path: P) -> Result<Arc<MmapFile>, MmapError> {
        let path = path.as_ref();

        // Check cache first
        if let Some(cached) = self.cache.get(path) {
            return Ok(Arc::clone(&*cached));
        }

        // Create new mmap
        let mmap_file = Arc::new(MmapFile::new(path)?);

        // Add to cache (simple eviction: just check size)
        if self.cache.len() >= self.max_entries {
            // In production, implement proper LRU eviction
            // For now, just allow growth
            tracing::warn!(
                "Mmap cache size {} exceeds max {}",
                self.cache.len(),
                self.max_entries
            );
        }

        self.cache
            .insert(path.to_path_buf(), Arc::clone(&mmap_file));

        Ok(mmap_file)
    }

    /// Clear the cache
    pub fn clear(&self) {
        self.cache.clear();
    }

    /// Get current cache size
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Check if cache is empty
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }
}

// ============================================================================
// Platform-Specific Optimizations
// ============================================================================

/// Platform-specific optimization hints
#[derive(Debug, Clone, Copy)]
pub struct MmapConfig {
    /// Use hugepages if available (Linux)
    pub use_hugepages: bool,

    /// Advise sequential access pattern
    pub sequential_access: bool,

    /// Advise random access pattern
    pub random_access: bool,

    /// Pre-populate the page tables (Linux)
    pub populate: bool,
}

impl Default for MmapConfig {
    fn default() -> Self {
        MmapConfig {
            use_hugepages: false,
            sequential_access: true,
            random_access: false,
            populate: false,
        }
    }
}

impl MmapConfig {
    /// Configuration optimized for sequential tensor streaming
    pub fn sequential() -> Self {
        MmapConfig {
            use_hugepages: false,
            sequential_access: true,
            random_access: false,
            populate: false,
        }
    }

    /// Configuration optimized for random access (e.g., tensor slicing)
    pub fn random() -> Self {
        MmapConfig {
            use_hugepages: false,
            sequential_access: false,
            random_access: true,
            populate: false,
        }
    }

    /// Configuration for large files with hugepage support
    pub fn hugepages() -> Self {
        MmapConfig {
            use_hugepages: true,
            sequential_access: false,
            random_access: false,
            populate: true,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn create_test_file() -> (tempfile::NamedTempFile, Vec<u8>) {
        let mut file = tempfile::NamedTempFile::new().unwrap();
        let data: Vec<u8> = (0..1024).map(|i| (i % 256) as u8).collect();
        file.write_all(&data).unwrap();
        file.flush().unwrap();
        (file, data)
    }

    #[test]
    fn test_mmap_file_creation() {
        let (file, _data) = create_test_file();
        let mmap = MmapFile::new(file.path()).unwrap();
        assert_eq!(mmap.size(), 1024);
        assert!(!mmap.is_empty());
    }

    #[test]
    fn test_mmap_file_not_found() {
        let result = MmapFile::new("/nonexistent/file.bin");
        assert!(result.is_err());
        match result {
            Err(MmapError::FileNotFound(_)) => {}
            _ => panic!("Expected FileNotFound error"),
        }
    }

    #[test]
    fn test_mmap_bytes() {
        let (file, data) = create_test_file();
        let mmap = MmapFile::new(file.path()).unwrap();
        let bytes = mmap.bytes();
        assert_eq!(bytes.len(), 1024);
        assert_eq!(&bytes[..], &data[..]);
    }

    #[test]
    fn test_mmap_range() {
        let (file, data) = create_test_file();
        let mmap = MmapFile::new(file.path()).unwrap();

        let range = mmap.range(10..50).unwrap();
        assert_eq!(range.len(), 40);
        assert_eq!(&range[..], &data[10..50]);
    }

    #[test]
    fn test_mmap_range_invalid() {
        let (file, _data) = create_test_file();
        let mmap = MmapFile::new(file.path()).unwrap();

        // Start > size
        assert!(mmap.range(2000..2100).is_err());

        // End > size
        assert!(mmap.range(1000..2000).is_err());

        // Start >= end
        assert!(mmap.range(100..100).is_err());
    }

    #[test]
    fn test_mmap_multi_range() {
        let (file, data) = create_test_file();
        let mmap = MmapFile::new(file.path()).unwrap();

        let ranges = vec![0..10, 50..60, 100..120];
        let results = mmap.multi_range(&ranges).unwrap();

        assert_eq!(results.len(), 3);
        assert_eq!(&results[0][..], &data[0..10]);
        assert_eq!(&results[1][..], &data[50..60]);
        assert_eq!(&results[2][..], &data[100..120]);
    }

    #[test]
    fn test_mmap_clone() {
        let (file, _data) = create_test_file();
        let mmap1 = MmapFile::new(file.path()).unwrap();
        let mmap2 = mmap1.clone();

        assert_eq!(mmap1.size(), mmap2.size());
        assert_eq!(mmap1.path(), mmap2.path());
    }

    #[test]
    fn test_mmap_cache() {
        let (file, _data) = create_test_file();
        let cache = MmapCache::new(10);

        // First access - creates mmap
        let mmap1 = cache.get_or_create(file.path()).unwrap();
        assert_eq!(cache.len(), 1);

        // Second access - retrieves from cache
        let mmap2 = cache.get_or_create(file.path()).unwrap();
        assert_eq!(cache.len(), 1);

        // Should be the same Arc
        assert_eq!(mmap1.size(), mmap2.size());
    }

    #[test]
    fn test_mmap_cache_clear() {
        let (file, _data) = create_test_file();
        let cache = MmapCache::new(10);

        cache.get_or_create(file.path()).unwrap();
        assert_eq!(cache.len(), 1);

        cache.clear();
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_mmap_config_presets() {
        let sequential = MmapConfig::sequential();
        assert!(sequential.sequential_access);
        assert!(!sequential.random_access);

        let random = MmapConfig::random();
        assert!(!random.sequential_access);
        assert!(random.random_access);

        let hugepages = MmapConfig::hugepages();
        assert!(hugepages.use_hugepages);
        assert!(hugepages.populate);
    }
}