agentmux_srv_core/backend/
old_versions_service.rs1use std::sync::Arc;
15use std::time::{Duration, SystemTime};
16
17use crate::backend::old_versions::{self as ov, Policy};
18use crate::backend::wconfig::ConfigState;
19
20const FIRST_AFTER: Duration = Duration::from_secs(20 * 60);
22const HOSTED_FIRST_AFTER: Duration = Duration::from_secs(2 * 60);
24const EVERY: Duration = Duration::from_secs(24 * 3600);
25
26pub fn policy(config: &ConfigState, hosted: bool) -> Policy {
29 Policy::from_extra_for(&config.get_settings().extra, hosted)
30}
31
32fn start_is_confirmed(layout: &ov::Layout) -> bool {
40 use crate::migrations::carry_forward::{version_core, CARRIED_FROM_FILE, PRE_VERSIONING};
41 let db_of = |name: &str| layout.versions_root.join(name).join("data").join("db");
42 let has_older_data = |than: (u64, u64, u64)| {
43 std::fs::read_dir(&layout.versions_root).map(|d| {
44 d.filter_map(|e| e.ok()).any(|e| {
45 let name = e.file_name();
46 name.to_str().and_then(version_core).is_some_and(|v| v < than) && db_of(&name.to_string_lossy()).join("objects.db").is_file()
47 })
48 })
49 };
50 let Some(mut at) = version_core(&layout.running) else {
51 return false;
52 };
53 let mut marker = std::fs::read_to_string(db_of(&layout.running).join(CARRIED_FROM_FILE));
54 loop {
56 let Ok(text) = marker else {
57 return false;
58 };
59 let from = text.trim();
60 if from == PRE_VERSIONING {
61 return true;
62 }
63 let Some(from_core) = version_core(from).filter(|v| *v < at) else {
64 return false;
65 };
66 let source = db_of(from);
67 if !source.join("objects.db").is_file() {
70 return has_older_data(from_core).is_ok_and(|older| !older);
71 }
72 marker = std::fs::read_to_string(source.join(CARRIED_FROM_FILE));
73 if marker.is_err() {
74 return has_older_data(from_core).is_ok_and(|older| !older);
75 }
76 at = from_core;
77 }
78}
79
80fn pass(config: &ConfigState, hosted: bool) {
81 let Some(layout) = ov::layout_from_env() else {
82 tracing::debug!("old versions: this srv has no per-version folders");
83 return;
84 };
85 let policy = policy(config, hosted);
86 if policy.clean && !start_is_confirmed(&layout) {
87 tracing::info!("old versions: this version did not carry its data forward; nothing is removed");
88 return;
89 }
90 let run = ov::run(&layout, &policy, !policy.clean, None, SystemTime::now());
91 if !run.scan_ok {
92 tracing::warn!("old versions: the running processes could not be read; nothing is removed");
93 return;
94 }
95 let plan = &run.plan;
96 match &run.report {
97 Some(report) => {
98 for (dir, bytes) in &report.removed {
99 tracing::info!(dir = %dir.display(), freed = %crate::backend::build_cache::human(*bytes), "old versions: removed");
100 }
101 for (dir, why) in &report.skipped {
102 tracing::info!(dir = %dir.display(), why = %why, "old versions: left alone");
103 }
104 }
105 None if !plan.removable.is_empty() => {
106 for c in &plan.removable {
107 tracing::info!(dir = %c.dir.display(), kind = ?c.kind, size = %crate::backend::build_cache::human(c.bytes), "old versions: could be removed");
108 }
109 tracing::info!(
110 folders = plan.removable.len(),
111 reclaimable = %crate::backend::build_cache::human(plan.reclaimable_bytes()),
112 "old versions: a dry run (set oldversions:clean to remove them)"
113 );
114 }
115 None => {}
116 }
117}
118
119pub fn install(config: Arc<ConfigState>, hosted: bool) {
121 if !hosted && !crate::backend::build_cache_service::this_srv_may_clean() {
123 tracing::debug!("old versions: not an srv that cleans");
124 return;
125 }
126 tokio::spawn(async move {
127 tokio::time::sleep(if hosted { HOSTED_FIRST_AFTER } else { FIRST_AFTER }).await;
128 let mut tick = tokio::time::interval(EVERY);
129 loop {
130 tick.tick().await;
131 let cfg = config.clone();
132 let _ = tokio::task::spawn_blocking(move || pass(&cfg, hosted)).await;
133 }
134 });
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 fn layout(root: &std::path::Path) -> ov::Layout {
142 ov::Layout { versions_root: root.join("versions"), running: "0.60.35".into(), channel: "chan".into(), portable_parents: Vec::new() }
143 }
144
145 fn db_dir(l: &ov::Layout) -> std::path::PathBuf {
146 let dir = l.versions_root.join(&l.running).join("data").join("db");
147 std::fs::create_dir_all(&dir).unwrap();
148 dir
149 }
150
151 fn version_with_data(l: &ov::Layout, name: &str, marker: Option<&str>) {
153 let dir = l.versions_root.join(name).join("data").join("db");
154 std::fs::create_dir_all(&dir).unwrap();
155 std::fs::write(dir.join("objects.db"), "").unwrap();
156 if let Some(m) = marker {
157 std::fs::write(dir.join(crate::migrations::carry_forward::CARRIED_FROM_FILE), m).unwrap();
158 }
159 }
160
161 fn carried_from_old(root: &std::path::Path) -> ov::Layout {
162 let l = layout(root);
163 std::fs::write(db_dir(&l).join(crate::migrations::carry_forward::CARRIED_FROM_FILE), "0.60.34\n").unwrap();
164 l
165 }
166
167 #[test]
168 fn a_start_that_carried_forward_the_origin_of_the_data_is_confirmed() {
169 let root = tempfile::tempdir().unwrap();
170 let l = carried_from_old(root.path());
171 version_with_data(&l, "0.60.34", None);
172 assert!(start_is_confirmed(&l), "the source is the oldest version with data");
173 }
174
175 #[test]
176 fn a_start_that_carried_forward_a_version_that_was_carried_itself_is_confirmed() {
177 let root = tempfile::tempdir().unwrap();
178 let l = carried_from_old(root.path());
179 version_with_data(&l, "0.60.33", None);
180 version_with_data(&l, "0.60.34", Some("0.60.33"));
181 assert!(start_is_confirmed(&l));
182 }
183
184 #[test]
185 fn a_start_from_the_pre_versioning_copy_is_confirmed() {
186 let root = tempfile::tempdir().unwrap();
187 let l = layout(root.path());
188 std::fs::write(db_dir(&l).join(crate::migrations::carry_forward::CARRIED_FROM_FILE), crate::migrations::carry_forward::PRE_VERSIONING).unwrap();
189 assert!(start_is_confirmed(&l));
190 }
191
192 #[test]
195 fn a_chain_through_a_copy_of_an_empty_fresh_start_is_not_confirmed() {
196 let root = tempfile::tempdir().unwrap();
197 let l = layout(root.path());
198 version_with_data(&l, "0.60.33", None);
199 version_with_data(&l, "0.60.34", None);
200 version_with_data(&l, "0.60.35", Some("0.60.34"));
201 std::fs::write(db_dir(&l).join(crate::migrations::carry_forward::CARRIED_FROM_FILE), "0.60.35").unwrap();
202 assert!(!start_is_confirmed(&l));
203 }
204
205 #[test]
206 fn a_marker_that_does_not_name_an_older_version_is_not_confirmed() {
207 let root = tempfile::tempdir().unwrap();
208 let l = carried_from_old(root.path());
209 version_with_data(&l, "0.60.34", Some("0.60.34"));
210 assert!(!start_is_confirmed(&l), "a loop back to itself");
211 }
212
213 #[test]
216 fn a_start_that_copied_an_empty_fresh_start_is_not_confirmed() {
217 let root = tempfile::tempdir().unwrap();
218 let l = carried_from_old(root.path());
219 version_with_data(&l, "0.60.33", None);
220 version_with_data(&l, "0.60.34", None);
221 assert!(!start_is_confirmed(&l));
222 }
223
224 #[test]
227 fn a_chain_whose_origin_an_earlier_pass_removed_is_still_confirmed() {
228 let root = tempfile::tempdir().unwrap();
229 let l = carried_from_old(root.path());
230 version_with_data(&l, "0.60.34", Some("0.60.33"));
231 assert!(start_is_confirmed(&l));
232 }
233
234 #[test]
236 fn a_source_folder_that_is_gone_with_older_data_behind_it_is_not_confirmed() {
237 let root = tempfile::tempdir().unwrap();
238 let l = carried_from_old(root.path());
239 version_with_data(&l, "0.60.33", None);
240 assert!(!start_is_confirmed(&l), "0.60.34 is gone, 0.60.33 is still there");
241 }
242
243 #[test]
245 fn a_start_with_no_record_of_a_carry_forward_is_not_confirmed_so_nothing_is_judged() {
246 let root = tempfile::tempdir().unwrap();
247 let l = layout(root.path());
248 db_dir(&l);
249 assert!(!start_is_confirmed(&l), "a database folder, but no record of where its data came from");
250 assert!(!start_is_confirmed(&layout(&root.path().join("elsewhere"))), "no folder at all");
251 }
252}