Skip to main content

vpf_runner/
start.rs

1//! When runs start: on a schedule, every so many minutes, or when files change.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5
6use jiff::civil::{Date, Time, Weekday};
7use jiff::{Timestamp, Zoned};
8use vpf::{Day, Plan};
9
10use crate::folder;
11
12/// The dates between which runs start: none before `from`, none after `until`.
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub struct Window {
15    /// No run starts before it.
16    pub from: Option<Timestamp>,
17    /// No run starts after it.
18    pub until: Option<Timestamp>,
19}
20
21impl Window {
22    /// The dates a plan's start names. A checked plan writes them as dates and times with their offset.
23    pub fn of(plan: &Plan) -> Self {
24        let read = |text: Option<&str>| text.and_then(|text| text.trim().parse::<Timestamp>().ok());
25        Self {
26            from: read(plan.runs_from()),
27            until: read(plan.runs_until()),
28        }
29    }
30
31    /// Whether a run that would start at `at` is too late.
32    pub fn over(&self, at: Timestamp) -> bool {
33        self.until.is_some_and(|until| at > until)
34    }
35}
36
37fn weekday(day: Day) -> Weekday {
38    match day {
39        Day::Mon => Weekday::Monday,
40        Day::Tue => Weekday::Tuesday,
41        Day::Wed => Weekday::Wednesday,
42        Day::Thu => Weekday::Thursday,
43        Day::Fri => Weekday::Friday,
44        Day::Sat => Weekday::Saturday,
45        Day::Sun => Weekday::Sunday,
46    }
47}
48
49/// The next time after `now` that falls on one of the days of the week or of the month, at the time of day
50/// `HH:MM`, in `now`'s time zone. A day of the month past the end of a month falls on its last day, once.
51///
52/// # Panics
53///
54/// When `time` is not `HH:MM`, or there are neither days nor dates, which a checked plan never has.
55pub fn next_schedule(days: &[Day], dates: &[i64], time: &str, now: &Zoned) -> Zoned {
56    let (hour, minute) = time.split_once(':').expect("a time as HH:MM");
57    let at = Time::new(
58        hour.parse().expect("an hour"),
59        minute.parse().expect("a minute"),
60        0,
61        0,
62    )
63    .expect("a time of day");
64    let wanted: Vec<Weekday> = days.iter().copied().map(weekday).collect();
65    let on_a_date = |date: Date| {
66        let last = i64::from(date.days_in_month());
67        dates
68            .iter()
69            .any(|&wanted| wanted.min(last) == i64::from(date.day()))
70    };
71    // Every day of the month comes within two months.
72    (0..=62)
73        .filter_map(|ahead| now.date().checked_add(jiff::Span::new().days(ahead)).ok())
74        .filter(|date| wanted.contains(&date.weekday()) || on_a_date(*date))
75        .filter_map(|date| date.to_datetime(at).to_zoned(now.time_zone().clone()).ok())
76        .find(|start| start > now)
77        .expect("a day within two months")
78}
79
80/// What the files that match the start's paths hold, to see when one changes.
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct Snapshot(BTreeMap<PathBuf, u64>);
83
84impl Snapshot {
85    /// What the matching files hold now.
86    pub fn take(base: &Path, paths: &[String]) -> Self {
87        Self(folder::contents(base, paths))
88    }
89}