async-log-watch 0.2.0

A simple Rust library to monitor log files and trigger an async callback when a new line is added.
Documentation
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
use async_std::{fs::File, io::BufReader, prelude::*, sync::Mutex, task};

use notify::event::{DataChange, ModifyKind};
use notify::{event::EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use regex::RegexSet;
use shellexpand::tilde;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::{mpsc::channel, Arc};

//==== Errors

#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
    #[error("failed to open file - {0}")]
    FileOpenError(std::io::Error),
    #[error("failed to seek file - {0}")]
    FileSeekError(std::io::Error),
}

#[derive(Debug)]
pub struct LogError {
    pub kind: ErrorKind,
    // pub path: String,
}

impl LogError {
    // Display the error message
    pub fn display_error(&self) -> String {
        match &self.kind {
            ErrorKind::FileOpenError(err) => {
                // format!("{:?} - {}", err, self.path)
                format!("{:?}", err)
            }
            ErrorKind::FileSeekError(err) => {
                // format!("{:?} - {}", err, self.path)
                format!("{:?}", err)
            }
        }
    }
}

impl std::fmt::Display for LogError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.display_error())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("event error - {0}")]
    EventError(notify::Error),
    #[error("failed to receive data - {0}")]
    RecvError(std::sync::mpsc::RecvError),
}

//==== Events
pub struct LogEvent {
    line: Option<String>,
    log_error: Option<LogError>,
    path: String,
    // log_watcher: Arc<Mutex<LogWatcher>>,
}

impl LogEvent {
    fn new(
        path: String,
        line: Option<String>,
        error: Option<LogError>, /*, log_watcher:Arc<Mutex<LogWatcher>>*/
    ) -> Self {
        Self {
            path,
            line,
            log_error: error,
            // log_watcher
        }
    }

    // pub async fn change_file_path(&self, new_path: &str) -> Result<(), Error>{
    //     self.log_watcher.lock().await.change_file_path(&self.path, new_path).await
    // }
    //
    // pub async fn stop_monitoring_file(&self) -> Result<(), Error>{
    //     self.log_watcher.lock().await.stop_monitoring_file(&self.path).await
    // }
    pub fn file_path(&self) -> &str {
        self.path.as_str()
    }

    pub fn get_line(&self) -> Option<&String> {
        self.line.as_ref()
    }

    pub fn get_log_error(&self) -> Option<&LogError> {
        self.log_error.as_ref()
    }
}

//==== Callback

pub type LogCallback =
    Arc<dyn Fn(LogEvent) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> + Send + Sync>;

pub struct LogWatcher {
    log_callbacks: Arc<Mutex<HashMap<String, (LogCallback, Option<RegexSet>)>>>,
    watcher: Arc<Mutex<Option<RecommendedWatcher>>>,
}

impl LogWatcher {
    pub fn new() -> Self {
        Self {
            log_callbacks: Arc::new(Mutex::new(HashMap::new())),
            watcher: Arc::new(Mutex::new(None)),
        }
    }

    pub async fn change_file_path(&mut self, old_path: &str, new_path: &str) -> Result<(), Error> {
        // change into absolute path
        let old_path = self.make_absolute_path(&Path::new(old_path));
        let old_path = old_path.into_os_string().into_string().unwrap();

        let callback = self.log_callbacks.lock().await.remove(&old_path);
        if let Some(callback) = callback {
            self.log_callbacks
                .lock()
                .await
                .insert(new_path.to_owned(), callback);
            let mut watcher = self.watcher.lock().await;
            if let Some(watcher) = &mut *watcher {
                watcher
                    .unwatch(Path::new(&old_path))
                    .map_err(|e| Error::EventError(e))?;
                watcher
                    .watch(Path::new(new_path), RecursiveMode::NonRecursive)
                    .map_err(|e| Error::EventError(e))?;
            }
        }
        Ok(())
    }

    pub async fn stop_monitoring_file(&mut self, path: &str) -> Result<(), Error> {
        // change into absolute path
        let path = self.make_absolute_path(&Path::new(path));
        let path = path.into_os_string().into_string().unwrap();

        self.log_callbacks.lock().await.remove(&path);
        let mut watcher = self.watcher.lock().await;
        if let Some(watcher) = &mut *watcher {
            watcher
                .unwatch(Path::new(&path))
                .map_err(|e| Error::EventError(e))?;
        }
        Ok(())
    }

    // helper function to convert a relative path into an absolute path
    fn make_absolute_path(&self, path: &Path) -> PathBuf {
        let expanded_path = tilde(&path.to_string_lossy()).into_owned();
        let expanded_path = Path::new(&expanded_path);

        if expanded_path.is_absolute() {
            expanded_path.to_path_buf()
        } else {
            std::env::current_dir().unwrap().join(expanded_path)
        }
    }

    // register a file path and its associated callback function.
    pub async fn register<P: AsRef<Path>, F, Fut>(
        &mut self,
        path: P,
        callback: F,
        patterns: Option<Vec<&str>>,
    ) where
        F: Fn(LogEvent) -> Fut + Send + Sync + 'static,
        Fut: std::future::Future<Output = ()> + Send + Sync + 'static,
    {
        let path = self.make_absolute_path(path.as_ref());
        let path = path.into_os_string().into_string().unwrap();

        let callback = Arc::new(
            move |log_event: LogEvent| -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
                Box::pin(callback(log_event))
            },
        );
        let regex_set = if let Some(patterns) = patterns {
            Some(RegexSet::new(patterns).unwrap())
        } else {
            None
        };
        self.log_callbacks
            .lock()
            .await
            .insert(path, (callback, regex_set));
    }

    // Start monitoring
    pub async fn monitoring(&self, poll_interval: std::time::Duration) -> Result<(), Error> {
        let (tx, rx) = channel();

        let config = notify::Config::default().with_poll_interval(poll_interval);

        let watcher: RecommendedWatcher = Watcher::new(tx, config).unwrap();
        *self.watcher.lock().await = Some(watcher);

        for path in self.log_callbacks.lock().await.keys() {
            self.watcher
                .lock()
                .await
                .as_mut()
                .unwrap()
                .watch(Path::new(&path), RecursiveMode::NonRecursive)
                .map_err(|e| Error::EventError(e))?;
        }

        let file_positions = Arc::new(Mutex::new(HashMap::<String, u64>::new()));
        loop {
            match rx.recv() {
                Ok(event) => match event {
                    Ok(event) => match event.kind {
                        EventKind::Modify(ModifyKind::Data(DataChange::Any)) => {
                            let paths = &event.paths;
                            for path in paths {
                                let path_str = path.clone().into_os_string().into_string().unwrap();

                                // clone the contianers
                                let log_callbacks = Arc::clone(&self.log_callbacks);
                                let file_positions_clone = Arc::clone(&file_positions);

                                task::spawn(async move {
                                    // to avoid the deadlock
                                    let log_callbacks = log_callbacks.lock().await;

                                    if let Some((callback, regex_set)) =
                                        log_callbacks.get(&path_str)
                                    {
                                        let callback = Arc::clone(callback);

                                        let mut file_positions = file_positions_clone.lock().await;
                                        let position = file_positions
                                            .entry(path_str.clone())
                                            .or_insert(std::u64::MAX);

                                        // file open
                                        match File::open(&path_str).await {
                                            Ok(file) => {
                                                let mut reader = BufReader::new(file);
                                                let mut line = String::new();

                                                // need to set initial position
                                                if *position == std::u64::MAX {
                                                    *position = find_last_line(&mut reader).await;
                                                }

                                                // seek from *position
                                                match reader
                                                    .seek(std::io::SeekFrom::Start(*position))
                                                    .await
                                                {
                                                    Ok(_) => {
                                                        // check if a full line has been read
                                                        if reader
                                                            .read_line(&mut line)
                                                            .await
                                                            .unwrap()
                                                            > 0
                                                            && line.ends_with('\n')
                                                        {
                                                            *position += line.len() as u64;

                                                            // remove trailing newline character, if present
                                                            // use the trim_end_matches
                                                            let line = line
                                                                .trim_end_matches(|c| {
                                                                    c == '\n' || c == '\r'
                                                                })
                                                                .to_owned();

                                                            let notify = if let Some(regex_set) =
                                                                regex_set
                                                            {
                                                                if regex_set.is_match(&line) {
                                                                    true
                                                                } else {
                                                                    false
                                                                }
                                                            } else {
                                                                true
                                                            };

                                                            if notify {
                                                                let event = LogEvent::new(
                                                                    path_str,
                                                                    Some(line),
                                                                    None,
                                                                );
                                                                callback(event).await;
                                                            }
                                                        }
                                                    }
                                                    Err(e) => {
                                                        let log_error = LogError {
                                                            kind: ErrorKind::FileSeekError(e),
                                                        };
                                                        let event = LogEvent::new(
                                                            path_str,
                                                            None,
                                                            Some(log_error),
                                                        );
                                                        callback(event).await;
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                let log_error = LogError {
                                                    kind: ErrorKind::FileOpenError(e),
                                                };
                                                let event =
                                                    LogEvent::new(path_str, None, Some(log_error));
                                                callback(event).await;
                                            }
                                        }
                                    }
                                });
                            }
                        }
                        _ => {}
                    },
                    Err(e) => return Err(Error::EventError(e)),
                },
                Err(e) => return Err(Error::RecvError(e)),
            }
        }
    }
}

// find the position of last line.
async fn find_last_line(reader: &mut BufReader<File>) -> u64 {
    let mut last_line_start = 0;
    let mut last_line = String::new();
    let mut current_position = 0;

    while let Ok(len) = reader.read_line(&mut last_line).await {
        if len == 0 || !last_line.ends_with('\n') {
            break;
        }
        last_line_start = current_position;
        current_position += len as u64;
        last_line.clear();
    }

    last_line_start
}
#[cfg(test)]
mod tests {

    use super::find_last_line;
    use async_std::{fs::remove_file, fs::File, io::BufReader, prelude::*};

    #[async_std::test]
    async fn test_find_last_line() {
        //
        let filepath = "test-log.txt";

        let _ = remove_file(filepath);

        let mut file = File::create(filepath).await.unwrap();

        file.write_all(b"0\n").await.unwrap();
        file.write_all(b"1\n").await.unwrap();
        file.write_all(b"2\n").await.unwrap();
        file.write_all(b"3\n").await.unwrap();
        file.flush().await.unwrap();

        let ofile = File::open(&filepath).await.unwrap();
        let mut reader = BufReader::new(ofile);
        let position = find_last_line(&mut reader).await;

        // assert last line position
        assert_eq!(position, 6);

        let mut line = String::new();
        reader
            .seek(std::io::SeekFrom::Start(position))
            .await
            .unwrap();
        reader.read_line(&mut line).await.unwrap();
        // assert last line
        assert_eq!(line, "3\n");

        let _ = remove_file(filepath).await; // Remove the file if it exists
    }

    #[async_std::test]
    async fn test_log_watcher() {
        let mut log_watcher = super::LogWatcher::new();

        let log_file_1 = "test-log1.txt";
        let log_file_2 = "test-log2.txt";
        let log_file_3 = "test-log3.txt";

        // create log files
        let mut file_1 = File::create(log_file_1).await.unwrap();
        let mut file_2 = File::create(log_file_2).await.unwrap();
        let mut file_3 = File::create(log_file_3).await.unwrap();

        log_watcher.register(log_file_1, |_| async {}, None).await;
        log_watcher.register(log_file_2, |_| async {}, None).await;

        // write data to log files
        file_1.write_all(b"line 1\n").await.unwrap();
        file_1.sync_all().await.unwrap();
        file_2.write_all(b"line 2\n").await.unwrap();
        file_2.sync_all().await.unwrap();

        // stop monitoring log_file_1
        log_watcher.stop_monitoring_file(log_file_1).await.unwrap();
        // change the path of log_file_2 to log_file_3
        log_watcher
            .change_file_path(log_file_2, log_file_3)
            .await
            .unwrap();

        // write data to log files
        file_1.write_all(b"line 3\n").await.unwrap();
        file_1.sync_all().await.unwrap();
        file_3.write_all(b"line 4\n").await.unwrap();
        file_3.sync_all().await.unwrap();

        assert!(!log_watcher
            .log_callbacks
            .lock()
            .await
            .contains_key(log_file_1));
        assert!(!log_watcher
            .log_callbacks
            .lock()
            .await
            .contains_key(log_file_2));
        assert!(log_watcher
            .log_callbacks
            .lock()
            .await
            .contains_key(log_file_3));

        // remove the test log files
        remove_file(log_file_1).await.unwrap();
        remove_file(log_file_2).await.unwrap();
        remove_file(log_file_3).await.unwrap();
    }
}