adk_agent/ambient/
file_watch_trigger.rs1use 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
12pub struct FileWatchTrigger {
24 path: PathBuf,
25 pattern: String,
26 name: String,
27}
28
29impl FileWatchTrigger {
30 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 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 Self::glob_match(pattern, file_name)
57 }
58
59 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 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 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 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 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 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 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 principal: None,
173 };
174 }
175 }
176 }
177 };
178
179 Ok(Box::pin(stream))
180 }
181}
182
183struct 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}