Skip to main content

watchbird_api/v1alpha1/
watch.rs

1use aide::OperationIo;
2use chrono::{DateTime, Utc};
3use chrono_tz::Tz;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize, de::IntoDeserializer};
6use std::{
7    fmt::{Debug, Display},
8    hash::Hash,
9    num::{NonZeroU32, ParseIntError},
10    str::FromStr,
11};
12use thiserror::Error;
13pub use uuid::Uuid;
14
15use crate::v1alpha1::Probe;
16
17pub type WatchId = Uuid;
18
19/// A watch is a number of regular checks to perform, as well as alerts to ring if something happens.
20#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, OperationIo)]
21#[serde(rename_all = "camelCase")]
22pub struct Watch {
23    pub id: WatchId,
24    /// User-readable identifier
25    pub name: String,
26    /// Unique identifier of this alerts owner. Will fire for watches with the same owner.
27    pub owner_ref: String,
28    pub config: WatchConfig,
29    pub status: WatchStatus,
30}
31impl PartialEq for Watch {
32    fn eq(&self, other: &Self) -> bool {
33        let Watch {
34            id,
35            name,
36            owner_ref,
37            config,
38            status: _,
39        } = self;
40        id == &other.id
41            && name == &other.name
42            && owner_ref == &other.owner_ref
43            && config == &other.config
44    }
45}
46impl Eq for Watch {}
47impl Hash for Watch {
48    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
49        let Watch {
50            id,
51            name,
52            owner_ref,
53            config,
54            status: _,
55        } = self;
56        id.hash(state);
57        name.hash(state);
58        owner_ref.hash(state);
59        config.hash(state);
60    }
61}
62impl Display for Watch {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(f, "{} ({})", self.name, self.id)
65    }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
69#[serde(rename_all = "camelCase")]
70pub struct CreateWatch {
71    /// User-readable identifier
72    pub name: String,
73    /// Unique identifier of this alerts owner. Will fire for watches with the same owner.
74    pub owner_ref: String,
75    pub config: WatchConfig,
76}
77#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, Error)]
78#[serde(rename_all = "camelCase")]
79pub enum CreateWatchError {
80    #[error("probes list must not be empty")]
81    NoProbes,
82    #[error("alerts list must not be empty")]
83    NoAlerts,
84}
85impl CreateWatch {
86    pub fn try_into_watch(self, id: WatchId) -> Result<Watch, CreateWatchError> {
87        if self.config.probes.is_empty() {
88            return Err(CreateWatchError::NoProbes);
89        }
90        Ok(Watch {
91            id,
92            name: self.name,
93            status: WatchStatus::new(&self.config),
94            owner_ref: self.owner_ref,
95            config: self.config,
96        })
97    }
98}
99impl From<Watch> for CreateWatch {
100    fn from(value: Watch) -> Self {
101        CreateWatch {
102            name: value.name,
103            owner_ref: value.owner_ref,
104            config: value.config,
105        }
106    }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, Default)]
110#[serde(rename_all = "camelCase")]
111pub struct WatchConfig {
112    /// Probes that this watch will execute
113    pub probes: Vec<Probe>,
114    /// Periods during with the watch will be paused. No probes will be executed.
115    /// Each maintenance period has a start and an end. Overlapping periods will be merged
116    pub maintenance_periods: Option<Vec<MaintenancePeriod>>,
117}
118impl WatchConfig {
119    pub fn in_maintenance_period(&self) -> bool {
120        self.maintenance_periods
121            .clone()
122            .is_some_and(|periods| periods.iter().any(|p| p.is_active()))
123    }
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
127#[serde(rename_all = "camelCase")]
128pub struct MaintenancePeriod {
129    // Start of the maintenance periods, as a cron expression
130    pub schedule: CronSchedule,
131    // Duration of the maintenance period, in minutes. Must be shorter than the period between maintenances
132    pub duration_mins: NonZeroU32,
133    // Timezone, in tz database format: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
134    #[schemars(with = "String")]
135    pub timezone: Tz,
136}
137impl MaintenancePeriod {
138    fn is_active_at(&self, at: DateTime<impl chrono::TimeZone>) -> bool {
139        let earliest_sched_start =
140            at.clone() - chrono::TimeDelta::minutes(i64::from(self.duration_mins.get()));
141
142        self.schedule
143            .schedule
144            .after(&earliest_sched_start)
145            .next()
146            .is_some_and(|start| start <= at)
147    }
148    pub fn is_active(&self) -> bool {
149        self.is_active_at(chrono::Utc::now().with_timezone(&self.timezone))
150    }
151}
152#[derive(Debug, Error)]
153pub enum ParseMaintenancePeriodError {
154    #[error(
155        "input must be colon-separated cron expression, duration and optional Timezone in minutes"
156    )]
157    InvalidFormat,
158    #[error("invalid Crontab expression: {0}")]
159    InvalidCron(#[from] cron::error::Error),
160    #[error("duration must be in minutes and an integer: {0}")]
161    InvalidDuration(#[from] ParseIntError),
162    #[error("failed to parse timezone: {0}")]
163    InvalidTimezone(#[from] chrono_tz::ParseError),
164}
165impl FromStr for MaintenancePeriod {
166    type Err = ParseMaintenancePeriodError;
167
168    fn from_str(s: &str) -> Result<Self, Self::Err> {
169        let segments: Vec<_> = s.split(":").collect();
170        if segments.len() < 2 || segments.len() > 3 {
171            return Err(ParseMaintenancePeriodError::InvalidFormat);
172        }
173        #[allow(clippy::indexing_slicing)] // panic-safety: statically checked above
174        let schedule: CronSchedule = segments[0].trim().parse()?;
175        #[allow(clippy::indexing_slicing)] // panic-safety: statically checked above
176        let duration_mins: NonZeroU32 = segments[1].trim().parse()?;
177        let timezone = segments
178            .get(2)
179            .map(|s| s.trim().parse())
180            .transpose()?
181            .unwrap_or(Tz::UTC);
182        Ok(MaintenancePeriod {
183            schedule,
184            duration_mins,
185            timezone,
186        })
187    }
188}
189
190#[derive(Debug, Clone, PartialEq, Eq, JsonSchema)]
191#[serde(rename_all = "camelCase", transparent)]
192#[schemars(with = "String")]
193/// A cron entry defining a schedule.
194// Thin wrapper around the cron crate for compatibility and to remove seconds field.
195pub struct CronSchedule {
196    schedule: cron::Schedule,
197}
198impl FromStr for CronSchedule {
199    type Err = cron::error::Error;
200
201    fn from_str(s: &str) -> Result<Self, Self::Err> {
202        // cron uses second-format cron expressions, wrap these so we don't confuse people
203        let exp = format!("0 {}", s);
204        Ok(CronSchedule {
205            schedule: exp.parse::<cron::Schedule>()?,
206        })
207    }
208}
209impl Hash for CronSchedule {
210    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
211        self.schedule.to_string().hash(state);
212    }
213}
214impl From<cron::Schedule> for CronSchedule {
215    fn from(value: cron::Schedule) -> Self {
216        CronSchedule { schedule: value }
217    }
218}
219// override cron::Schedules (de)serialization since that has a non-standard seconds field included
220impl Serialize for CronSchedule {
221    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
222    where
223        S: serde::Serializer,
224    {
225        let Some((_seconds, cron)) = self.schedule.source().split_once(" ") else {
226            return Err(serde::ser::Error::custom("malformed crontab expression"));
227        };
228        serializer.serialize_str(cron)
229    }
230}
231impl<'de> Deserialize<'de> for CronSchedule {
232    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
233    where
234        D: serde::Deserializer<'de>,
235    {
236        let with_seconds = format!("0 {}", String::deserialize(deserializer)?);
237        let schedule = cron::Schedule::deserialize(with_seconds.into_deserializer())?;
238        Ok(CronSchedule { schedule })
239    }
240}
241
242#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
243#[serde(rename_all = "camelCase")]
244pub struct WatchStatus {
245    pub state: WatchState,
246    #[serde(default)]
247    pub last_update: Option<DateTime<Utc>>,
248    #[serde(default)]
249    pub failing_probes: Vec<String>,
250}
251impl WatchStatus {
252    pub fn new(config: &WatchConfig) -> WatchStatus {
253        WatchStatus {
254            state: if config.in_maintenance_period() {
255                WatchState::InMaintenance
256            } else {
257                WatchState::Pending
258            },
259            last_update: Some(Utc::now()),
260            failing_probes: vec![],
261        }
262    }
263}
264
265#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, Default)]
266#[serde(rename_all = "camelCase")]
267pub enum WatchState {
268    #[default]
269    Pending,
270    Ok,
271    Failing,
272    InMaintenance,
273}
274impl Display for WatchState {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        write!(
277            f,
278            "{}",
279            match self {
280                Self::Pending => "pending",
281                Self::Ok => "ok",
282                Self::Failing => "failing",
283                Self::InMaintenance => "maintenance",
284            }
285        )
286    }
287}
288
289#[cfg(test)]
290#[allow(clippy::unwrap_used)]
291mod test {
292    use chrono::{TimeDelta, Timelike};
293    use cron::TimeUnitSpec;
294
295    use super::*;
296
297    #[test]
298    fn maintenace_period_parses() -> anyhow::Result<()> {
299        MaintenancePeriod::from_str("0 0 * * *:120")?;
300        MaintenancePeriod::from_str("* * * * *:120")?;
301        MaintenancePeriod::from_str("* * * * *:120:Europe/Berlin")?;
302        MaintenancePeriod::from_str("* * * * *:120:Etc/UTC")?;
303
304        let period = MaintenancePeriod::from_str("1 2 3 4 5:120")?;
305        assert!(period.schedule.schedule.minutes().includes(1));
306        assert!(period.schedule.schedule.hours().includes(2));
307        assert!(period.schedule.schedule.days_of_month().includes(3));
308        assert!(period.schedule.schedule.months().includes(4));
309        assert!(period.schedule.schedule.days_of_week().includes(5));
310        // cron also expects a seconds field for some godforsaken reason
311        assert!(period.schedule.schedule.seconds().includes(0));
312        assert_eq!(period.schedule.schedule.seconds().iter().count(), 1);
313
314        assert_eq!(period.duration_mins.get(), 120_u32);
315        Ok(())
316    }
317
318    // since the cron crate defaults to cron with a second field , we have to overwrite the Serialization logic
319    #[test]
320    fn maintenance_period_serde_roundtrip() -> anyhow::Result<()> {
321        let period = MaintenancePeriod {
322            schedule: "20 4 * * *".parse()?,
323            duration_mins: NonZeroU32::new(120).unwrap(),
324            timezone: chrono_tz::Europe::Berlin,
325        };
326        let serialized = serde_json::to_string(&period)?;
327        let deserialzed_naive: serde_json::Value = serde_json::from_str(&serialized)?;
328        assert_eq!(
329            deserialzed_naive
330                .as_object()
331                .unwrap()
332                .get("schedule")
333                .unwrap()
334                .as_str()
335                .unwrap(),
336            "20 4 * * *"
337        );
338        let _deserialized: MaintenancePeriod = serde_json::from_str(&serialized)?;
339        Ok(())
340    }
341
342    #[test]
343    fn maintenance_period_marks_active() {
344        let current = chrono::Utc::now();
345
346        let started_just_now = MaintenancePeriod::from_str(
347            format!("{} {} * * *:5", current.minute(), current.hour()).as_str(),
348        )
349        .unwrap();
350        let started_1h_ago = MaintenancePeriod::from_str(
351            format!(
352                "{} {} * * *:120",
353                current.minute(),
354                (current - TimeDelta::hours(1)).hour()
355            )
356            .as_str(),
357        )
358        .unwrap();
359        let starting_in_1h = MaintenancePeriod::from_str(
360            format!(
361                "{} {} * * *:5",
362                current.minute(),
363                (current + TimeDelta::hours(1)).hour()
364            )
365            .as_str(),
366        )
367        .unwrap();
368        let starting_next_minute_1m = MaintenancePeriod::from_str(
369            format!(
370                "{} {} * * *:1",
371                (current + TimeDelta::minutes(1)).minute(),
372                (current + TimeDelta::minutes(1)).hour()
373            )
374            .as_str(),
375        )
376        .unwrap();
377
378        assert!(!started_just_now.is_active_at(current - TimeDelta::minutes(1)));
379        assert!(started_just_now.is_active_at(current));
380        assert!(started_just_now.is_active_at(current + TimeDelta::minutes(4)));
381        assert!(!started_just_now.is_active_at(current + TimeDelta::minutes(5)));
382
383        assert!(!started_1h_ago.is_active_at(current - TimeDelta::minutes(61)));
384        assert!(started_1h_ago.is_active_at(current - TimeDelta::minutes(60)));
385        assert!(started_1h_ago.is_active_at(current));
386        assert!(started_1h_ago.is_active_at(current + TimeDelta::minutes(59)));
387        assert!(!started_1h_ago.is_active_at(current + TimeDelta::minutes(60)));
388
389        assert!(!starting_in_1h.is_active_at(current));
390        assert!(!starting_in_1h.is_active_at(current + TimeDelta::minutes(59)));
391        assert!(starting_in_1h.is_active_at(current + TimeDelta::minutes(60)));
392        assert!(starting_in_1h.is_active_at(current + TimeDelta::minutes(64)));
393        assert!(!starting_in_1h.is_active_at(current + TimeDelta::minutes(65)));
394
395        assert!(!starting_next_minute_1m.is_active_at(current));
396        assert!(starting_next_minute_1m.is_active_at(current + TimeDelta::minutes(1)));
397        assert!(!starting_next_minute_1m.is_active_at(current + TimeDelta::minutes(2)));
398    }
399}