use serde::{Deserialize, Serialize};
use crate::time;
pub const MAX_SPAN_MS: i64 = 366 * 24 * 3_600_000;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "WindowText")]
pub struct Window {
pub from: String,
pub until: String,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum WindowText {
Window {
#[serde(default)]
from: String,
#[serde(default)]
until: String,
},
Other(serde::de::IgnoredAny),
}
impl From<WindowText> for Window {
fn from(text: WindowText) -> Self {
match text {
WindowText::Window { from, until } => Self { from, until },
WindowText::Other(_) => Self {
from: String::new(),
until: String::new(),
},
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Holds { until_ms: i64 },
Ended { until_ms: i64 },
Early,
Unreadable,
}
impl Window {
#[must_use]
pub fn starting(now_ms: i64, span_ms: i64) -> Self {
let end = now_ms.saturating_add(span_ms).saturating_add(999);
Self {
from: time::rfc3339(now_ms),
until: time::rfc3339(end.div_euclid(1000) * 1000),
}
}
#[must_use]
pub fn state(&self, now_ms: i64) -> State {
match (
time::parse_rfc3339(&self.from),
time::parse_rfc3339(&self.until),
) {
(Some(from), Some(until_ms)) if from < until_ms => {
if now_ms < from {
State::Early
} else if now_ms < until_ms {
State::Holds { until_ms }
} else {
State::Ended { until_ms }
}
}
_ => State::Unreadable,
}
}
#[must_use]
pub fn holds(&self, now_ms: i64) -> bool {
matches!(self.state(now_ms), State::Holds { .. })
}
}
pub const SOON_MS: i64 = 24 * 3_600_000;
#[must_use]
pub fn summary(overlay: &super::Overlay, now_ms: i64) -> Option<String> {
let mut ended = Vec::new();
let mut soon = Vec::new();
for id in overlay.ids() {
match overlay.expires.get(id).map(|w| w.state(now_ms)) {
Some(State::Holds { until_ms }) if until_ms - now_ms <= SOON_MS => {
soon.push(format!("{id} in {}", time::duration(until_ms - now_ms)));
}
None | Some(State::Holds { .. }) => {}
Some(_) => ended.push(id),
}
}
let ended = (!ended.is_empty()).then(|| {
format!(
"{} standing grant(s) expired and no longer apply ({}; `openmoat allow --prune` \
removes them)",
ended.len(),
ended.join(", ")
)
});
let soon = (!soon.is_empty()).then(|| format!("ending soon: {}", soon.join(", ")));
let parts: Vec<String> = [ended, soon].into_iter().flatten().collect();
(!parts.is_empty()).then(|| parts.join("; "))
}
pub fn parse_for(text: &str) -> anyhow::Result<i64> {
use anyhow::Context as _;
let span = time::parse_span(text).filter(|s| *s <= MAX_SPAN_MS);
span.with_context(|| {
format!(
"cannot read `{text}` as a duration; use a number and s, m, h, d or w (30m, 2h, \
3d, 1w), at most 366 days; leave out --for for a grant that lasts until you \
remove it"
)
})
}
#[cfg(test)]
mod tests;