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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Watch management for filesystem events.
//!
//! This module handles the registration and management of filesystem watches.

use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use lazy_static::lazy_static;
use spin::Mutex;

use super::types::{EventMask, EventType, FsEvent, NotifyError, WatchDescriptor, WatchOptions};

// ═══════════════════════════════════════════════════════════════════════════════
// WATCH CALLBACK
// ═══════════════════════════════════════════════════════════════════════════════

/// Callback function type for watch events.
pub type WatchCallback = Box<dyn Fn(&FsEvent) + Send + Sync>;

// ═══════════════════════════════════════════════════════════════════════════════
// WATCH
// ═══════════════════════════════════════════════════════════════════════════════

/// A registered watch on a path.
pub struct Watch {
    /// Watch descriptor
    pub descriptor: WatchDescriptor,
    /// Dataset being watched
    pub dataset: String,
    /// Path being watched
    pub path: String,
    /// Event mask (which events to watch)
    pub mask: EventMask,
    /// Watch options
    pub options: WatchOptions,
    /// Callback function
    callback: Option<WatchCallback>,
    /// Number of events received
    pub event_count: u64,
    /// Whether watch is active
    pub active: bool,
}

impl Watch {
    /// Create a new watch.
    pub fn new(
        descriptor: WatchDescriptor,
        dataset: &str,
        path: &str,
        mask: EventMask,
        options: WatchOptions,
    ) -> Self {
        Self {
            descriptor,
            dataset: dataset.into(),
            path: path.into(),
            mask,
            options,
            callback: None,
            event_count: 0,
            active: true,
        }
    }

    /// Set the callback function.
    pub fn with_callback(mut self, callback: WatchCallback) -> Self {
        self.callback = Some(callback);
        self
    }

    /// Check if this watch matches an event.
    pub fn matches(&self, event: &FsEvent) -> bool {
        if !self.active {
            return false;
        }

        // Check dataset
        if self.dataset != event.dataset {
            return false;
        }

        // Check event type mask
        if !self.mask.contains(event.event_type) {
            return false;
        }

        // Check path
        if self.options.recursive {
            // For recursive watches, path must be under watched path
            event.path.starts_with(&self.path)
                || event.path == self.path
                || (event.path.starts_with(&self.path)
                    && event.path.as_bytes().get(self.path.len()) == Some(&b'/'))
        } else {
            // For non-recursive, path must be exact or immediate child
            if event.path == self.path {
                !self.options.exclude_self
            } else if let Some(parent) = event.path.rsplit_once('/') {
                parent.0 == self.path
            } else {
                false
            }
        }
    }

    /// Invoke the callback with an event.
    pub fn invoke(&mut self, event: &FsEvent) {
        if let Some(ref callback) = self.callback {
            callback(event);
        }
        self.event_count += 1;

        // Handle oneshot
        if self.options.oneshot {
            self.active = false;
        }
    }

    /// Deactivate the watch.
    pub fn deactivate(&mut self) {
        self.active = false;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// WATCH REGISTRY
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global registry of watches.
    static ref WATCHES: Mutex<WatchRegistry> = Mutex::new(WatchRegistry::new());
}

/// Registry of all active watches.
pub struct WatchRegistry {
    /// Watches by descriptor ID
    watches: BTreeMap<u64, Watch>,
    /// Next descriptor ID
    next_id: u64,
    /// Maximum number of watches allowed
    max_watches: usize,
}

impl WatchRegistry {
    /// Create a new watch registry.
    pub fn new() -> Self {
        Self {
            watches: BTreeMap::new(),
            next_id: 1,
            max_watches: 65536, // 64K watches default
        }
    }

    /// Set the maximum number of watches.
    pub fn set_max_watches(&mut self, max: usize) {
        self.max_watches = max;
    }

    /// Add a new watch.
    pub fn add(
        &mut self,
        dataset: &str,
        path: &str,
        mask: EventMask,
        options: WatchOptions,
        callback: Option<WatchCallback>,
    ) -> Result<WatchDescriptor, NotifyError> {
        if self.watches.len() >= self.max_watches {
            return Err(NotifyError::TooManyWatches);
        }

        let id = self.next_id;
        self.next_id += 1;

        let descriptor = WatchDescriptor::new(id);
        let mut watch = Watch::new(descriptor, dataset, path, mask, options);
        if let Some(cb) = callback {
            watch = watch.with_callback(cb);
        }

        self.watches.insert(id, watch);

        Ok(descriptor)
    }

    /// Remove a watch.
    pub fn remove(&mut self, descriptor: WatchDescriptor) -> Result<(), NotifyError> {
        if self.watches.remove(&descriptor.id()).is_none() {
            return Err(NotifyError::WatchNotFound(descriptor.id()));
        }
        Ok(())
    }

    /// Get a watch by descriptor.
    pub fn get(&self, descriptor: WatchDescriptor) -> Option<&Watch> {
        self.watches.get(&descriptor.id())
    }

    /// Get a mutable watch by descriptor.
    pub fn get_mut(&mut self, descriptor: WatchDescriptor) -> Option<&mut Watch> {
        self.watches.get_mut(&descriptor.id())
    }

    /// Find all watches that match an event.
    pub fn matching_watches(&self, event: &FsEvent) -> Vec<WatchDescriptor> {
        self.watches
            .values()
            .filter(|w| w.matches(event))
            .map(|w| w.descriptor)
            .collect()
    }

    /// Get the number of watches.
    pub fn count(&self) -> usize {
        self.watches.len()
    }

    /// Get the number of active watches.
    pub fn active_count(&self) -> usize {
        self.watches.values().filter(|w| w.active).count()
    }

    /// List all watches for a dataset.
    pub fn list_by_dataset(&self, dataset: &str) -> Vec<WatchDescriptor> {
        self.watches
            .values()
            .filter(|w| w.dataset == dataset)
            .map(|w| w.descriptor)
            .collect()
    }

    /// Remove all watches for a dataset.
    pub fn remove_by_dataset(&mut self, dataset: &str) -> usize {
        let to_remove: Vec<u64> = self
            .watches
            .iter()
            .filter(|(_, w)| w.dataset == dataset)
            .map(|(id, _)| *id)
            .collect();

        let count = to_remove.len();
        for id in to_remove {
            self.watches.remove(&id);
        }
        count
    }

    /// Remove all inactive (oneshot triggered) watches.
    pub fn cleanup_inactive(&mut self) -> usize {
        let to_remove: Vec<u64> = self
            .watches
            .iter()
            .filter(|(_, w)| !w.active)
            .map(|(id, _)| *id)
            .collect();

        let count = to_remove.len();
        for id in to_remove {
            self.watches.remove(&id);
        }
        count
    }

    /// Clear all watches.
    pub fn clear(&mut self) {
        self.watches.clear();
    }
}

impl Default for WatchRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PUBLIC API
// ═══════════════════════════════════════════════════════════════════════════════

/// Add a watch on a path.
///
/// # Arguments
/// * `dataset` - Dataset to watch
/// * `path` - Path within dataset
/// * `mask` - Event types to watch
/// * `options` - Watch options
/// * `callback` - Optional callback function
///
/// # Returns
/// Watch descriptor on success.
pub fn add_watch(
    dataset: &str,
    path: &str,
    mask: EventMask,
    options: WatchOptions,
    callback: Option<WatchCallback>,
) -> Result<WatchDescriptor, NotifyError> {
    let mut registry = WATCHES.lock();
    registry.add(dataset, path, mask, options, callback)
}

/// Add a simple watch with default options.
pub fn watch(
    dataset: &str,
    path: &str,
    events: &[EventType],
    callback: WatchCallback,
) -> Result<WatchDescriptor, NotifyError> {
    let mask = EventMask::from_events(events);
    add_watch(dataset, path, mask, WatchOptions::default(), Some(callback))
}

/// Add a recursive watch.
pub fn watch_recursive(
    dataset: &str,
    path: &str,
    events: &[EventType],
    callback: WatchCallback,
) -> Result<WatchDescriptor, NotifyError> {
    let mask = EventMask::from_events(events);
    add_watch(
        dataset,
        path,
        mask,
        WatchOptions::recursive(),
        Some(callback),
    )
}

/// Remove a watch.
pub fn remove_watch(descriptor: WatchDescriptor) -> Result<(), NotifyError> {
    let mut registry = WATCHES.lock();
    registry.remove(descriptor)
}

/// Get watch information.
pub fn get_watch_info(descriptor: WatchDescriptor) -> Option<WatchInfo> {
    let registry = WATCHES.lock();
    registry.get(descriptor).map(|w| WatchInfo {
        descriptor: w.descriptor,
        dataset: w.dataset.clone(),
        path: w.path.clone(),
        mask: w.mask,
        recursive: w.options.recursive,
        active: w.active,
        event_count: w.event_count,
    })
}

/// Get the number of active watches.
pub fn watch_count() -> usize {
    let registry = WATCHES.lock();
    registry.count()
}

/// Information about a watch (for querying).
#[derive(Debug, Clone)]
pub struct WatchInfo {
    /// Watch descriptor
    pub descriptor: WatchDescriptor,
    /// Dataset being watched
    pub dataset: String,
    /// Path being watched
    pub path: String,
    /// Event mask
    pub mask: EventMask,
    /// Whether recursive
    pub recursive: bool,
    /// Whether active
    pub active: bool,
    /// Number of events received
    pub event_count: u64,
}

/// Dispatch an event to matching watches.
///
/// This is called by the event emission system.
pub(crate) fn dispatch_to_watches(event: &FsEvent) {
    let mut registry = WATCHES.lock();

    // Find matching watches first to avoid borrow issues
    let matching: Vec<u64> = registry
        .watches
        .iter()
        .filter(|(_, w)| w.matches(event))
        .map(|(id, _)| *id)
        .collect();

    // Invoke callbacks
    for id in matching {
        if let Some(watch) = registry.watches.get_mut(&id) {
            watch.invoke(event);
        }
    }

    // Cleanup inactive oneshot watches
    registry.cleanup_inactive();
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::sync::Arc;
    use core::sync::atomic::{AtomicU64, Ordering};

    #[test]
    fn test_watch_matches_exact() {
        let watch = Watch::new(
            WatchDescriptor::new(1),
            "tank/data",
            "/path/to",
            EventMask::ALL,
            WatchOptions::default(),
        );

        // Immediate child should match
        let event = FsEvent::new(EventType::Create, "tank/data", "/path/to/file.txt");
        assert!(watch.matches(&event));

        // Exact path should match (if not exclude_self)
        let event = FsEvent::new(EventType::Create, "tank/data", "/path/to");
        assert!(watch.matches(&event));

        // Wrong dataset
        let event = FsEvent::new(EventType::Create, "other/pool", "/path/to/file.txt");
        assert!(!watch.matches(&event));

        // Deeper path without recursive
        let event = FsEvent::new(EventType::Create, "tank/data", "/path/to/sub/file.txt");
        assert!(!watch.matches(&event));
    }

    #[test]
    fn test_watch_matches_recursive() {
        let watch = Watch::new(
            WatchDescriptor::new(1),
            "tank/data",
            "/path/to",
            EventMask::ALL,
            WatchOptions::recursive(),
        );

        // Should match deep paths
        let event = FsEvent::new(EventType::Create, "tank/data", "/path/to/sub/deep/file.txt");
        assert!(watch.matches(&event));
    }

    #[test]
    fn test_watch_mask_filter() {
        let watch = Watch::new(
            WatchDescriptor::new(1),
            "tank",
            "/path",
            EventMask::from_events(&[EventType::Create, EventType::Delete]),
            WatchOptions::default(),
        );

        let create = FsEvent::new(EventType::Create, "tank", "/path/file.txt");
        assert!(watch.matches(&create));

        let modify = FsEvent::new(EventType::Modify, "tank", "/path/file.txt");
        assert!(!watch.matches(&modify));
    }

    #[test]
    fn test_watch_oneshot() {
        let mut watch = Watch::new(
            WatchDescriptor::new(1),
            "tank",
            "/path",
            EventMask::ALL,
            WatchOptions::oneshot(),
        );

        let event = FsEvent::new(EventType::Create, "tank", "/path/file.txt");
        assert!(watch.matches(&event));

        watch.invoke(&event);
        assert!(!watch.active);
        assert!(!watch.matches(&event)); // Should not match after oneshot triggered
    }

    #[test]
    fn test_registry_add_remove() {
        let mut registry = WatchRegistry::new();

        let wd = registry
            .add(
                "tank",
                "/path",
                EventMask::ALL,
                WatchOptions::default(),
                None,
            )
            .unwrap();

        assert_eq!(registry.count(), 1);

        registry.remove(wd).unwrap();
        assert_eq!(registry.count(), 0);
    }

    #[test]
    fn test_registry_max_watches() {
        let mut registry = WatchRegistry::new();
        registry.set_max_watches(2);

        registry
            .add(
                "tank",
                "/path1",
                EventMask::ALL,
                WatchOptions::default(),
                None,
            )
            .unwrap();
        registry
            .add(
                "tank",
                "/path2",
                EventMask::ALL,
                WatchOptions::default(),
                None,
            )
            .unwrap();

        let result = registry.add(
            "tank",
            "/path3",
            EventMask::ALL,
            WatchOptions::default(),
            None,
        );
        assert!(matches!(result, Err(NotifyError::TooManyWatches)));
    }

    #[test]
    fn test_registry_matching_watches() {
        let mut registry = WatchRegistry::new();

        let wd1 = registry
            .add(
                "tank",
                "/path1",
                EventMask::from_events(&[EventType::Create]),
                WatchOptions::default(),
                None,
            )
            .unwrap();

        let wd2 = registry
            .add(
                "tank",
                "/path2",
                EventMask::from_events(&[EventType::Create]),
                WatchOptions::default(),
                None,
            )
            .unwrap();

        let event = FsEvent::new(EventType::Create, "tank", "/path1/file.txt");
        let matches = registry.matching_watches(&event);

        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0], wd1);
    }

    #[test]
    fn test_registry_remove_by_dataset() {
        let mut registry = WatchRegistry::new();

        registry
            .add(
                "tank",
                "/path1",
                EventMask::ALL,
                WatchOptions::default(),
                None,
            )
            .unwrap();
        registry
            .add(
                "tank",
                "/path2",
                EventMask::ALL,
                WatchOptions::default(),
                None,
            )
            .unwrap();
        registry
            .add(
                "other",
                "/path3",
                EventMask::ALL,
                WatchOptions::default(),
                None,
            )
            .unwrap();

        let removed = registry.remove_by_dataset("tank");
        assert_eq!(removed, 2);
        assert_eq!(registry.count(), 1);
    }

    #[test]
    fn test_watch_with_callback() {
        let counter = Arc::new(AtomicU64::new(0));
        let counter_clone = counter.clone();

        let callback: WatchCallback = Box::new(move |_event| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        let mut watch = Watch::new(
            WatchDescriptor::new(1),
            "tank",
            "/path",
            EventMask::ALL,
            WatchOptions::default(),
        )
        .with_callback(callback);

        let event = FsEvent::new(EventType::Create, "tank", "/path/file.txt");
        watch.invoke(&event);
        watch.invoke(&event);

        assert_eq!(counter.load(Ordering::SeqCst), 2);
        assert_eq!(watch.event_count, 2);
    }
}