1use std::collections::BTreeSet;
11use std::path::{Path, PathBuf};
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use crate::apply::{ApplyEnv, journal};
15use crate::error::{CoreError, ErrorCode};
16use crate::fs::Fs;
17use crate::paths::SurjectionHome;
18use crate::secrets::SecretValue;
19use crate::secrets::scanner::MIN_TRACKED_LEN;
20use crate::store::{LOCK_TIMEOUT, StoreLock, utc_datetime};
21
22pub const FILES_DIR: &str = "files";
24const KEEP_RUNS: usize = 50;
26const KEEP_FOR: Duration = Duration::from_secs(30 * 86_400);
28
29pub fn timestamp(time: SystemTime) -> String {
31 let datetime = utc_datetime(time);
32 let (date, clock) = (datetime.date.expect("set"), datetime.time.expect("set"));
33 format!(
34 "{:04}{:02}{:02}T{:02}{:02}{:02}Z",
35 date.year,
36 date.month,
37 date.day,
38 clock.hour,
39 clock.minute,
40 clock.second.unwrap_or(0)
41 )
42}
43
44pub fn run_dir(home: &SurjectionHome, time: SystemTime, apply_id: &str) -> PathBuf {
46 home.backups_dir()
47 .join(FILES_DIR)
48 .join(format!("{}-{apply_id}", timestamp(time)))
49}
50
51pub fn encode_path(path: &Path) -> String {
56 let text = path.to_string_lossy();
57 let mut out = String::with_capacity(text.len());
58 for c in text.chars() {
59 let reserved = matches!(
60 c,
61 '%' | ':' | '/' | '\\' | '<' | '>' | '"' | '|' | '?' | '*'
62 ) || c.is_control();
63 if reserved {
64 let mut buf = [0u8; 4];
65 for byte in c.encode_utf8(&mut buf).bytes() {
66 out.push_str(&format!("%{byte:02X}"));
67 }
68 } else {
69 out.push(c);
70 }
71 }
72 out
73}
74
75pub fn decode_path(name: &str) -> Option<String> {
77 let bytes = name.as_bytes();
78 let mut out = Vec::with_capacity(bytes.len());
79 let mut index = 0;
80 while index < bytes.len() {
81 if bytes[index] == b'%' {
82 let hex = name.get(index + 1..index + 3)?;
83 out.push(u8::from_str_radix(hex, 16).ok()?);
84 index += 3;
85 } else {
86 out.push(bytes[index]);
87 index += 1;
88 }
89 }
90 String::from_utf8(out).ok()
91}
92
93pub fn save(
97 fs: &dyn Fs,
98 home: &SurjectionHome,
99 dir: &Path,
100 file: &Path,
101 bytes: &[u8],
102) -> Result<PathBuf, CoreError> {
103 for level in [
104 home.backups_dir(),
105 home.backups_dir().join(FILES_DIR),
106 dir.to_path_buf(),
107 ] {
108 fs.create_private_dir_all(&level).map_err(|err| {
109 CoreError::new(
110 ErrorCode::IoError,
111 format!("cannot create backup directory: {err}"),
112 )
113 .with_path(&level)
114 })?;
115 }
116 let path = dir.join(encode_path(file));
117 fs.write_private(&path, bytes).map_err(|err| {
118 CoreError::new(ErrorCode::IoError, format!("cannot write backup: {err}")).with_path(&path)
119 })?;
120 Ok(path)
121}
122
123pub fn prune(fs: &dyn Fs, home: &SurjectionHome, now: SystemTime) -> Result<(), CoreError> {
126 let root = home.backups_dir().join(FILES_DIR);
127 if !fs.is_dir(&root) {
128 return Ok(());
129 }
130 let mut runs: Vec<(PathBuf, SystemTime)> = fs
131 .read_dir(&root)
132 .map_err(|err| {
133 CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}"))
134 .with_path(&root)
135 })?
136 .into_iter()
137 .filter_map(|path| {
138 let name = path.file_name()?.to_str()?;
139 let time = parse_timestamp(name.get(..16)?)?;
140 Some((path, time))
141 })
142 .collect();
143 runs.sort_by_key(|(_, time)| *time);
144 let old = runs.len().saturating_sub(KEEP_RUNS);
145 for (path, time) in runs.into_iter().take(old) {
146 let age = now.duration_since(time).unwrap_or_default();
147 if age > KEEP_FOR {
148 fs.remove_dir_all(&path).map_err(|err| {
149 CoreError::new(ErrorCode::IoError, format!("cannot prune backups: {err}"))
150 .with_path(&path)
151 })?;
152 }
153 }
154 Ok(())
155}
156
157#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct BackupRun {
160 pub dir: String,
162 pub apply_id: String,
165 pub time: SystemTime,
166 pub files: Vec<PathBuf>,
168}
169
170pub fn list_runs(fs: &dyn Fs, home: &SurjectionHome) -> Result<Vec<BackupRun>, CoreError> {
173 let root = home.backups_dir().join(FILES_DIR);
174 if !fs.is_dir(&root) {
175 return Ok(Vec::new());
176 }
177 let list = |dir: &Path| {
178 fs.read_dir(dir).map_err(|err| {
179 CoreError::new(ErrorCode::IoError, format!("cannot list backups: {err}")).with_path(dir)
180 })
181 };
182 let mut runs = Vec::new();
183 for dir in list(&root)? {
184 let Some(name) = dir.file_name().and_then(|name| name.to_str()) else {
185 continue;
186 };
187 let (Some(time), Some(apply_id)) = (
188 name.get(..16).and_then(parse_timestamp),
189 name.get(17..)
190 .filter(|_| name.as_bytes().get(16) == Some(&b'-')),
191 ) else {
192 continue;
193 };
194 if !fs.is_dir(&dir) {
195 continue;
196 }
197 let mut files: Vec<PathBuf> = list(&dir)?
198 .iter()
199 .filter_map(|file| decode_path(file.file_name()?.to_str()?))
200 .map(PathBuf::from)
201 .collect();
202 files.sort();
203 runs.push(BackupRun {
204 dir: name.to_owned(),
205 apply_id: apply_id.to_owned(),
206 time,
207 files,
208 });
209 }
210 runs.sort_by(|a, b| {
211 b.time
212 .cmp(&a.time)
213 .then_with(|| b.apply_id.cmp(&a.apply_id))
214 });
215 Ok(runs)
216}
217
218pub fn parse_timestamp(text: &str) -> Option<SystemTime> {
220 let bytes = text.as_bytes();
221 if bytes.len() != 16 || bytes[8] != b'T' || bytes[15] != b'Z' {
222 return None;
223 }
224 let number = |range: std::ops::Range<usize>| text.get(range)?.parse::<i64>().ok();
225 let (year, month, day) = (number(0..4)?, number(4..6)?, number(6..8)?);
226 let (hour, minute, second) = (number(9..11)?, number(11..13)?, number(13..15)?);
227 let days = days_from_civil(year, month, day);
228 let seconds = days * 86_400 + hour * 3600 + minute * 60 + second;
229 Some(UNIX_EPOCH + Duration::from_secs(u64::try_from(seconds).ok()?))
230}
231
232fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
235 let year = if month <= 2 { year - 1 } else { year };
236 let era = year.div_euclid(400);
237 let yoe = year - era * 400;
238 let mp = (month + 9) % 12;
239 let doy = (153 * mp + 2) / 5 + day - 1;
240 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
241 era * 146_097 + doe - 719_468
242}
243
244pub fn mark_old_values(
251 fs: &dyn Fs,
252 state_dir: &Path,
253 apply_id: &str,
254 values: &[SecretValue],
255) -> Result<Vec<PathBuf>, CoreError> {
256 let needles = value_forms(values);
257 if needles.is_empty() {
258 return Ok(Vec::new());
259 }
260 let Some(mut run) = journal::result(fs, state_dir, apply_id)? else {
261 return Ok(Vec::new());
262 };
263 let mut found = Vec::new();
264 for record in run.files.iter_mut().filter(|record| !record.backup_removed) {
265 let Some(backup) = record.backup.as_deref() else {
266 continue;
267 };
268 let Ok(bytes) = fs.read(Path::new(backup)) else {
269 continue;
270 };
271 if needles.iter().any(|needle| contains(&bytes, needle)) {
272 record.old_values = true;
273 found.push(PathBuf::from(&record.file));
274 }
275 }
276 if !found.is_empty() {
277 run.save_result(fs, state_dir)?;
278 }
279 Ok(found)
280}
281
282fn value_forms(values: &[SecretValue]) -> Vec<Vec<u8>> {
285 let mut forms: BTreeSet<Vec<u8>> = BTreeSet::new();
286 for value in values {
287 let value = value.expose();
288 let escaped = serde_json::to_string(value).unwrap_or_default();
289 let escaped = escaped
290 .strip_prefix('"')
291 .and_then(|rest| rest.strip_suffix('"'))
292 .unwrap_or_default();
293 for form in [value, value.trim(), escaped] {
294 if form.len() >= MIN_TRACKED_LEN {
295 forms.insert(form.as_bytes().to_vec());
296 }
297 }
298 }
299 forms.into_iter().collect()
300}
301
302fn contains(haystack: &[u8], needle: &[u8]) -> bool {
303 haystack
304 .windows(needle.len())
305 .any(|window| window == needle)
306}
307
308pub(crate) fn files_holding(
311 fs: &dyn Fs,
312 files: &[PathBuf],
313 values: &[SecretValue],
314) -> Vec<PathBuf> {
315 let needles = value_forms(values);
316 if needles.is_empty() {
317 return Vec::new();
318 }
319 files
320 .iter()
321 .filter(|file| {
322 fs.read(file)
323 .is_ok_and(|bytes| needles.iter().any(|needle| contains(&bytes, needle)))
324 })
325 .cloned()
326 .collect()
327}
328
329#[derive(Debug, Default)]
331pub struct Purge {
332 pub removed: Vec<PathBuf>,
335 pub not_deleted: Vec<(PathBuf, CoreError)>,
339 pub failed: Vec<(PathBuf, CoreError)>,
341}
342
343pub fn purge_old_values(ax: &ApplyEnv<'_>, apply_id: &str) -> Result<Purge, CoreError> {
354 let fs = ax.fs;
355 let state_dir = ax.home.state_dir();
356 let _lock = StoreLock::acquire(fs, &state_dir, LOCK_TIMEOUT)?;
357 let Some(mut run) = journal::result(fs, &state_dir, apply_id)? else {
358 return Err(CoreError::new(
359 ErrorCode::NotFound,
360 format!("no apply run {apply_id:?} is recorded on this machine"),
361 ));
362 };
363 let mut purge = Purge::default();
364 let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
365 for record in run
366 .files
367 .iter_mut()
368 .filter(|record| record.old_values && !record.backup_removed)
369 {
370 let Some(backup) = record
371 .backup
372 .as_deref()
373 .map(|recorded| rebased(ax.home, Path::new(recorded)))
374 else {
375 continue;
376 };
377 let file = PathBuf::from(&record.file);
378 if let Err(err) = check_backup_path(ax.home, apply_id, &backup, &file) {
379 purge.failed.push((file, err));
380 continue;
381 }
382 let fail = |what: &str, err: std::io::Error| {
383 CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(&backup)
384 };
385 if fs.is_regular_file(&backup) {
386 if let Err(err) = fs.overwrite_with_zeros(&backup) {
387 purge
388 .failed
389 .push((file, fail("cannot overwrite backup", err)));
390 continue;
391 }
392 record.backup_removed = true;
395 if let Err(err) = fs.remove_file(&backup) {
396 purge
397 .not_deleted
398 .push((file.clone(), fail("cannot delete the zeroed backup", err)));
399 }
400 } else if fs.exists(&backup) || fs.is_dir(&backup) {
401 purge.failed.push((
402 file,
403 CoreError::new(
404 ErrorCode::InvalidValue,
405 "the recorded backup is not a regular file (a link or a folder); left alone",
406 )
407 .with_path(&backup),
408 ));
409 continue;
410 } else {
411 record.backup_removed = true;
414 }
415 purge.removed.push(file);
416 if let Some(dir) = backup.parent() {
417 dirs.insert(dir.to_path_buf());
418 }
419 }
420 if !purge.removed.is_empty() {
421 run.save_result(fs, &state_dir)?;
422 }
423 for dir in dirs {
424 if fs.read_dir(&dir).is_ok_and(|entries| entries.is_empty()) {
425 let _ = fs.remove_dir_all(&dir);
427 }
428 }
429 Ok(purge)
430}
431
432fn rebased(home: &SurjectionHome, recorded: &Path) -> PathBuf {
438 let name = recorded.file_name();
439 let run = recorded.parent().and_then(Path::file_name);
440 match (run, name) {
441 (Some(run), Some(name)) => home.backups_dir().join(FILES_DIR).join(run).join(name),
442 _ => recorded.to_path_buf(),
443 }
444}
445
446fn check_backup_path(
451 home: &SurjectionHome,
452 apply_id: &str,
453 backup: &Path,
454 file: &Path,
455) -> Result<(), CoreError> {
456 let root = home.backups_dir().join(FILES_DIR);
457 let suffix = format!("-{apply_id}");
458 let in_run = backup.parent().is_some_and(|dir| {
459 dir.parent() == Some(root.as_path())
460 && dir
461 .file_name()
462 .and_then(|name| name.to_str())
463 .is_some_and(|name| {
464 name.get(..16).and_then(parse_timestamp).is_some()
465 && name.get(16..) == Some(suffix.as_str())
466 })
467 });
468 let plain = backup
469 .components()
470 .all(|part| !matches!(part, std::path::Component::ParentDir));
471 let named =
472 backup.file_name().and_then(|name| name.to_str()) == Some(encode_path(file).as_str());
473 if in_run && plain && named {
474 Ok(())
475 } else {
476 Err(CoreError::new(
477 ErrorCode::InvalidValue,
478 format!(
479 "the recorded backup is not apply {apply_id}'s backup of this file; left alone"
480 ),
481 )
482 .with_path(backup))
483 }
484}
485
486pub fn removed_backups(
490 fs: &dyn Fs,
491 state_dir: &Path,
492 apply_id: &str,
493) -> Result<Vec<PathBuf>, CoreError> {
494 Ok(journal::result(fs, state_dir, apply_id)?
495 .map(|run| {
496 run.files
497 .into_iter()
498 .filter(|record| record.backup_removed)
499 .map(|record| PathBuf::from(record.file))
500 .collect()
501 })
502 .unwrap_or_default())
503}
504
505#[cfg(test)]
506mod rebase_tests {
507 use std::path::{Path, PathBuf};
508
509 use super::{FILES_DIR, rebased};
510 use crate::paths::{HomeSource, SurjectionHome};
511
512 #[test]
515 fn recorded_backups_are_rebuilt_under_this_data_folder() {
516 let root = std::env::temp_dir().join("surjection-rebase");
517 let home = SurjectionHome {
518 path: root.join("Surjection"),
519 source: HomeSource::Default,
520 sync_root: None,
521 };
522 let run = "20260101T000000Z-01M8WVNEZ659GZ5Q8B30FY2344";
523 let recorded: PathBuf = root
524 .join("Loadout")
525 .join("backups")
526 .join(FILES_DIR)
527 .join(run)
528 .join("file.json");
529 assert_eq!(
530 rebased(&home, &recorded),
531 home.backups_dir()
532 .join(FILES_DIR)
533 .join(run)
534 .join("file.json")
535 );
536 let elsewhere = Path::new("file.json");
537 assert_eq!(rebased(&home, elsewhere), elsewhere);
538 }
539}