lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Filesystem event types and structures.
//!
//! This module defines the core types for filesystem event notification,
//! similar to Linux's inotify system.

use alloc::string::{String, ToString};
use alloc::vec::Vec;

// ═══════════════════════════════════════════════════════════════════════════════
// EVENT TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Types of filesystem events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum EventType {
    /// File created
    Create = 0x00000001,
    /// File modified (content changed)
    Modify = 0x00000002,
    /// File deleted
    Delete = 0x00000004,
    /// File renamed/moved
    Rename = 0x00000008,
    /// File attributes changed (permissions, timestamps, etc.)
    Attrib = 0x00000010,
    /// File opened for reading/writing
    Open = 0x00000020,
    /// File closed
    Close = 0x00000040,
    /// Directory created
    DirCreate = 0x00000080,
    /// Directory deleted
    DirDelete = 0x00000100,
    /// Metadata sync (fsync called)
    Sync = 0x00000200,
    /// Truncate operation
    Truncate = 0x00000400,
    /// Hard link created
    Link = 0x00000800,
    /// Symbolic link created
    Symlink = 0x00001000,
    /// Extended attribute modified
    Xattr = 0x00002000,
    /// Clone/reflink operation
    Clone = 0x00004000,
}

impl EventType {
    /// Get the bitmask value for this event type.
    pub fn mask(&self) -> u32 {
        *self as u32
    }

    /// Get string representation.
    pub fn as_str(&self) -> &'static str {
        match self {
            EventType::Create => "CREATE",
            EventType::Modify => "MODIFY",
            EventType::Delete => "DELETE",
            EventType::Rename => "RENAME",
            EventType::Attrib => "ATTRIB",
            EventType::Open => "OPEN",
            EventType::Close => "CLOSE",
            EventType::DirCreate => "DIR_CREATE",
            EventType::DirDelete => "DIR_DELETE",
            EventType::Sync => "SYNC",
            EventType::Truncate => "TRUNCATE",
            EventType::Link => "LINK",
            EventType::Symlink => "SYMLINK",
            EventType::Xattr => "XATTR",
            EventType::Clone => "CLONE",
        }
    }

    /// Parse from string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "CREATE" => Some(EventType::Create),
            "MODIFY" => Some(EventType::Modify),
            "DELETE" => Some(EventType::Delete),
            "RENAME" => Some(EventType::Rename),
            "ATTRIB" => Some(EventType::Attrib),
            "OPEN" => Some(EventType::Open),
            "CLOSE" => Some(EventType::Close),
            "DIR_CREATE" => Some(EventType::DirCreate),
            "DIR_DELETE" => Some(EventType::DirDelete),
            "SYNC" => Some(EventType::Sync),
            "TRUNCATE" => Some(EventType::Truncate),
            "LINK" => Some(EventType::Link),
            "SYMLINK" => Some(EventType::Symlink),
            "XATTR" => Some(EventType::Xattr),
            "CLONE" => Some(EventType::Clone),
            _ => None,
        }
    }

    /// Get all event types.
    pub fn all() -> &'static [EventType] {
        &[
            EventType::Create,
            EventType::Modify,
            EventType::Delete,
            EventType::Rename,
            EventType::Attrib,
            EventType::Open,
            EventType::Close,
            EventType::DirCreate,
            EventType::DirDelete,
            EventType::Sync,
            EventType::Truncate,
            EventType::Link,
            EventType::Symlink,
            EventType::Xattr,
            EventType::Clone,
        ]
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EVENT MASK
// ═══════════════════════════════════════════════════════════════════════════════

/// Bitmask for event types to watch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct EventMask(pub u32);

impl EventMask {
    /// Watch no events.
    pub const NONE: EventMask = EventMask(0);

    /// Watch all events.
    pub const ALL: EventMask = EventMask(0xFFFFFFFF);

    /// Watch all file modification events.
    pub const FILE_CHANGES: EventMask = EventMask(
        EventType::Create as u32
            | EventType::Modify as u32
            | EventType::Delete as u32
            | EventType::Rename as u32,
    );

    /// Watch all directory events.
    pub const DIR_CHANGES: EventMask =
        EventMask(EventType::DirCreate as u32 | EventType::DirDelete as u32);

    /// Create a new mask from a raw value.
    pub fn new(mask: u32) -> Self {
        EventMask(mask)
    }

    /// Create a mask from a slice of event types.
    pub fn from_events(events: &[EventType]) -> Self {
        let mut mask = 0u32;
        for event in events {
            mask |= event.mask();
        }
        EventMask(mask)
    }

    /// Check if this mask includes the given event type.
    pub fn contains(&self, event: EventType) -> bool {
        (self.0 & event.mask()) != 0
    }

    /// Add an event type to this mask.
    pub fn add(&mut self, event: EventType) {
        self.0 |= event.mask();
    }

    /// Remove an event type from this mask.
    pub fn remove(&mut self, event: EventType) {
        self.0 &= !event.mask();
    }

    /// Get the raw mask value.
    pub fn raw(&self) -> u32 {
        self.0
    }

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

    /// Get all event types in this mask.
    pub fn events(&self) -> Vec<EventType> {
        EventType::all()
            .iter()
            .filter(|e| self.contains(**e))
            .copied()
            .collect()
    }
}

impl core::ops::BitOr for EventMask {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        EventMask(self.0 | rhs.0)
    }
}

impl core::ops::BitAnd for EventMask {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self::Output {
        EventMask(self.0 & rhs.0)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FILESYSTEM EVENT
// ═══════════════════════════════════════════════════════════════════════════════

/// A filesystem event.
#[derive(Debug, Clone)]
pub struct FsEvent {
    /// Type of event
    pub event_type: EventType,
    /// Dataset where event occurred
    pub dataset: String,
    /// Path to the affected file/directory
    pub path: String,
    /// Object ID (inode equivalent)
    pub object_id: u64,
    /// Old path (for rename events)
    pub old_path: Option<String>,
    /// Timestamp (microseconds since epoch)
    pub timestamp: u64,
    /// Transaction group when event occurred
    pub txg: u64,
    /// Size of the file (if applicable)
    pub size: Option<u64>,
    /// Process ID that triggered the event (if known)
    pub pid: Option<u32>,
}

impl FsEvent {
    /// Create a new filesystem event.
    pub fn new(event_type: EventType, dataset: &str, path: &str) -> Self {
        Self {
            event_type,
            dataset: dataset.into(),
            path: path.into(),
            object_id: 0,
            old_path: None,
            timestamp: 0,
            txg: 0,
            size: None,
            pid: None,
        }
    }

    /// Set the object ID.
    pub fn with_object_id(mut self, id: u64) -> Self {
        self.object_id = id;
        self
    }

    /// Set the old path (for rename events).
    pub fn with_old_path(mut self, path: &str) -> Self {
        self.old_path = Some(path.into());
        self
    }

    /// Set the timestamp.
    pub fn with_timestamp(mut self, ts: u64) -> Self {
        self.timestamp = ts;
        self
    }

    /// Set the transaction group.
    pub fn with_txg(mut self, txg: u64) -> Self {
        self.txg = txg;
        self
    }

    /// Set the file size.
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = Some(size);
        self
    }

    /// Set the process ID.
    pub fn with_pid(mut self, pid: u32) -> Self {
        self.pid = Some(pid);
        self
    }

    /// Check if this is a directory event.
    pub fn is_directory(&self) -> bool {
        matches!(self.event_type, EventType::DirCreate | EventType::DirDelete)
    }

    /// Check if this is a rename event.
    pub fn is_rename(&self) -> bool {
        self.event_type == EventType::Rename
    }

    /// Get the filename from the path.
    pub fn filename(&self) -> &str {
        self.path.rsplit('/').next().unwrap_or(&self.path)
    }

    /// Get the parent directory from the path.
    pub fn parent(&self) -> &str {
        if let Some(idx) = self.path.rfind('/') {
            if idx == 0 { "/" } else { &self.path[..idx] }
        } else {
            "/"
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// WATCH DESCRIPTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// A watch descriptor returned when adding a watch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WatchDescriptor(pub u64);

impl WatchDescriptor {
    /// Create a new watch descriptor.
    pub fn new(id: u64) -> Self {
        WatchDescriptor(id)
    }

    /// Get the raw ID.
    pub fn id(&self) -> u64 {
        self.0
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// WATCH OPTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Options for creating a watch.
#[derive(Debug, Clone, Default)]
pub struct WatchOptions {
    /// Watch subdirectories recursively
    pub recursive: bool,
    /// Only watch for one event, then auto-remove
    pub oneshot: bool,
    /// Don't follow symlinks
    pub no_follow: bool,
    /// Exclude events on self (for directories)
    pub exclude_self: bool,
    /// Debounce interval in milliseconds (0 = no debouncing)
    pub debounce_ms: u64,
}

impl WatchOptions {
    /// Create recursive watch options.
    pub fn recursive() -> Self {
        Self {
            recursive: true,
            ..Default::default()
        }
    }

    /// Create oneshot watch options.
    pub fn oneshot() -> Self {
        Self {
            oneshot: true,
            ..Default::default()
        }
    }

    /// Set debounce interval.
    pub fn with_debounce(mut self, ms: u64) -> Self {
        self.debounce_ms = ms;
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// NOTIFY ERROR
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors that can occur in the notification system.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotifyError {
    /// Watch not found
    WatchNotFound(u64),
    /// Path not found
    PathNotFound(String),
    /// Too many watches
    TooManyWatches,
    /// Invalid path
    InvalidPath(String),
    /// Internal error
    Internal(String),
    /// Queue overflow
    QueueOverflow,
    /// No events available (for non-blocking poll)
    NoEvents,
    /// Timeout waiting for events
    Timeout,
}

impl NotifyError {
    /// Get error message.
    pub fn message(&self) -> String {
        match self {
            NotifyError::WatchNotFound(id) => alloc::format!("Watch {} not found", id),
            NotifyError::PathNotFound(path) => alloc::format!("Path not found: {}", path),
            NotifyError::TooManyWatches => "Too many watches".into(),
            NotifyError::InvalidPath(path) => alloc::format!("Invalid path: {}", path),
            NotifyError::Internal(msg) => alloc::format!("Internal error: {}", msg),
            NotifyError::QueueOverflow => "Event queue overflow".into(),
            NotifyError::NoEvents => "No events available".into(),
            NotifyError::Timeout => "Timeout waiting for events".into(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn test_event_type_mask() {
        assert_eq!(EventType::Create.mask(), 0x00000001);
        assert_eq!(EventType::Modify.mask(), 0x00000002);
        assert_eq!(EventType::Delete.mask(), 0x00000004);
    }

    #[test]
    fn test_event_type_round_trip() {
        for event in EventType::all() {
            let s = event.as_str();
            let parsed = EventType::from_str(s).unwrap();
            assert_eq!(*event, parsed);
        }
    }

    #[test]
    fn test_event_mask_from_events() {
        let mask = EventMask::from_events(&[EventType::Create, EventType::Delete]);
        assert!(mask.contains(EventType::Create));
        assert!(mask.contains(EventType::Delete));
        assert!(!mask.contains(EventType::Modify));
    }

    #[test]
    fn test_event_mask_add_remove() {
        let mut mask = EventMask::NONE;
        assert!(mask.is_empty());

        mask.add(EventType::Create);
        assert!(mask.contains(EventType::Create));

        mask.add(EventType::Delete);
        assert!(mask.contains(EventType::Delete));

        mask.remove(EventType::Create);
        assert!(!mask.contains(EventType::Create));
        assert!(mask.contains(EventType::Delete));
    }

    #[test]
    fn test_event_mask_bitwise() {
        let mask1 = EventMask::from_events(&[EventType::Create]);
        let mask2 = EventMask::from_events(&[EventType::Delete]);

        let combined = mask1 | mask2;
        assert!(combined.contains(EventType::Create));
        assert!(combined.contains(EventType::Delete));

        let intersect = combined & mask1;
        assert!(intersect.contains(EventType::Create));
        assert!(!intersect.contains(EventType::Delete));
    }

    #[test]
    fn test_fs_event_builder() {
        let event = FsEvent::new(EventType::Create, "tank/data", "/path/to/file.txt")
            .with_object_id(12345)
            .with_timestamp(1000000)
            .with_txg(100)
            .with_size(1024)
            .with_pid(42);

        assert_eq!(event.event_type, EventType::Create);
        assert_eq!(event.dataset, "tank/data");
        assert_eq!(event.path, "/path/to/file.txt");
        assert_eq!(event.object_id, 12345);
        assert_eq!(event.timestamp, 1000000);
        assert_eq!(event.txg, 100);
        assert_eq!(event.size, Some(1024));
        assert_eq!(event.pid, Some(42));
    }

    #[test]
    fn test_fs_event_rename() {
        let event = FsEvent::new(EventType::Rename, "tank/data", "/new/path.txt")
            .with_old_path("/old/path.txt");

        assert!(event.is_rename());
        assert_eq!(event.old_path, Some("/old/path.txt".into()));
    }

    #[test]
    fn test_fs_event_filename_parent() {
        let event = FsEvent::new(EventType::Create, "tank", "/path/to/file.txt");
        assert_eq!(event.filename(), "file.txt");
        assert_eq!(event.parent(), "/path/to");

        let event2 = FsEvent::new(EventType::Create, "tank", "/file.txt");
        assert_eq!(event2.filename(), "file.txt");
        assert_eq!(event2.parent(), "/");
    }

    #[test]
    fn test_watch_descriptor() {
        let wd = WatchDescriptor::new(42);
        assert_eq!(wd.id(), 42);
    }

    #[test]
    fn test_watch_options_default() {
        let opts = WatchOptions::default();
        assert!(!opts.recursive);
        assert!(!opts.oneshot);
        assert_eq!(opts.debounce_ms, 0);
    }

    #[test]
    fn test_watch_options_recursive() {
        let opts = WatchOptions::recursive();
        assert!(opts.recursive);
    }

    #[test]
    fn test_notify_error_message() {
        let err = NotifyError::WatchNotFound(42);
        assert!(err.message().contains("42"));

        let err = NotifyError::PathNotFound("/missing".into());
        assert!(err.message().contains("/missing"));
    }
}