Skip to main content

rustango_cms/analytics/
retention.rs

1//! Analytics retention — delete events older than N days. Run per
2//! tenant at boot (servers restart/redeploy regularly).
3
4use rustango::core::SqlValue;
5
6/// Default retention window when the tenant hasn't configured one.
7pub const DEFAULT_RETENTION_DAYS: i64 = 365;
8
9/// Resolve the retention window from the `"analytics"` `SiteSetting`
10/// scope (`retention_days`), falling back to [`DEFAULT_RETENTION_DAYS`].
11pub async fn retention_days(pool: &rustango::sql::Pool) -> i64 {
12    match crate::site_setting::get(pool, super::SETTINGS_SCOPE).await {
13        Ok(Some(s)) => s
14            .value_json
15            .get("retention_days")
16            .and_then(serde_json::Value::as_i64)
17            .filter(|d| *d > 0)
18            .unwrap_or(DEFAULT_RETENTION_DAYS),
19        _ => DEFAULT_RETENTION_DAYS,
20    }
21}
22
23/// Delete events older than `days`. `days <= 0` is a no-op (never wipe
24/// the whole table implicitly).
25///
26/// # Errors
27/// Driver / SQL failures from the DELETE.
28pub async fn prune(pool: &rustango::sql::Pool, days: i64) -> Result<(), rustango::sql::ExecError> {
29    if days <= 0 {
30        return Ok(());
31    }
32    let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
33    let d = pool.dialect();
34    let sql = format!(
35        "DELETE FROM {} WHERE {} < {}",
36        d.quote_ident("cms_analytics_event"),
37        d.quote_ident("created_at"),
38        d.placeholder(1),
39    );
40    // A typed bind on every dialect (#654): `created_at` is written by the
41    // ORM, which SQLite stores as RFC3339 text, so a space-separated
42    // cutoff compared lexically kept rows from the cutoff's own day.
43    rustango::sql::raw_execute_pool(pool, &sql, vec![SqlValue::DateTime(cutoff)]).await?;
44    Ok(())
45}
46
47#[cfg(all(test, feature = "sqlite"))]
48mod tests {
49    use super::*;
50    use crate::analytics::model::AnalyticsEvent;
51    use rustango::sql::{Auto, FetcherPool as _};
52
53    fn event(path: &str, created_at: chrono::DateTime<chrono::Utc>) -> AnalyticsEvent {
54        AnalyticsEvent {
55            id: Auto::Unset,
56            visitor_id: "v".into(),
57            session_id: "s".into(),
58            event_type: "pageview".into(),
59            path: path.into(),
60            referrer_host: String::new(),
61            country: String::new(),
62            device: String::new(),
63            browser: String::new(),
64            os: String::new(),
65            screen_w: 0,
66            screen_h: 0,
67            duration_ms: 0,
68            max_scroll_pct: 0,
69            is_bounce: false,
70            locale: String::new(),
71            created_at,
72        }
73    }
74
75    /// An event minutes past the cutoff is deleted on SQLite, even
76    /// on the cutoff's own calendar day.
77    #[tokio::test]
78    async fn prune_deletes_right_up_to_the_cutoff() {
79        let pool = rustango::sql::Pool::connect("sqlite::memory:")
80            .await
81            .expect("pool");
82        crate::analytics::model::ensure_table(&pool).await.expect("table");
83        let cutoff = chrono::Utc::now() - chrono::Duration::days(1);
84        for (path, at) in [
85            ("/old", cutoff - chrono::Duration::minutes(5)),
86            ("/new", cutoff + chrono::Duration::minutes(5)),
87        ] {
88            event(path, at).insert(&pool).await.expect("event");
89        }
90        prune(&pool, 1).await.expect("prune");
91        let left: Vec<String> = AnalyticsEvent::objects()
92            .fetch(&pool)
93            .await
94            .expect("fetch")
95            .into_iter()
96            .map(|e| e.path)
97            .collect();
98        assert_eq!(left, ["/new"]);
99    }
100}