Skip to main content

tale_ndjson/multiplexed/
watcher.rs

1//! Multi-file watching using notify.
2//!
3//! This module handles file system event monitoring for multiple files,
4//! coordinating with the file state manager and batch processor.
5
6use std::path::{Path, PathBuf};
7
8use miette::Result;
9use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
10use tokio::sync::mpsc;
11use tokio::task::JoinHandle;
12
13use super::file_state::FileStateManager;
14use crate::errors::*;
15
16/// Events that can occur during file watching
17#[derive(Debug, Clone)]
18pub enum WatchEvent {
19    /// A file was modified (new content available)
20    FileModified(PathBuf),
21    /// A file was created
22    FileCreated(PathBuf),
23    /// A file was deleted
24    FileDeleted(PathBuf),
25    /// A file was moved/renamed
26    FileMoved { from: PathBuf, to: PathBuf },
27    /// An error occurred while watching
28    Error(String),
29}
30
31/// Multi-file watcher using notify and async coordination.
32///
33/// `_watcher` and `_task_handle` are RAII guards: dropping the
34/// `MultiFileWatcher` stops the underlying notify watcher and joins the
35/// event-processing task. They're never read directly; the underscore prefix
36/// signals "kept alive on purpose".
37pub struct MultiFileWatcher {
38    file_manager: FileStateManager,
39    _watcher: Option<RecommendedWatcher>,
40    _task_handle: Option<JoinHandle<()>>,
41}
42
43impl MultiFileWatcher {
44    /// Create a new MultiFileWatcher
45    pub fn new() -> Self {
46        Self {
47            file_manager: FileStateManager::new(),
48            _watcher: None,
49            _task_handle: None,
50        }
51    }
52
53    /// Add files to be watched
54    pub async fn add_files<I, P>(&mut self, paths: I) -> Result<(), TaleError>
55    where
56        I: IntoIterator<Item = P>,
57        P: AsRef<Path>,
58    {
59        for path in paths {
60            self.file_manager.add_file_for_tailing(path)?;
61        }
62
63        Ok(())
64    }
65
66    /// Start watching files and return a stream of events
67    pub async fn watch(&mut self) -> Result<mpsc::UnboundedReceiver<WatchEvent>, TaleError> {
68        let (event_sender, event_receiver) = mpsc::unbounded_channel();
69
70        // Create a channel for notify events
71        let (notify_sender, notify_receiver) = std::sync::mpsc::channel();
72
73        // Create the notify watcher
74        let mut watcher = notify::recommended_watcher(move |result: notify::Result<Event>| {
75            if let Err(e) = notify_sender.send(result) {
76                eprintln!("Failed to send notify event: {e}");
77            }
78        })?;
79
80        // Watch all tracked files
81        for file_path in self.file_manager.tracked_files() {
82            watcher
83                .watch(file_path, RecursiveMode::NonRecursive)
84                .map_err(TaleError::NotifyError)?;
85        }
86
87        // Spawn a task to process notify events and convert them to WatchEvents
88        let task_handle = tokio::spawn(async move {
89            while let Ok(result) = notify_receiver.recv() {
90                match result {
91                    Ok(event) => {
92                        if let Some(watch_event) = Self::convert_notify_event(event)
93                            && event_sender.send(watch_event).is_err()
94                        {
95                            break; // Receiver dropped
96                        }
97                    }
98                    Err(e) => {
99                        let error_event = WatchEvent::Error(format!("Notify error: {e}"));
100                        if event_sender.send(error_event).is_err() {
101                            break; // Receiver dropped
102                        }
103                    }
104                }
105            }
106        });
107
108        self._watcher = Some(watcher);
109        self._task_handle = Some(task_handle);
110
111        Ok(event_receiver)
112    }
113
114    /// Convert a notify Event to our WatchEvent
115    fn convert_notify_event(event: Event) -> Option<WatchEvent> {
116        match event.kind {
117            EventKind::Modify(_) => event.paths.first().map(|path| WatchEvent::FileModified(path.clone())),
118            EventKind::Create(_) => event.paths.first().map(|path| WatchEvent::FileCreated(path.clone())),
119            EventKind::Remove(_) => event.paths.first().map(|path| WatchEvent::FileDeleted(path.clone())),
120            _ => None,
121        }
122    }
123
124    /// Get mutable access to the file state manager
125    pub fn file_manager_mut(&mut self) -> &mut FileStateManager {
126        &mut self.file_manager
127    }
128}
129
130impl Default for MultiFileWatcher {
131    fn default() -> Self {
132        Self::new()
133    }
134}
135
136/// Create a new multi-file watcher with default configuration
137pub fn create_watcher() -> MultiFileWatcher {
138    MultiFileWatcher::new()
139}