hawdb-storage 0.13.0

An embedded Rust graph database for local data-plane workloads
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
// Copyright 2026 Nowledge
// Licensed under the Apache License, Version 2.0.

use super::*;
use std::os::fd::{AsRawFd, FromRawFd};
use std::os::unix::fs::OpenOptionsExt;

pub(super) fn open_root(path: &Path) -> io::Result<std::fs::File> {
    std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_DIRECTORY | libc::O_CLOEXEC)
        .open(path)
}

fn name_bytes(name: ChildName<'_>) -> [u8; 256] {
    let mut bytes = [0; 256];
    bytes[..name.0.len()].copy_from_slice(name.0.as_bytes());
    bytes
}

pub(super) fn create_directory(root: &std::fs::File, name: ChildName<'_>) -> io::Result<()> {
    let name = name_bytes(name);
    // SAFETY: the live parent FD and terminated validated single component
    // outlive mkdirat. Creation is exclusive; an existing symlink is not followed.
    let result = unsafe { libc::mkdirat(root.as_raw_fd(), name.as_ptr().cast(), 0o700) };
    if result == -1 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

pub(super) fn create_control_candidate(
    root: &std::fs::File,
    name: ChildName<'_>,
) -> io::Result<std::fs::File> {
    let name = name_bytes(name);
    // SAFETY: live root, terminated validated component, exclusive regular-file
    // creation with a supplied mode. No existing entry or symlink is followed.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            name.as_ptr().cast(),
            libc::O_RDWR | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC | libc::O_NOFOLLOW,
            0o600,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful openat transferred one fresh owned descriptor.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

pub(super) fn replace_control(
    root: &std::fs::File,
    _file: &std::fs::File,
    source: ChildName<'_>,
    target: ChildName<'_>,
) -> io::Result<()> {
    let source = name_bytes(source);
    let target = name_bytes(target);
    // SAFETY: both canonical components and the same borrowed native directory
    // remain live. The caller excludes mutation/reuse of the private candidate.
    let result = unsafe {
        libc::renameat(
            root.as_raw_fd(),
            source.as_ptr().cast(),
            root.as_raw_fd(),
            target.as_ptr().cast(),
        )
    };
    if result == -1 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

pub(super) fn open_wal_append_child(
    root: &std::fs::File,
    name: ChildName<'_>,
) -> io::Result<std::fs::File> {
    let name = name_bytes(name);
    // SAFETY: held root, validated terminated child, existing regular file.
    // O_APPEND preserves end-of-file writes independently of the replay cursor.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            name.as_ptr().cast(),
            libc::O_RDWR | libc::O_APPEND | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful openat transfers one fresh owned descriptor.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

pub(super) fn open_mutable_child(
    root: &std::fs::File,
    name: ChildName<'_>,
) -> io::Result<std::fs::File> {
    let name = name_bytes(name);
    // SAFETY: live root and terminated canonical component. No creation,
    // truncation, symlink traversal or path lookup outside this capture.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            name.as_ptr().cast(),
            libc::O_RDWR | libc::O_CLOEXEC | libc::O_NOFOLLOW,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful openat transferred one fresh owned descriptor.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

#[cfg(all(
    any(test, feature = "test-support"),
    any(target_os = "linux", target_vendor = "apple")
))]
pub(super) fn reopen_directory(root: &std::fs::File) -> io::Result<std::fs::File> {
    open_directory(root, ChildName("."))
}

pub(super) fn sync_directory(root: &std::fs::File, _context: &FileOpenContext) -> io::Result<()> {
    root.sync_all()
}

#[cfg(any(test, feature = "test-support"))]
pub(super) fn open_recorded_lock(
    root: &std::fs::File,
    name: ChildName<'_>,
    create_new: bool,
) -> io::Result<std::fs::File> {
    let bytes = name_bytes(name);
    let create = if create_new {
        libc::O_CREAT | libc::O_EXCL
    } else {
        0
    };
    // SAFETY: live parent, validated terminated component and ordinary mode.
    // Exclusive creation cannot adopt a foreign entry; existing opens cannot
    // recreate an entry missing from the recorded native namespace.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            bytes.as_ptr().cast(),
            libc::O_RDWR | create | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK,
            0o600,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: one fresh owned descriptor from successful openat.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

pub(super) fn open_child(root: &std::fs::File, name: ChildName<'_>) -> io::Result<std::fs::File> {
    let bytes = name_bytes(name);
    // SAFETY: root is borrowed live; validated ASCII name is NUL-terminated in
    // fixed scratch. Read-only open needs no mode argument. NONBLOCK prevents a
    // corrupt FIFO entry blocking before the caller checks regular-file type.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            bytes.as_ptr().cast(),
            libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful openat returned a fresh owned descriptor exactly once.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

pub(super) fn open_directory(
    root: &std::fs::File,
    name: ChildName<'_>,
) -> io::Result<std::fs::File> {
    let bytes = name_bytes(name);
    // SAFETY: live borrowed directory, validated NUL-terminated component;
    // O_DIRECTORY and O_NOFOLLOW reject files and symlinks before returning.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            bytes.as_ptr().cast(),
            libc::O_RDONLY
                | libc::O_DIRECTORY
                | libc::O_CLOEXEC
                | libc::O_NOFOLLOW
                | libc::O_NONBLOCK,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: exactly one fresh owned descriptor from successful openat.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

pub(super) fn remove_child(
    root: &std::fs::File,
    name: ChildName<'_>,
    _context: &FileOpenContext,
) -> io::Result<()> {
    let bytes = name_bytes(name);
    // SAFETY: borrowed live root and NUL-terminated single-component name; flags
    // zero unlink a file entry and cannot recursively delete a directory.
    let status = unsafe { libc::unlinkat(root.as_raw_fd(), bytes.as_ptr().cast(), 0) };
    if status == -1 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

pub(super) fn remove_directory(
    root: &std::fs::File,
    name: ChildName<'_>,
    _context: &FileOpenContext,
) -> io::Result<()> {
    let name = name_bytes(name);
    // SAFETY: live captured parent and validated, terminated child component.
    // AT_REMOVEDIR rejects regular files and nonempty directories.
    let result =
        unsafe { libc::unlinkat(root.as_raw_fd(), name.as_ptr().cast(), libc::AT_REMOVEDIR) };
    if result == -1 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

pub(super) fn open_lock_file(
    root: &std::fs::File,
    name: ChildName<'_>,
    mode: SourceDirectoryLockMode,
) -> io::Result<std::fs::File> {
    let bytes = name_bytes(name);
    let access = match mode {
        SourceDirectoryLockMode::ReadExisting => libc::O_RDONLY,
        SourceDirectoryLockMode::ReadWriteCreate => libc::O_RDWR | libc::O_CREAT,
    };
    // SAFETY: validated NUL-terminated component, borrowed live directory,
    // valid open flags and permission mode. No truncation or symlink traversal.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            bytes.as_ptr().cast(),
            access | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK,
            0o600,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: one fresh owned descriptor from successful openat.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

// A new open file description avoids sharing enumeration offsets between
// concurrent/repeated visitors. Duplicating root's FD would share its offset.
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
pub(super) fn visit_children(
    root: &std::fs::File,
    visitor: &mut dyn FnMut(&str) -> io::Result<()>,
) -> io::Result<()> {
    visit_names(root, &mut |name| {
        let name = name.to_str().ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "source directory contains a non-UTF-8 name",
            )
        })?;
        visitor(name)
    })
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
pub(super) fn visit_names(
    root: &std::fs::File,
    visitor: &mut dyn FnMut(&std::ffi::OsStr) -> io::Result<()>,
) -> io::Result<()> {
    use std::os::unix::ffi::OsStrExt;
    // SAFETY: borrowed directory and static NUL-terminated relative component.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            c".".as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: the fresh descriptor is exclusively transferred on success.
    let directory = unsafe { libc::fdopendir(fd) };
    if directory.is_null() {
        let error = io::Error::last_os_error();
        // SAFETY: fdopendir failed, so ownership was not transferred.
        unsafe {
            libc::close(fd);
        }
        return Err(error);
    }
    struct Cursor(*mut libc::DIR);
    impl Drop for Cursor {
        fn drop(&mut self) {
            // SAFETY: owns one live stream; closedir also closes its FD.
            unsafe {
                libc::closedir(self.0);
            }
        }
    }
    let cursor = Cursor(directory);
    loop {
        // SAFETY: errno is thread-local; this cursor is local to this call.
        let entry = unsafe {
            #[cfg(target_os = "linux")]
            {
                *libc::__errno_location() = 0;
            }
            #[cfg(target_vendor = "apple")]
            {
                *libc::__error() = 0;
            }
            libc::readdir(cursor.0)
        };
        if entry.is_null() {
            let error = io::Error::last_os_error();
            return if error.raw_os_error() == Some(0) {
                Ok(())
            } else {
                Err(error)
            };
        }
        // SAFETY: readdir returns a NUL-terminated name valid until the next
        // call on this stream. It cannot escape the borrowed callback.
        let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) };
        if matches!(name.to_bytes(), b"." | b"..") {
            continue;
        }
        visitor(std::ffi::OsStr::from_bytes(name.to_bytes()))?;
    }
}

#[cfg(all(
    any(test, feature = "test-support"),
    any(target_os = "linux", target_vendor = "apple")
))]
pub(super) fn open_recorded_child(
    root: &std::fs::File,
    name: &std::ffi::OsStr,
) -> io::Result<std::fs::File> {
    use std::os::unix::ffi::OsStrExt;
    let name = name.as_bytes();
    if name.is_empty()
        || name.len() > 255
        || matches!(name, b"." | b"..")
        || name.iter().any(|byte| matches!(byte, 0 | b'/'))
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "invalid native child name",
        ));
    }
    let mut encoded = [0_u8; 256];
    encoded[..name.len()].copy_from_slice(name);
    let mut metadata = std::mem::MaybeUninit::<libc::stat>::uninit();
    // SAFETY: live parent, validated terminated component, valid stat output.
    // Do not open devices or FIFOs merely to discover their type.
    let result = unsafe {
        libc::fstatat(
            root.as_raw_fd(),
            encoded.as_ptr().cast(),
            metadata.as_mut_ptr(),
            libc::AT_SYMLINK_NOFOLLOW,
        )
    };
    if result == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful fstatat initialized the entire stat record.
    let kind = unsafe { metadata.assume_init() }.st_mode & libc::S_IFMT;
    if kind != libc::S_IFREG && kind != libc::S_IFDIR {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "captured project contains a nonregular file",
        ));
    }
    // SAFETY: counted live parent, validated single native component in
    // NUL-terminated scratch. NONBLOCK rejects blocking FIFO opens; NOFOLLOW
    // rejects links. The caller validates regular-file/directory metadata.
    let fd = unsafe {
        libc::openat(
            root.as_raw_fd(),
            encoded.as_ptr().cast(),
            libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK,
        )
    };
    if fd == -1 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: one fresh owned descriptor from successful openat.
    Ok(unsafe { std::fs::File::from_raw_fd(fd) })
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
pub(super) fn visit_children(
    _root: &std::fs::File,
    _visitor: &mut dyn FnMut(&str) -> io::Result<()>,
) -> io::Result<()> {
    Err(io::Error::new(
        io::ErrorKind::Unsupported,
        "source directory enumeration requires Linux, Apple or Windows",
    ))
}

// Do not open/close another descriptor to a POSIX process-owned lock inode.
pub(super) fn matches_child_file(
    root: &std::fs::File,
    name: ChildName<'_>,
    file: &std::fs::File,
    _context: &FileOpenContext,
) -> io::Result<bool> {
    use std::os::unix::fs::MetadataExt;
    let name = name_bytes(name);
    let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
    // SAFETY: live root, fixed terminated component, writable stat, and no
    // symlink traversal. On success fstatat initializes the whole stat object.
    if unsafe {
        libc::fstatat(
            root.as_raw_fd(),
            name.as_ptr().cast(),
            stat.as_mut_ptr(),
            libc::AT_SYMLINK_NOFOLLOW,
        )
    } == -1
    {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful fstatat initialized stat above.
    let stat = unsafe { stat.assume_init() };
    if stat.st_mode & libc::S_IFMT != libc::S_IFREG {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "source child is not a regular non-symlink file",
        ));
    }
    let held = file.metadata()?;
    // Darwin's dev_t is signed; normalize its sign extension just as MetadataExt
    // does. Other Unix device types are unsigned. Both fit exactly in i128.
    fn device_number(value: impl Into<i128>) -> u64 {
        value.into() as u64
    }
    Ok(held.is_file() && held.dev() == device_number(stat.st_dev) && held.ino() == stat.st_ino)
}