Skip to main content

schedr_master/
retention.rs

1//! The master's retention job (decisions 430-435): every `SCHEDR_HIDDEN__MASTER__RETENTION_INTERVAL`
2//! (1 h) while it leads, it deletes what `[retention]` no longer keeps, a batch of
3//! `SCHEDR_HIDDEN__MASTER__RETENTION_BATCH` runs per transaction, until nothing is left, so it
4//! never holds long locks nor holds the scheduler up (it runs beside the master's loop).
5
6use std::time::Duration;
7
8use jiff::{SignedDuration, Timestamp};
9use schedr_config::config::{Age, RetentionSection};
10use schedr_db::{Database, DbError};
11
12use crate::metrics::MasterMetrics;
13
14#[cfg(test)]
15mod tests;
16
17/// How long each kind is kept: `None` forever.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct RetentionSettings {
20    /// Finished runs.
21    pub runs: Option<Duration>,
22    /// Finished runs' outputs (only when shorter than `runs`).
23    pub outputs: Option<Duration>,
24    /// Events triggers found and events posted through the API.
25    pub events: Option<Duration>,
26    /// Decided commands.
27    pub commands: Option<Duration>,
28    /// How often a pass runs.
29    pub interval: Duration,
30    /// The most runs (events, commands) one transaction deletes.
31    pub batch: u32,
32}
33
34impl Default for RetentionSettings {
35    /// Everything kept: a master built for a test deletes nothing.
36    fn default() -> Self {
37        Self {
38            runs: None,
39            outputs: None,
40            events: None,
41            commands: None,
42            interval: Duration::from_hours(1),
43            batch: 100,
44        }
45    }
46}
47
48const fn kept(age: Age) -> Option<Duration> {
49    match age {
50        Age::For(duration) => Some(duration),
51        Age::Forever => None,
52    }
53}
54
55impl RetentionSettings {
56    /// From `[retention]` and the hidden interval and batch.
57    #[must_use]
58    pub fn from_config(section: &RetentionSection, interval: Duration, batch: usize) -> Self {
59        let runs = kept(section.runs);
60        // Outputs kept as long as their runs, or longer: they go with the runs.
61        let outputs = kept(section.outputs()).filter(|o| runs.is_none_or(|r| *o < r));
62        Self {
63            runs,
64            outputs,
65            events: kept(section.events()),
66            commands: kept(section.commands),
67            interval,
68            batch: u32::try_from(batch).unwrap_or(u32::MAX).max(1),
69        }
70    }
71}
72
73/// What one pass deleted.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75pub struct Pass {
76    /// Runs.
77    pub runs: u64,
78    /// Runs whose outputs went.
79    pub outputs: u64,
80    /// Events.
81    pub events: u64,
82    /// Commands.
83    pub commands: u64,
84    /// Removed DAGs gone with their last run.
85    pub dags: u64,
86    /// DAG versions no run, trigger or DAG uses any more.
87    pub versions: u64,
88}
89
90impl Pass {
91    /// Whether it deleted anything.
92    #[must_use]
93    pub const fn any(&self) -> bool {
94        self.runs + self.outputs + self.events + self.commands + self.dags + self.versions > 0
95    }
96}
97
98/// `now` less `age`: what ended before is old.
99fn cut(now: Timestamp, age: Duration) -> Timestamp {
100    SignedDuration::try_from(age)
101        .ok()
102        .and_then(|age| now.checked_sub(age).ok())
103        .unwrap_or(Timestamp::MIN)
104}
105
106/// Deletes batch after batch through `delete`, while `leading`, until one deletes nothing (a
107/// batch of runs is one DAG's, so one not full doesn't mean none is left).
108async fn batches<F, Fut>(leading: &impl Fn() -> bool, mut delete: F) -> Result<u64, DbError>
109where
110    F: FnMut() -> Fut,
111    Fut: std::future::Future<Output = Result<u64, DbError>>,
112{
113    let mut total = 0;
114    while leading() {
115        let deleted = delete().await?;
116        total += deleted;
117        if deleted == 0 {
118            break;
119        }
120    }
121    Ok(total)
122}
123
124/// One pass at `now`: outputs, runs, removed DAGs, unused DAG versions, events, commands, each
125/// counted in `metrics`. Stops when this master no longer leads.
126///
127/// # Errors
128///
129/// [`DbError`] if a batch fails: what the earlier ones deleted stays deleted.
130pub async fn pass(
131    db: &Database,
132    settings: &RetentionSettings,
133    now: Timestamp,
134    leading: impl Fn() -> bool,
135    metrics: &MasterMetrics,
136) -> Result<Pass, DbError> {
137    let batch = settings.batch;
138    let mut pass = Pass::default();
139    if let Some(age) = settings.outputs {
140        let before = cut(now, age);
141        pass.outputs = batches(&leading, || db.delete_old_outputs(before, batch, now)).await?;
142        metrics.retention_deleted("outputs", pass.outputs);
143    }
144    if let Some(age) = settings.runs {
145        let before = cut(now, age);
146        pass.runs = batches(&leading, || db.delete_old_runs(before, batch)).await?;
147        metrics.retention_deleted("runs", pass.runs);
148        if leading() {
149            pass.dags = db.delete_removed_dags(before).await?;
150            metrics.retention_deleted("dags", pass.dags);
151        }
152        pass.versions = batches(&leading, || db.delete_unused_versions()).await?;
153        metrics.retention_deleted("versions", pass.versions);
154    }
155    if let Some(age) = settings.events {
156        let before = cut(now, age);
157        pass.events = batches(&leading, || db.delete_old_events(before, batch)).await?;
158        metrics.retention_deleted("events", pass.events);
159    }
160    if let Some(age) = settings.commands {
161        let before = cut(now, age);
162        pass.commands = batches(&leading, || db.delete_old_commands(before, batch)).await?;
163        metrics.retention_deleted("commands", pass.commands);
164    }
165    Ok(pass)
166}