Skip to main content

adk_agent/ambient/
file_watch_trigger.rs

1use std::path::PathBuf;
2use std::time::Duration;
3
4use adk_core::{AdkError, Result};
5use async_trait::async_trait;
6use futures::stream::BoxStream;
7use notify::{Config, Event as NotifyEvent, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
8use tokio::sync::mpsc;
9
10use super::event_source::{EventSource, TriggerEvent};
11
12/// Emits trigger events when files matching a glob pattern change.
13///
14/// Uses the `notify` crate for cross-platform filesystem watching.
15///
16/// # Example
17///
18/// ```rust,ignore
19/// use adk_agent::ambient::FileWatchTrigger;
20///
21/// let trigger = FileWatchTrigger::new("/path/to/watch", "*.json")?;
22/// ```
23pub struct FileWatchTrigger {
24    path: PathBuf,
25    pattern: String,
26    name: String,
27}
28
29impl FileWatchTrigger {
30    /// Create a file watch trigger for the given path and glob pattern.
31    ///
32    /// Returns an error if the path does not exist.
33    ///
34    /// # Errors
35    ///
36    /// Returns `AdkError::Agent` if the watch path does not exist on the filesystem.
37    pub fn new(path: impl Into<PathBuf>, pattern: &str) -> Result<Self> {
38        let path = path.into();
39
40        if !path.exists() {
41            return Err(AdkError::agent(format!("watch path not found: {}", path.display())));
42        }
43
44        Ok(Self {
45            name: format!("file_watch:{}", path.display()),
46            path,
47            pattern: pattern.to_string(),
48        })
49    }
50
51    /// Check if an event path matches the configured glob pattern.
52    fn matches_pattern(pattern: &str, event_path: &std::path::Path) -> bool {
53        let file_name = event_path.file_name().and_then(|n| n.to_str()).unwrap_or("");
54
55        // Simple glob matching: support * and ? patterns
56        Self::glob_match(pattern, file_name)
57    }
58
59    /// Simple glob pattern matching supporting `*` (any chars) and `?` (single char).
60    fn glob_match(pattern: &str, text: &str) -> bool {
61        let pattern_chars: Vec<char> = pattern.chars().collect();
62        let text_chars: Vec<char> = text.chars().collect();
63
64        Self::glob_match_recursive(&pattern_chars, &text_chars, 0, 0)
65    }
66
67    fn glob_match_recursive(pattern: &[char], text: &[char], pi: usize, ti: usize) -> bool {
68        if pi == pattern.len() && ti == text.len() {
69            return true;
70        }
71        if pi == pattern.len() {
72            return false;
73        }
74
75        match pattern[pi] {
76            '*' => {
77                // * matches zero or more characters
78                for i in ti..=text.len() {
79                    if Self::glob_match_recursive(pattern, text, pi + 1, i) {
80                        return true;
81                    }
82                }
83                false
84            }
85            '?' => {
86                // ? matches exactly one character
87                if ti < text.len() {
88                    Self::glob_match_recursive(pattern, text, pi + 1, ti + 1)
89                } else {
90                    false
91                }
92            }
93            c => {
94                if ti < text.len() && text[ti] == c {
95                    Self::glob_match_recursive(pattern, text, pi + 1, ti + 1)
96                } else {
97                    false
98                }
99            }
100        }
101    }
102}
103
104#[async_trait]
105impl EventSource for FileWatchTrigger {
106    fn name(&self) -> &str {
107        &self.name
108    }
109
110    /// Subscribes to changes under the watched path. The `notify` watcher lives on its own
111    /// thread for as long as the returned stream: dropping the stream stops the watcher and
112    /// ends the thread.
113    async fn subscribe(&self) -> Result<BoxStream<'static, TriggerEvent>> {
114        let source_name = self.name.clone();
115        let pattern = self.pattern.clone();
116        let watch_path = self.path.clone();
117
118        // `notify` calls back on its own thread; this bounded channel bridges to async.
119        let (sync_tx, sync_rx) = mpsc::channel::<NotifyEvent>(256);
120        let subscribed = sync_tx.clone();
121
122        let watcher_thread = std::thread::Builder::new()
123            .name("adk-file-watch".into())
124            .spawn(move || {
125                let mut watcher = match RecommendedWatcher::new(
126                    move |res: std::result::Result<NotifyEvent, notify::Error>| {
127                        if let Ok(event) = res {
128                            let _ = sync_tx.blocking_send(event);
129                        }
130                    },
131                    Config::default(),
132                ) {
133                    Ok(w) => w,
134                    Err(e) => {
135                        tracing::warn!("file watch trigger failed to create watcher: {e}");
136                        return;
137                    }
138                };
139
140                if let Err(e) = watcher.watch(&watch_path, RecursiveMode::Recursive) {
141                    tracing::warn!("file watch trigger failed to watch path: {e}");
142                    return;
143                }
144
145                // The watcher stops when it drops at the end of this closure, once the
146                // subscription closes the channel; `WatchSubscription` unparks the thread
147                // then, and the timeout only bounds a missed unpark.
148                while !subscribed.is_closed() {
149                    std::thread::park_timeout(Duration::from_secs(1));
150                }
151            })
152            .map_err(|e| AdkError::agent(format!("file watch trigger failed to start: {e}")))?;
153
154        let mut subscription =
155            WatchSubscription { events: sync_rx, watcher_thread: watcher_thread.thread().clone() };
156        let stream = async_stream::stream! {
157            while let Some(event) = subscription.events.recv().await {
158                // A read is not a change: inotify reports every open and close as `Access`.
159                if matches!(event.kind, EventKind::Access(_)) {
160                    continue;
161                }
162                let event_kind = format!("{:?}", event.kind);
163                for event_path in &event.paths {
164                    if FileWatchTrigger::matches_pattern(&pattern, event_path) {
165                        yield TriggerEvent {
166                            source: source_name.clone(),
167                            payload: serde_json::json!({
168                                "event": event_kind,
169                                "path": event_path.display().to_string(),
170                            }),
171                            // A filesystem change has no caller.
172                            principal: None,
173                        };
174                    }
175                }
176            }
177        };
178
179        Ok(Box::pin(stream))
180    }
181}
182
183/// The receiving end of one subscription. Dropping it closes the channel and wakes the
184/// watcher thread, which then drops the watcher and ends.
185struct WatchSubscription {
186    events: mpsc::Receiver<NotifyEvent>,
187    watcher_thread: std::thread::Thread,
188}
189
190impl Drop for WatchSubscription {
191    fn drop(&mut self) {
192        self.events.close();
193        self.watcher_thread.unpark();
194    }
195}
196
197impl std::fmt::Debug for FileWatchTrigger {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.debug_struct("FileWatchTrigger")
200            .field("path", &self.path)
201            .field("pattern", &self.pattern)
202            .finish()
203    }
204}