diff --git a/src/main.rs b/src/main.rs index 532b071..30ea07a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,7 +4,7 @@ mod utils; use models::CloudS3; use std::fs; -use utils::{delete_old_files, delete_old_local_files, handle_bucket_contents, list_all_buckets}; +use utils::{handle_bucket_contents, keep_last_n_local_files, list_all_buckets}; use crate::utils::s3_utils::{create_client, create_config}; @@ -91,20 +91,13 @@ async fn run_clean_and_backup() -> Result<(), Box> { Err(e) => eprintln!("Hiba a bucket listázásakor: {}", e), } - // 14 napnál régebbi fájlok törlése - match delete_old_files(&client, &bucket_cloud, 14).await { - Ok(count) => { - if count > 0 { - println!("{} régi fájl törölve a {} bucket-ből", count, bucket_name); - } - } - Err(e) => eprintln!("Hiba a régi fájlok törlésekor: {}", e), - } + // Az S3-on lévő fájlokat NEM töröljük, csak letöltjük. + // A takarítás kizárólag lokálisan történik (lásd lentebb). } } - // Helyi régi fájlok törlése a db_backup mappából - match delete_old_local_files("./db_backup", 14) { + // Helyi takarítás: mappánként csak a legutolsó 14 mentés marad meg + match keep_last_n_local_files("./db_backup", 14) { Ok(count) => { if count > 0 { println!("{} régi helyi fájl törölve a db_backup mappából", count); diff --git a/src/utils/file_utils.rs b/src/utils/file_utils.rs index d83e49b..6111cc9 100644 --- a/src/utils/file_utils.rs +++ b/src/utils/file_utils.rs @@ -1,11 +1,12 @@ use std::fs; use std::path::Path; -use std::time::{Duration, SystemTime}; +use std::time::SystemTime; use crate::models::S3Item; -pub fn delete_old_local_files(dir: &str, days: u64) -> std::io::Result { - let cutoff = SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60); +/// Minden (fájlokat tartalmazó) mappában csak a legfrissebb `keep` darab fájlt +/// hagyja meg, a régebbieket törli. Mappánként külön számolja a darabszámot. +pub fn keep_last_n_local_files(dir: &str, keep: usize) -> std::io::Result { let root = Path::new(dir); if !root.exists() { @@ -15,10 +16,9 @@ pub fn delete_old_local_files(dir: &str, days: u64) -> std::io::Result { let mut deleted_count = 0; - // Első menet: régi fájlok törlése - delete_old_files_recursive(root, cutoff, &mut deleted_count)?; + keep_last_n_recursive(root, keep, &mut deleted_count)?; - // Második menet: üres mappák törlése (bottom-up), de a gyökeret meghagyjuk + // Üres mappák törlése (a gyökeret meghagyjuk) for entry in fs::read_dir(root)? { let entry = entry?; if entry.path().is_dir() { @@ -28,46 +28,55 @@ pub fn delete_old_local_files(dir: &str, days: u64) -> std::io::Result { if deleted_count > 0 { println!( - "Helyi törlés kész: {} fájl törölve ({} napnál régebbiek) a {} mappából", - deleted_count, days, dir + "Helyi törlés kész: {} fájl törölve (csak a legutolsó {} mentés marad mappánként) a {} mappából", + deleted_count, keep, dir ); } Ok(deleted_count) } -fn delete_old_files_recursive( +fn keep_last_n_recursive( dir: &Path, - cutoff: SystemTime, + keep: usize, deleted_count: &mut usize, ) -> std::io::Result<()> { if !dir.is_dir() { return Ok(()); } + // Az aktuális mappa fájljai (módosítási idővel együtt) + let mut files: Vec<(std::path::PathBuf, SystemTime)> = Vec::new(); + for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { - delete_old_files_recursive(&path, cutoff, deleted_count)?; - } else if path.is_file() - && let Ok(metadata) = fs::metadata(&path) - && let Ok(modified) = metadata.modified() - && modified < cutoff - { - match fs::remove_file(&path) { - Ok(_) => { - println!("🗑 Helyi fájl törölve: {}", path.display()); - *deleted_count += 1; - } - Err(e) => { - eprintln!( - "Hiba a helyi fájl törlésekor: {} - {}", - path.display(), - e - ); - } + keep_last_n_recursive(&path, keep, deleted_count)?; + } else if path.is_file() { + let modified = fs::metadata(&path) + .and_then(|m| m.modified()) + .unwrap_or(SystemTime::UNIX_EPOCH); + files.push((path, modified)); + } + } + + if files.len() <= keep { + return Ok(()); + } + + // Legfrissebb elöl, a `keep` utániakat töröljük + files.sort_by(|a, b| b.1.cmp(&a.1)); + + for (path, _) in files.into_iter().skip(keep) { + match fs::remove_file(&path) { + Ok(_) => { + println!("🗑 Helyi fájl törölve: {}", path.display()); + *deleted_count += 1; + } + Err(e) => { + eprintln!("Hiba a helyi fájl törlésekor: {} - {}", path.display(), e); } } } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 5a09412..8b51740 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,6 +1,5 @@ pub mod file_utils; pub mod s3_utils; -pub use file_utils::delete_old_local_files; -pub use s3_utils::delete_old_files; +pub use file_utils::keep_last_n_local_files; pub use s3_utils::handle_bucket_contents; pub use s3_utils::list_all_buckets; diff --git a/src/utils/s3_utils.rs b/src/utils/s3_utils.rs index 5f96f79..e3fb09d 100644 --- a/src/utils/s3_utils.rs +++ b/src/utils/s3_utils.rs @@ -5,7 +5,6 @@ use crate::models::S3Item; use aws_config::BehaviorVersion; use aws_sdk_s3::config::{Credentials, Region}; use aws_sdk_s3::{Client, Error}; -use chrono::{DateTime, Duration, Utc}; use futures::stream::{self, StreamExt}; pub fn create_config(s3: &CloudS3) -> aws_sdk_s3::Config { @@ -175,49 +174,3 @@ pub async fn handle_bucket_contents( Ok(()) } - -/// Törli a 14 napnál régebbi fájlokat a bucket-ből -pub async fn delete_old_files( - client: &Client, - s3: &CloudS3, - days: i64, -) -> Result> { - let items = list_bucket(client, s3).await?; - let cutoff_date = Utc::now() - Duration::days(days); - - let mut deleted_count = 0; - - for item in items.iter().filter(|i| !i.is_folder) { - if let Some(last_modified_str) = &item.last_modified { - // AWS SDK DateTime formátum: "2024-01-15T10:30:00Z" - if let Ok(last_modified) = DateTime::parse_from_rfc3339(last_modified_str) { - let last_modified_utc: DateTime = last_modified.into(); - - if last_modified_utc < cutoff_date { - match client - .delete_object() - .bucket(&s3.bucket) - .key(&item.key) - .send() - .await - { - Ok(_) => { - println!("🗑 Törölve: {} ({})", item.key, last_modified_str); - deleted_count += 1; - } - Err(e) => { - eprintln!("Hiba a törléskor: {} - {}", item.key, e); - } - } - } - } - } - } - - println!( - "Törlés kész: {} fájl törölve ({} napnál régebbiek)", - deleted_count, days - ); - - Ok(deleted_count) -}