use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::error::Result;
use crate::partition::{PartitionId, RecurringCrossing};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RuleAge {
pub id: String,
pub user: String,
pub created_at: DateTime<Utc>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<DateTime<Utc>>,
}
impl RuleAge {
pub fn new(id: impl Into<String>, user: impl Into<String>, created_at: DateTime<Utc>) -> Self {
Self { id: id.into(), user: user.into(), created_at, expires_at: None }
}
#[must_use]
pub fn with_expiry(mut self, at: DateTime<Utc>) -> Self {
self.expires_at = Some(at);
self
}
}
#[async_trait]
pub trait StandingRuleSource: Send + Sync {
async fn rules(&self, app: &str, user: &str) -> Result<Vec<RuleAge>>;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct StaleRule {
pub id: String,
pub user: String,
#[serde(rename = "ageMs", with = "crate::serde_util::millis")]
pub age: Duration,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct AgedProcess {
pub pid: String,
#[serde(rename = "ageMs", with = "crate::serde_util::millis")]
pub age: Duration,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ReviewReport {
pub partition: PartitionId,
#[serde(rename = "reviewPeriodMs", with = "crate::serde_util::millis")]
pub review_period: Duration,
pub at: DateTime<Utc>,
#[serde(default)]
pub rules: Vec<StaleRule>,
#[serde(default)]
pub sleepers: Vec<AgedProcess>,
#[serde(default)]
pub frozen: Vec<AgedProcess>,
#[serde(default)]
pub crossings: Vec<RecurringCrossing>,
}
impl ReviewReport {
pub const CROSSING_WINDOW: Duration = Duration::from_secs(7 * 86_400);
pub const CROSSING_THRESHOLD: usize = 5;
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
&& self.sleepers.is_empty()
&& self.frozen.is_empty()
&& self.crossings.is_empty()
}
pub fn crossing_remedies(&self) -> Vec<String> {
self.crossings.iter().map(RecurringCrossing::remedy).collect()
}
pub fn renewal_ask(&self) -> Option<String> {
if self.rules.is_empty() {
return None;
}
let ids: Vec<&str> = self.rules.iter().map(|rule| rule.id.as_str()).collect();
Some(format!(
"{} standing rule(s) have no expiry and were granted more than {} day(s) ago: {}. \
Renew each with an expiry, or revoke it.",
ids.len(),
self.review_period.as_secs() / 86_400,
ids.join(", ")
))
}
}