vtcode_session_store/
retention.rs1use std::path::Path;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use walkdir::WalkDir;
7
8use crate::error::SessionStoreError;
9use crate::query::SessionSummary;
10use crate::sessions_root;
11
12#[derive(Debug, Clone, Copy)]
14pub struct RetentionPolicy {
15 pub max_sessions: usize,
17 pub max_age_days: u64,
19}
20
21impl Default for RetentionPolicy {
22 fn default() -> Self {
23 Self { max_sessions: 50, max_age_days: 30 }
24 }
25}
26
27pub fn apply_retention(
33 workspace: &Path,
34 policy: RetentionPolicy,
35) -> Result<usize, SessionStoreError> {
36 let root = sessions_root(workspace);
37 if !root.exists() {
38 return Ok(0);
39 }
40 let mut sessions: Vec<SessionSummary> = crate::query::recent_sessions(workspace, usize::MAX);
41 let mut removed = 0usize;
42
43 if sessions.len() > policy.max_sessions {
45 sessions.sort_by(|a, b| a.updated_at.cmp(&b.updated_at));
46 let to_remove = sessions.len() - policy.max_sessions;
47 for s in sessions.iter().take(to_remove) {
48 remove_session(&root.join(&s.session_id))?;
49 removed += 1;
50 }
51 sessions.drain(..to_remove);
53 }
54
55 let cutoff = age_cutoff(policy.max_age_days);
57 for s in &sessions {
58 if older_than(s.updated_at.as_str(), cutoff) {
59 remove_session(&root.join(&s.session_id))?;
60 removed += 1;
61 }
62 }
63
64 Ok(removed)
65}
66
67pub fn gc_legacy(workspace: &Path) -> Result<u64, SessionStoreError> {
74 let vt = workspace.join(".vtcode");
75 let mut freed = 0u64;
76 for name in ["history", "logs"] {
77 let dir = vt.join(name);
78 if dir.exists() {
79 freed += dir_size(&dir);
80 std::fs::remove_dir_all(&dir).map_err(|e| SessionStoreError::io(dir.clone(), e))?;
81 }
82 }
83 Ok(freed)
84}
85
86fn remove_session(dir: &Path) -> Result<(), SessionStoreError> {
87 if dir.exists() {
88 std::fs::remove_dir_all(dir).map_err(|e| SessionStoreError::io(dir.to_path_buf(), e))?;
89 }
90 Ok(())
91}
92
93fn dir_size(dir: &Path) -> u64 {
94 WalkDir::new(dir)
95 .into_iter()
96 .filter_map(Result::ok)
97 .filter(|e| e.file_type().is_file())
98 .filter_map(|e| e.metadata().ok())
99 .map(|m| m.len())
100 .sum()
101}
102
103fn age_cutoff(max_age_days: u64) -> SystemTime {
104 SystemTime::now() - Duration::from_secs(max_age_days * 24 * 3600)
105}
106
107fn older_than(rfc3339: &str, cutoff: SystemTime) -> bool {
108 let Ok(dt) = chrono::DateTime::parse_from_rfc3339(rfc3339) else {
109 return false;
110 };
111 let cutoff_secs = cutoff
112 .duration_since(UNIX_EPOCH)
113 .map(|d| d.as_secs() as i64)
114 .unwrap_or(i64::MAX);
115 dt.timestamp() < cutoff_secs
116}