ed_journals/modules/logs/blocking/
live_log_file_reader.rsuse std::io;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use thiserror::Error;
use crate::logs::content::LogEvent;
use crate::modules::logs::blocking::{LogFileReader, LogFileReaderError};
use crate::modules::shared::blocking::sync_blocker::SyncBlocker;
#[derive(Debug)]
pub struct LiveLogFileReader {
blocker: SyncBlocker,
log_file_reader: LogFileReader,
_watcher: RecommendedWatcher,
active: Arc<AtomicBool>,
}
#[derive(Debug, Error)]
pub enum LiveLogFileReaderError {
#[error(transparent)]
IO(#[from] io::Error),
#[error(transparent)]
NotifyError(#[from] notify::Error),
#[error(transparent)]
LogFileReaderError(#[from] LogFileReaderError),
}
impl LiveLogFileReader {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, LiveLogFileReaderError> {
let journal_file_reader = LogFileReader::open(&path)?;
let blocker = SyncBlocker::new();
let local_blocker = blocker.clone();
let mut watcher = notify::recommended_watcher(move |_| {
local_blocker.unblock();
})?;
watcher.watch(path.as_ref(), RecursiveMode::NonRecursive)?;
Ok(LiveLogFileReader {
blocker,
log_file_reader: journal_file_reader,
_watcher: watcher,
active: Arc::new(AtomicBool::new(true)),
})
}
pub fn handle(&self) -> LiveLogFileHandle {
LiveLogFileHandle {
active: self.active.clone(),
blocker: self.blocker.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct LiveLogFileHandle {
active: Arc<AtomicBool>,
blocker: SyncBlocker,
}
impl LiveLogFileHandle {
pub fn stop(&self) {
self.active.swap(false, Ordering::Relaxed);
self.blocker.unblock();
}
}
impl Iterator for LiveLogFileReader {
type Item = Result<LogEvent, LogFileReaderError>;
fn next(&mut self) -> Option<Self::Item> {
loop {
if !self.active.load(Ordering::Relaxed) {
return None;
}
match self.log_file_reader.next() {
Some(value) => return Some(value),
None => self.blocker.block(),
}
}
}
}