noxu-log 7.1.0

Log-structured storage engine for Noxu DB
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
474
475
476
477
478
479
480
481
482
483
484
//! File handle with latch protection.
//!
//!
//! A FileHandle wraps a file descriptor with a latch to ensure exclusive
//! access during I/O operations.

use crate::error::{LogError, Result};
use noxu_latch::{ExclusiveLatch, ExclusiveLatchGuard};
use noxu_sync::Mutex;
use std::fs::File;
use std::sync::Arc;

use crate::posio;

/// A file handle with latch protection for thread-safe I/O.
///
/// The handle holds a file descriptor and an exclusive latch.
/// All I/O operations must be performed while holding the latch.
pub struct FileHandle {
    /// The underlying file (wrapped in Mutex for interior mutability).
    file: Mutex<Option<File>>,
    /// Latch protecting access to the file.
    latch: Arc<ExclusiveLatch>,
    /// Log version of this file.
    log_version: u32,
    /// File number this handle represents.
    file_num: u32,
}

impl FileHandle {
    /// Creates a new uninitialized file handle.
    ///
    /// The file must be initialized via `init()` before use.
    pub fn new(file_num: u32) -> Self {
        let latch =
            Arc::new(ExclusiveLatch::named(format!("file_{:08x}", file_num)));

        FileHandle { file: Mutex::new(None), latch, log_version: 0, file_num }
    }

    /// Initializes the handle with an open file and log version.
    pub fn init(&mut self, file: File, log_version: u32) {
        let mut f = self.file.lock();
        assert!(f.is_none(), "FileHandle already initialized");
        *f = Some(file);
        self.log_version = log_version;
    }

    /// Returns the file number.
    pub fn file_num(&self) -> u32 {
        self.file_num
    }

    /// Returns the log version.
    pub fn log_version(&self) -> u32 {
        self.log_version
    }

    /// Returns true if the file is initialized.
    pub fn is_initialized(&self) -> bool {
        self.file.lock().is_some()
    }

    /// Acquires the latch and returns a guard that provides access to the file.
    ///
    /// Returns `Ok(guard)` on success, or `Err(LogError::LatchTimeout)` if the
    /// latch acquisition times out. The latch is released when the guard drops.
    pub fn acquire(&self) -> Result<FileHandleGuard<'_>> {
        let _latch_guard = self
            .latch
            .acquire()
            .map_err(|e| LogError::LatchTimeout(e.to_string()))?;
        Ok(FileHandleGuard { handle: self, _latch_guard })
    }

    /// Attempts to acquire the latch without blocking.
    ///
    /// Returns `None` if the latch is currently held.
    pub fn try_acquire(&self) -> Option<FileHandleGuard<'_>> {
        self.latch
            .try_acquire()
            .map(|_latch_guard| FileHandleGuard { handle: self, _latch_guard })
    }

    /// Closes the file handle.
    ///
    /// This should only be called when the handle is no longer in use.
    pub fn close(&mut self) -> Result<()> {
        if let Some(file) = self.file.lock().take() {
            drop(file); // File is closed when dropped
        }
        Ok(())
    }
}

impl Drop for FileHandle {
    fn drop(&mut self) {
        let _ = self.close();
    }
}

/// RAII guard providing access to the file while the latch is held.
pub struct FileHandleGuard<'a> {
    handle: &'a FileHandle,
    _latch_guard: ExclusiveLatchGuard<'a>,
}

impl<'a> FileHandleGuard<'a> {
    /// Reads data from the file at the given offset.
    ///
    /// # Arguments
    ///
    /// * `offset` - File offset to read from
    /// * `buf` - Buffer to read into
    ///
    /// # Returns
    ///
    /// Number of bytes read.
    /// Reads data from the file at the given offset.
    ///
    /// Uses `pread64` (one syscall) instead of `lseek + read` (two syscalls).
    /// The JVM
    /// lowers to `pread64` on Linux.
    pub fn read_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<usize> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        Ok(posio::read_at(file, buf, offset)?)
    }

    /// Reads exactly `buf.len()` bytes from the file at the given offset.
    ///
    /// Uses `pread64` in a retry loop.
    /// Returns an error if fewer bytes are available.
    pub fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> Result<()> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        posio::read_exact_at(file, buf, offset)?;
        Ok(())
    }

    /// Writes data to the file at the given offset.
    ///
    /// Uses `pwrite64` (one syscall) instead of `lseek + write` (two syscalls).
    /// `FileChannel.write(ByteBuffer, position)` which the JVM
    /// lowers to `pwrite64` on Linux.  This eliminates half the syscalls on
    /// the hot write path and removes the need to serialise seek+write under
    /// the guard (pwrite64 is inherently positional and thread-safe).
    ///
    /// # Arguments
    ///
    /// * `offset` - File offset to write to (passed directly to pwrite64)
    /// * `buf` - Data to write
    ///
    /// # Returns
    ///
    /// Number of bytes written (always `buf.len()` on success).
    pub fn write_at(&mut self, offset: u64, buf: &[u8]) -> Result<usize> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        posio::write_all_at(file, buf, offset)?;
        Ok(buf.len())
    }

    /// Syncs all file data and metadata to disk (fsync).
    ///
    /// Use this when the file's metadata (size, mtime) must also be durable —
    /// typically for file-header writes.  For log-data writes prefer
    /// `sync_data()` which is faster.
    pub fn sync(&mut self) -> Result<()> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        // DST fault layer (inactive in production): a dropped fsync is
        // acknowledged without flushing, then power is cut so the unsynced
        // bytes vanish — modelling a disk that lies about durability.
        if crate::faultdisk::on_fsync() {
            drop(file_guard);
            crate::faultdisk::power_cut();
        }
        file.sync_all()?;
        Ok(())
    }

    /// Syncs only the file data to disk (fdatasync).
    ///
    /// Faster than `sync()` because it does not flush file metadata (mtime
    /// etc.).  uses `FileChannel.force(false)` (= fdatasync) for all
    /// log-data writes and `force(true)` (= fsync) only for file-header writes.
    ///
    /// / `FileChannel.force(false)`.
    pub fn sync_data(&mut self) -> Result<()> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        // DST fault layer (inactive in production): see `sync` above.
        if crate::faultdisk::on_fsync() {
            drop(file_guard);
            crate::faultdisk::power_cut();
        }
        file.sync_data()?;
        Ok(())
    }

    /// Returns true if the file is empty.
    pub fn is_empty(&mut self) -> Result<bool> {
        Ok(self.len()? == 0)
    }

    /// Returns the file length.
    pub fn len(&mut self) -> Result<u64> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        Ok(file.metadata()?.len())
    }

    /// Truncates the file to the given length.
    pub fn truncate(&mut self, len: u64) -> Result<()> {
        let file_guard = self.handle.file.lock();
        let file = file_guard.as_ref().ok_or_else(|| {
            LogError::Internal("FileHandle not initialized".to_string())
        })?;
        file.set_len(len)?;
        Ok(())
    }

    /// Returns the file number.
    pub fn file_num(&self) -> u32 {
        self.handle.file_num()
    }

    /// Returns the log version.
    pub fn log_version(&self) -> u32 {
        self.handle.log_version()
    }
}

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

    #[test]
    fn test_file_handle_basic() {
        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(b"Hello, world!").unwrap();
        temp_file.flush().unwrap();

        let file = File::open(temp_file.path()).unwrap();

        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        assert_eq!(handle.file_num(), 0);
        assert_eq!(handle.log_version(), 1);
        assert!(handle.is_initialized());
    }

    #[test]
    fn test_file_handle_read_write() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::options()
            .read(true)
            .write(true)
            .open(temp_file.path())
            .unwrap();

        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        {
            let mut guard = handle.acquire().expect("acquire");
            guard.write_at(0, b"test data").unwrap();
            guard.sync().unwrap();
        }

        {
            let mut guard = handle.acquire().expect("acquire");
            let mut buf = vec![0u8; 9];
            let n = guard.read_at(0, &mut buf).unwrap();
            assert_eq!(n, 9);
            assert_eq!(&buf, b"test data");
        }
    }

    #[test]
    fn test_file_handle_new_uninitialized() {
        let handle = FileHandle::new(42);
        assert_eq!(handle.file_num(), 42);
        assert_eq!(handle.log_version(), 0);
        assert!(!handle.is_initialized());
    }

    #[test]
    fn test_file_handle_log_version_set_on_init() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::open(temp_file.path()).unwrap();
        let mut handle = FileHandle::new(7);
        handle.init(file, 5);
        assert_eq!(handle.log_version(), 5);
        assert!(handle.is_initialized());
    }

    #[test]
    fn test_file_handle_file_num_preserved() {
        let mut handle = FileHandle::new(0xFF);
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::open(temp_file.path()).unwrap();
        handle.init(file, 1);
        assert_eq!(handle.file_num(), 0xFF);
    }

    #[test]
    fn test_file_handle_close_uninitialised() {
        let mut handle = FileHandle::new(0);
        // Closing a non-initialized handle should not error
        assert!(handle.close().is_ok());
        assert!(!handle.is_initialized());
    }

    #[test]
    fn test_file_handle_close_initialized() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::open(temp_file.path()).unwrap();
        let mut handle = FileHandle::new(1);
        handle.init(file, 1);
        assert!(handle.is_initialized());
        assert!(handle.close().is_ok());
        assert!(!handle.is_initialized());
    }

    #[test]
    fn test_file_handle_guard_file_num() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::open(temp_file.path()).unwrap();
        let mut handle = FileHandle::new(99);
        handle.init(file, 3);
        let guard = handle.acquire().expect("acquire");
        assert_eq!(guard.file_num(), 99);
        assert_eq!(guard.log_version(), 3);
    }

    #[test]
    fn test_file_handle_guard_read_exact() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::options()
            .read(true)
            .write(true)
            .open(temp_file.path())
            .unwrap();
        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        {
            let mut guard = handle.acquire().expect("acquire");
            guard.write_at(0, b"hello").unwrap();
        }
        {
            let mut guard = handle.acquire().expect("acquire");
            let mut buf = vec![0u8; 5];
            guard.read_exact_at(0, &mut buf).unwrap();
            assert_eq!(&buf, b"hello");
        }
    }

    #[test]
    fn test_file_handle_guard_len_and_is_empty() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::options()
            .read(true)
            .write(true)
            .open(temp_file.path())
            .unwrap();
        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        {
            let mut guard = handle.acquire().expect("acquire");
            assert!(guard.is_empty().unwrap());
            assert_eq!(guard.len().unwrap(), 0);
            guard.write_at(0, b"abc").unwrap();
        }
        {
            let mut guard = handle.acquire().expect("acquire");
            assert!(!guard.is_empty().unwrap());
            assert_eq!(guard.len().unwrap(), 3);
        }
    }

    #[test]
    fn test_file_handle_guard_truncate() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::options()
            .read(true)
            .write(true)
            .open(temp_file.path())
            .unwrap();
        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        {
            let mut guard = handle.acquire().expect("acquire");
            guard.write_at(0, b"hello world").unwrap();
        }
        {
            let mut guard = handle.acquire().expect("acquire");
            guard.truncate(5).unwrap();
            assert_eq!(guard.len().unwrap(), 5);
        }
    }

    #[test]
    fn test_file_handle_try_acquire() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::open(temp_file.path()).unwrap();
        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        let guard = handle.try_acquire();
        assert!(guard.is_some());
        // Guard released when dropped, then try_acquire succeeds again
        drop(guard);
        let guard2 = handle.try_acquire();
        assert!(guard2.is_some());
    }

    #[test]
    fn test_file_handle_read_at_offset() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::options()
            .read(true)
            .write(true)
            .open(temp_file.path())
            .unwrap();
        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        {
            let mut guard = handle.acquire().expect("acquire");
            guard.write_at(0, b"ABCDEF").unwrap();
        }
        {
            let mut guard = handle.acquire().expect("acquire");
            let mut buf = vec![0u8; 3];
            let n = guard.read_at(2, &mut buf).unwrap();
            assert_eq!(n, 3);
            assert_eq!(&buf, b"CDE");
        }
    }

    #[test]
    fn test_file_handle_write_at_offset() {
        let temp_file = NamedTempFile::new().unwrap();
        let file = File::options()
            .read(true)
            .write(true)
            .open(temp_file.path())
            .unwrap();
        let mut handle = FileHandle::new(0);
        handle.init(file, 1);

        {
            let mut guard = handle.acquire().expect("acquire");
            guard.write_at(0, b"XXXXXXXX").unwrap();
            guard.write_at(2, b"AB").unwrap();
        }
        {
            let mut guard = handle.acquire().expect("acquire");
            let mut buf = vec![0u8; 8];
            guard.read_exact_at(0, &mut buf).unwrap();
            assert_eq!(&buf[2..4], b"AB");
        }
    }
}