@@ -5,6 +5,8 @@ use tokio::io;
55use std:: collections:: HashMap ;
66use std:: path:: { Path , PathBuf } ;
77
8+ use crate :: util:: msec_to_log2_filename;
9+
810#[ derive( Debug , Clone ) ]
911pub ( crate ) struct LogFile {
1012 pub ( crate ) name : PathBuf ,
@@ -40,11 +42,11 @@ pub(crate) async fn collect_log2_files(dir: impl AsRef<Path>) -> io::Result<Vec<
4042}
4143
4244/// Prune `.log2` files while keeping the newest one per directory
43- pub ( crate ) async fn cleanup_log2_files ( dir : impl AsRef < Path > , size_limit : u64 ) -> io:: Result < ( ) > {
45+ pub ( crate ) async fn cleanup_log2_files ( dir : impl AsRef < Path > , size_limit : u64 , days_to_keep : i64 ) -> io:: Result < ( ) > {
4446 let files = collect_log2_files ( dir. as_ref ( ) ) . await ?;
4547 let mut files_size: u64 = files. iter ( ) . map ( |f| f. size ) . sum ( ) ;
4648
47- info ! ( "log2 files size: {files_size}, size limit: {size_limit}" ) ;
49+ info ! ( "log2 files size: {files_size}, size limit: {size_limit}, days_to_keep: {days_to_keep} " ) ;
4850 if files_size < size_limit {
4951 info ! ( "Size limit not hit, nothing to cleanup" ) ;
5052 return Ok ( ( ) ) ;
@@ -58,11 +60,15 @@ pub(crate) async fn cleanup_log2_files(dir: impl AsRef<Path>, size_limit: u64) -
5860
5961 let mut deletable_files = Vec :: new ( ) ;
6062
63+ // This file doesn't have to exist, I'm only constructing the filename for log retention.
64+ let oldest_file_to_keep = PathBuf :: from ( msec_to_log2_filename ( shvproto:: DateTime :: now ( ) . add_days ( -days_to_keep) . epoch_msec ( ) ) ) ;
65+ info ! ( "keeping files younger than {filename}" , filename = oldest_file_to_keep. to_string_lossy( ) ) ;
66+
6167 for ( _dir, mut group) in grouped {
6268 // Sort descending (newest first)
6369 group. sort_by ( |a, b| b. name . cmp ( & a. name ) ) ;
64- // Keep the newest file
65- deletable_files. extend ( group. into_iter ( ) . skip ( 1 ) ) ;
70+ // Keep the newest file, and keep files newer than oldest_file_to_delete
71+ deletable_files. extend ( group. into_iter ( ) . skip ( 1 ) . filter ( |log_file| log_file . name < oldest_file_to_keep ) ) ;
6672 }
6773
6874 // Sort deletable files (oldest first for deletion)
0 commit comments