180 lines
6.1 KiB
Rust
180 lines
6.1 KiB
Rust
use crate::state::HubState;
|
|
use anyhow::{Context, Result};
|
|
use chrono::{DateTime, NaiveTime, TimeZone, Utc};
|
|
use chrono_tz::Tz;
|
|
use cron::Schedule;
|
|
use std::str::FromStr;
|
|
use tessera_core::job::CaptureSchedule;
|
|
use tokio::time::{sleep, Duration};
|
|
use tracing::{error, info};
|
|
|
|
pub async fn start_orbit_scheduler(state: HubState) -> Result<()> {
|
|
let db = state.db.clone();
|
|
tokio::spawn(async move {
|
|
loop {
|
|
if let Err(e) = tick_capture_schedules(&db, Utc::now()) {
|
|
error!("capture scheduler tick: {e}");
|
|
}
|
|
sleep(Duration::from_secs(30)).await;
|
|
}
|
|
});
|
|
tokio::spawn(async move {
|
|
let mut previous = Utc::now();
|
|
loop {
|
|
let now = Utc::now();
|
|
if let Err(e) = tick_schedules(state.clone(), previous, now).await {
|
|
error!("scheduler tick: {e}");
|
|
}
|
|
previous = now;
|
|
sleep(Duration::from_secs(30)).await;
|
|
}
|
|
});
|
|
Ok(())
|
|
}
|
|
|
|
const DEFAULT_AUDIT_RETENTION_DAYS: i64 = 90;
|
|
|
|
/// `TESSERA_AUDIT_RETENTION_DAYS`: how long structured audit events are kept.
|
|
/// Unset means 90 days; `0` keeps them forever.
|
|
pub fn audit_retention_from_env() -> Result<Option<i64>> {
|
|
parse_audit_retention(std::env::var("TESSERA_AUDIT_RETENTION_DAYS").ok().as_deref())
|
|
}
|
|
|
|
fn parse_audit_retention(value: Option<&str>) -> Result<Option<i64>> {
|
|
let Some(value) = value.map(str::trim).filter(|v| !v.is_empty()) else {
|
|
return Ok(Some(DEFAULT_AUDIT_RETENTION_DAYS));
|
|
};
|
|
let days: i64 = value
|
|
.parse()
|
|
.ok()
|
|
.filter(|days| (0..=36_500).contains(days))
|
|
.context("TESSERA_AUDIT_RETENTION_DAYS must be a whole number of days (0 keeps everything)")?;
|
|
Ok((days > 0).then_some(days))
|
|
}
|
|
|
|
/// Prunes audit events once now and then every hour.
|
|
pub fn start_audit_retention(db: crate::db::Db, retention_days: Option<i64>) {
|
|
let Some(days) = retention_days else {
|
|
info!("audit retention disabled: audit events are kept forever");
|
|
return;
|
|
};
|
|
tokio::spawn(async move {
|
|
loop {
|
|
let cutoff = Utc::now().timestamp() - days * 86_400;
|
|
match db.prune_audit_events(cutoff) {
|
|
Ok(0) => {}
|
|
Ok(n) => info!("pruned {n} audit event(s) older than {days} days"),
|
|
Err(e) => error!("audit retention: {e}"),
|
|
}
|
|
sleep(Duration::from_secs(3600)).await;
|
|
}
|
|
});
|
|
}
|
|
|
|
pub(crate) fn orbit_schedule(expression: &str) -> Result<Schedule, cron::error::Error> {
|
|
if expression.split_whitespace().count() == 5 {
|
|
Schedule::from_str(&format!("0 {expression}"))
|
|
} else {
|
|
Schedule::from_str(expression)
|
|
}
|
|
}
|
|
|
|
async fn tick_schedules(
|
|
state: HubState,
|
|
previous: DateTime<Utc>,
|
|
now: DateTime<Utc>,
|
|
) -> Result<()> {
|
|
let orbits = state.db.list_orbits().await?;
|
|
for orbit in orbits {
|
|
if orbit.provider == "wormhole" {
|
|
continue;
|
|
}
|
|
let Some(cron_expr) = orbit
|
|
.schedule
|
|
.as_deref()
|
|
.filter(|expr| !expr.trim().is_empty())
|
|
else {
|
|
continue;
|
|
};
|
|
let schedule = match orbit_schedule(cron_expr) {
|
|
Ok(s) => s,
|
|
Err(e) => {
|
|
error!("bad cron on orbit {}: {e}", orbit.name);
|
|
continue;
|
|
}
|
|
};
|
|
if schedule
|
|
.after(&previous)
|
|
.next()
|
|
.is_some_and(|slot| slot <= now)
|
|
{
|
|
info!("scheduler firing orbit {}", orbit.name);
|
|
let orbit_id = orbit.id;
|
|
if let Err(e) = crate::api::run_orbit_internal(state.clone(), orbit).await {
|
|
error!("orbit {orbit_id} failed: {e}");
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn capture_schedule(schedule: &CaptureSchedule) -> Option<(NaiveTime, Tz)> {
|
|
let time = NaiveTime::from_hms_opt(u32::from(schedule.hour), u32::from(schedule.minute), 0)?;
|
|
Some((time, schedule.timezone.parse().ok()?))
|
|
}
|
|
|
|
pub(crate) fn tick_capture_schedules(db: &crate::db::Db, now: DateTime<Utc>) -> Result<()> {
|
|
for (profile, cursor) in db.capture_schedule_cursors()? {
|
|
let Some(schedule) = &profile.schedule else {
|
|
continue;
|
|
};
|
|
let (time, tz) = capture_schedule(schedule).context("invalid stored capture schedule")?;
|
|
let start = DateTime::from_timestamp(cursor, 0).context("invalid schedule cursor")?;
|
|
let end = now.with_timezone(&tz).date_naive();
|
|
let mut date = start.with_timezone(&tz).date_naive();
|
|
for _ in 0..32 {
|
|
if date > end {
|
|
break;
|
|
}
|
|
if let Some(slot) = tz.from_local_datetime(&date.and_time(time)).earliest() {
|
|
if slot.timestamp() > cursor && slot <= now {
|
|
db.enqueue_scheduled_capture(
|
|
profile.application_id,
|
|
slot.timestamp(),
|
|
now.timestamp(),
|
|
)?;
|
|
}
|
|
}
|
|
date = date.succ_opt().context("schedule date overflow")?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn audit_retention_defaults_to_ninety_days_and_zero_disables_it() {
|
|
assert_eq!(parse_audit_retention(None).unwrap(), Some(90));
|
|
assert_eq!(parse_audit_retention(Some(" ")).unwrap(), Some(90));
|
|
assert_eq!(parse_audit_retention(Some("30")).unwrap(), Some(30));
|
|
assert_eq!(parse_audit_retention(Some("0")).unwrap(), None);
|
|
assert!(parse_audit_retention(Some("-1")).is_err());
|
|
assert!(parse_audit_retention(Some("soon")).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn orbit_cron_accepts_legacy_minutes_and_explicit_seconds() {
|
|
let before = Utc.with_ymd_and_hms(2026, 11, 10, 1, 59, 55).unwrap();
|
|
let slot = Utc.with_ymd_and_hms(2026, 11, 10, 2, 0, 0).unwrap();
|
|
for expression in ["0 2 * * *", "0 0 2 * * *"] {
|
|
let schedule = orbit_schedule(expression).unwrap();
|
|
assert_eq!(schedule.after(&before).next(), Some(slot));
|
|
assert!(schedule.after(&slot).next().unwrap() > slot);
|
|
}
|
|
assert!(orbit_schedule("60 2 * * *").is_err());
|
|
}
|
|
}
|