1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! Allows to keep the number of backup files under control.
use std::fmt;
use chrono::{Datelike, Timelike};
use chrono::{Duration, Local};
use itertools::Itertools;
use super::backup::{Backup, BackupStatus};
/// Backups compaction strategy.
///
/// Determines if a backup can be kept (retainable) or purged (purgeable).
#[derive(Debug, Clone)]
pub enum Strategy {
/// Keep the `k` most recent backups.
KeepMostRecent {
/// Number of recent backup files to keep.
k: usize,
},
/// Classic backup strategy.
///
/// This is only useful if you save _very_ often, probably in an automated manner. See
/// the method [`Strategy::plan`] for details.
Classic,
}
impl Strategy {
/// Return a new simple strategy.
pub fn most_recent(k: usize) -> Self {
Self::KeepMostRecent { k }
}
/// Determine which backup files should be kept.
///
/// The `backup_files` are assumed to be sorted from oldest to newest.
///
/// # KeepMostRecent strategy
///
/// Simply splits the list of all backups into 2 lists: the `k` recent ones (or less if the
/// catalog does not contain as much) and the remaining ones are considered outdated
/// (purgeable).
///
/// # Classic strategy
///
/// Its goal is to keep
///
/// - the lastest backup per hour for the past 24 hours (max 23 backups - exclude the past hour),
/// - the lastest backup per day for the past 7 days (max 6 backups - exclude the past 24 hours),
/// - the lastest backup per week of the past 4 weeks (max 3 backups - exclude the past week),
/// - the lastest backup per month of this year (max 11 backups - exclude the past month).
///
/// The time windows above are a partition; they do not overlap. Within each partition,
/// only the most recent backup is kept.
///
pub fn plan<'a>(&self, backups: &'a [Backup]) -> Plan<'a> {
match self {
Strategy::KeepMostRecent { k } => {
let k = std::cmp::min(backups.len(), *k);
let index = std::cmp::max(0, backups.len() - k);
let (outdated_backups, recent_backups) = backups.split_at(index);
let mut statuses = vec![];
statuses.extend(
outdated_backups
.iter()
.map(|backup| (backup, BackupStatus::Purgeable)),
);
statuses.extend(
recent_backups
.iter()
.map(|backup| (backup, BackupStatus::Retainable)),
);
Plan {
purgeable: outdated_backups.iter().collect(),
retainable: recent_backups.iter().collect(),
statuses,
}
}
Strategy::Classic => {
let now = Local::now().naive_local();
let _24h_ago = now - Duration::days(1);
let _7d_ago = now - Duration::days(7);
let _4w_ago = now - Duration::weeks(4);
let _year_ago = now - Duration::days(365);
// Last 24 h, grouped by hour
let last_24h_per_hour: Vec<_> = backups
.iter()
.filter(|&b| b.creation_date > _24h_ago)
.chunk_by(|&b| b.creation_date.hour())
.into_iter()
.map(|(_key, group)| group.collect::<Vec<_>>())
.filter_map(|group| group.last().cloned())
.collect();
// Last 7 days excluding the last 24 h, grouped by day
let last_7d_per_day: Vec<_> = backups
.iter()
.filter(|&b| _24h_ago > b.creation_date && b.creation_date >= _7d_ago)
.chunk_by(|&b| b.creation_date.day())
.into_iter()
.map(|(_key, group)| group.collect::<Vec<_>>())
.filter_map(|group| group.last().cloned())
.collect();
// Last 4 weeks excluding the last 7 days, grouped by week number
let last_4w_per_isoweek: Vec<_> = backups
.iter()
.filter(|&b| _7d_ago > b.creation_date && b.creation_date >= _4w_ago)
.chunk_by(|&b| b.creation_date.iso_week())
.into_iter()
.map(|(_key, group)| group.collect::<Vec<_>>())
.filter_map(|group| group.last().cloned())
.collect();
// Last year (365 days) excluding the last 4 weeks, grouped by month
let last_year_per_month: Vec<_> = backups
.iter()
.filter(|&b| _4w_ago > b.creation_date && b.creation_date >= _year_ago)
.chunk_by(|&b| b.creation_date.month())
.into_iter()
.map(|(_key, group)| group.collect::<Vec<_>>())
.filter_map(|group| group.last().cloned())
.collect();
let retainable: Vec<_> = vec![
last_year_per_month,
last_4w_per_isoweek,
last_7d_per_day,
last_24h_per_hour,
]
.into_iter()
.flatten()
.collect();
let retain_set: std::collections::HashSet<&Backup> =
retainable.iter().copied().collect();
let purgeable: Vec<_> = backups
.iter()
.filter(|&b| !retain_set.contains(b))
.collect();
let statuses: Vec<_> = backups
.iter()
.map(|b| {
if retain_set.contains(b) {
(b, BackupStatus::Retainable)
} else {
(b, BackupStatus::Purgeable)
}
})
.collect();
Plan {
purgeable,
retainable,
statuses,
}
}
}
}
}
impl fmt::Display for Strategy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Strategy::KeepMostRecent { k } => {
write!(f, "KeepMostRecent: {k}")
}
Strategy::Classic => write!(f, "Classic"),
}
}
}
/// Describes what the strategy would do.
pub struct Plan<'a> {
/// List of backup files that should be purged.
pub purgeable: Vec<&'a Backup>,
/// List of backup files that should be kept.
pub retainable: Vec<&'a Backup>,
/// Sorted list of backup files along with their status (purgeable/retainable).
pub statuses: Vec<(&'a Backup, BackupStatus)>,
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::NaiveDate;
use std::path::PathBuf;
/// Create a backup at the given date/time. The path encodes the datetime for easy debugging.
fn backup_at(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> Backup {
let dt = NaiveDate::from_ymd_opt(year, month, day)
.unwrap()
.and_hms_opt(hour, min, sec)
.unwrap();
Backup {
filepath: PathBuf::from(format!(
"/backups/backup-{}.tar.zst",
dt.format("%Y%m%dT%H%M%S")
)),
creation_date: dt,
}
}
/// Generate a sequence of backups, one per hour, starting from a base datetime.
fn generate_hourly_backups(count: usize) -> Vec<Backup> {
(0..count)
.map(|i| {
let hour = i % 24;
let day = 1 + (i / 24);
backup_at(2024, 6, day as u32, hour as u32, 0, 0)
})
.collect()
}
mod keep_most_recent_strategy {
use super::*;
#[test]
fn empty_catalog_produces_empty_plan() {
let strategy = Strategy::most_recent(5);
let backups: Vec<Backup> = vec![];
let plan = strategy.plan(&backups);
assert!(plan.purgeable.is_empty());
assert!(plan.retainable.is_empty());
assert!(plan.statuses.is_empty());
}
#[test]
fn single_backup_when_k_is_one() {
let strategy = Strategy::most_recent(1);
let backups = vec![backup_at(2024, 6, 15, 10, 0, 0)];
let plan = strategy.plan(&backups);
assert!(plan.purgeable.is_empty());
assert_eq!(plan.retainable.len(), 1);
}
#[test]
fn single_backup_when_k_exceeds_count() {
let strategy = Strategy::most_recent(10);
let backups = vec![backup_at(2024, 6, 15, 10, 0, 0)];
let plan = strategy.plan(&backups);
// Should keep the one backup we have, not fail
assert!(plan.purgeable.is_empty());
assert_eq!(plan.retainable.len(), 1);
}
#[test]
fn keeps_exactly_k_most_recent() {
let strategy = Strategy::most_recent(3);
let backups = vec![
backup_at(2024, 6, 15, 8, 0, 0), // oldest - purgeable
backup_at(2024, 6, 15, 9, 0, 0), // purgeable
backup_at(2024, 6, 15, 10, 0, 0), // retainable
backup_at(2024, 6, 15, 11, 0, 0), // retainable
backup_at(2024, 6, 15, 12, 0, 0), // newest - retainable
];
let plan = strategy.plan(&backups);
assert_eq!(plan.purgeable.len(), 2);
assert_eq!(plan.retainable.len(), 3);
// The oldest two should be purgeable
assert_eq!(plan.purgeable[0].creation_date.hour(), 8);
assert_eq!(plan.purgeable[1].creation_date.hour(), 9);
// The newest three should be retainable
assert_eq!(plan.retainable[0].creation_date.hour(), 10);
assert_eq!(plan.retainable[1].creation_date.hour(), 11);
assert_eq!(plan.retainable[2].creation_date.hour(), 12);
}
#[test]
fn statuses_preserve_original_order() {
let strategy = Strategy::most_recent(2);
let backups = vec![
backup_at(2024, 6, 15, 8, 0, 0),
backup_at(2024, 6, 15, 9, 0, 0),
backup_at(2024, 6, 15, 10, 0, 0),
backup_at(2024, 6, 15, 11, 0, 0),
];
let plan = strategy.plan(&backups);
// Statuses should be in the same order as input
assert_eq!(plan.statuses.len(), 4);
assert!(matches!(plan.statuses[0].1, BackupStatus::Purgeable));
assert!(matches!(plan.statuses[1].1, BackupStatus::Purgeable));
assert!(matches!(plan.statuses[2].1, BackupStatus::Retainable));
assert!(matches!(plan.statuses[3].1, BackupStatus::Retainable));
}
#[test]
fn k_equals_count_keeps_all() {
let strategy = Strategy::most_recent(3);
let backups = vec![
backup_at(2024, 6, 15, 8, 0, 0),
backup_at(2024, 6, 15, 9, 0, 0),
backup_at(2024, 6, 15, 10, 0, 0),
];
let plan = strategy.plan(&backups);
assert!(plan.purgeable.is_empty());
assert_eq!(plan.retainable.len(), 3);
}
#[test]
fn k_zero_purges_all() {
let strategy = Strategy::most_recent(0);
let backups = vec![
backup_at(2024, 6, 15, 8, 0, 0),
backup_at(2024, 6, 15, 9, 0, 0),
];
let plan = strategy.plan(&backups);
assert_eq!(plan.purgeable.len(), 2);
assert!(plan.retainable.is_empty());
}
#[test]
fn handles_large_catalog() {
let strategy = Strategy::most_recent(10);
let backups = generate_hourly_backups(100);
let plan = strategy.plan(&backups);
assert_eq!(plan.purgeable.len(), 90);
assert_eq!(plan.retainable.len(), 10);
// Verify the retained ones are the most recent
for retained in &plan.retainable {
// The last 10 backups (indices 90-99)
assert!(backups[90..].contains(retained));
}
}
}
mod strategy_display {
use super::*;
#[test]
fn keep_most_recent_shows_count() {
let strategy = Strategy::most_recent(42);
assert_eq!(format!("{strategy}"), "KeepMostRecent: 42");
}
#[test]
fn classic_shows_name() {
let strategy = Strategy::Classic;
assert_eq!(format!("{strategy}"), "Classic");
}
}
mod strategy_constructors {
use super::*;
#[test]
fn most_recent_stores_k() {
let strategy = Strategy::most_recent(7);
match strategy {
Strategy::KeepMostRecent { k } => assert_eq!(k, 7),
_ => panic!("Expected KeepMostRecent variant"),
}
}
}
// Note: The Classic strategy uses `Local::now()` internally, making it
// non-deterministic and difficult to unit test reliably. To properly test
// Classic, consider refactoring `plan()` to accept a `now` parameter,
// or create an integration test with a controlled time environment.
//
// The Classic strategy logic groups backups by:
// - Hour (last 24h)
// - Day (last 7 days, excluding last 24h)
// - Week (last 4 weeks, excluding last 7 days)
// - Month (last year, excluding last 4 weeks)
//
// Each group keeps only the most recent backup within that time window.
}