Skip to main content

fetchium_core/monitor/
mod.rs

1//! Change detection and URL monitoring engine (Phase 5, PRD §10, Mode G).
2//!
3//! ## Commands
4//! ```bash
5//! fetchium monitor <url>                     # one-shot check for changes
6//! fetchium monitor <url> --diff              # show diff since last snapshot
7//! fetchium monitor <url> --interval 1h       # register for periodic polling
8//! fetchium monitor list                      # list all monitored URLs
9//! fetchium monitor remove <url>              # stop monitoring
10//! ```
11
12pub mod diff;
13pub mod snapshot;
14
15pub use diff::{compute_diff, compute_diff_summary, ContentDiff, DiffLine};
16pub use snapshot::{MonitorEntry, Snapshot, SnapshotStore};
17
18use serde::{Deserialize, Serialize};
19
20/// Result of a monitor check.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct MonitorResult {
23    /// The URL that was checked.
24    pub url: String,
25    /// Whether content changed since last check.
26    pub changed: bool,
27    /// Diff details (only populated when `changed = true`).
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub diff: Option<ContentDiff>,
30    /// When this check was performed.
31    pub checked_at: String,
32}
33
34/// Parse a human-readable interval string to seconds.
35///
36/// Supported units: `s`, `m`, `h`, `d`.
37/// Examples: `"30s"`, `"5m"`, `"1h"`, `"7d"`.
38pub fn parse_interval(s: &str) -> Option<u64> {
39    let s = s.trim();
40    if s.is_empty() {
41        return None;
42    }
43    let (num_part, unit) = s.split_at(s.len().saturating_sub(1));
44    let (digits, unit) = match unit {
45        "s" | "m" | "h" | "d" => (num_part, unit),
46        c if c.chars().all(|x| x.is_ascii_digit()) => (s, "s"), // bare number = seconds
47        _ => return None,
48    };
49    let n: u64 = digits.parse().ok()?;
50    let secs = match unit {
51        "s" => n,
52        "m" => n * 60,
53        "h" => n * 3600,
54        "d" => n * 86400,
55        _ => return None,
56    };
57    Some(secs)
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn parse_interval_seconds() {
66        assert_eq!(parse_interval("30s"), Some(30));
67    }
68
69    #[test]
70    fn parse_interval_minutes() {
71        assert_eq!(parse_interval("5m"), Some(300));
72    }
73
74    #[test]
75    fn parse_interval_hours() {
76        assert_eq!(parse_interval("1h"), Some(3600));
77    }
78
79    #[test]
80    fn parse_interval_days() {
81        assert_eq!(parse_interval("7d"), Some(7 * 86400));
82    }
83
84    #[test]
85    fn parse_interval_bare_number() {
86        assert_eq!(parse_interval("120"), Some(120));
87    }
88
89    #[test]
90    fn parse_interval_invalid() {
91        assert_eq!(parse_interval("abc"), None);
92        assert_eq!(parse_interval(""), None);
93    }
94}