adding comments, moving technical documentation, improve Dockerfile, delete unuseful files

This commit is contained in:
dionidev
2025-03-30 14:17:09 +00:00
parent b2d989fbe3
commit e79ca8304b
30 changed files with 461 additions and 1537 deletions
@@ -5,19 +5,19 @@ use tracing::{debug, error, instrument};
use crate::domain::repositories::file_repository::FileRepositoryResult;
use crate::infrastructure::repositories::file_fs_repository::FileFsRepository;
// Este archivo contiene la implementación de los métodos relacionados con la papelera
// para el repositorio de archivos FileFsRepository
// This file contains the implementation of trash-related methods
// for the FileFsRepository file repository
// Implementación de métodos de papelera para el repositorio de archivos
// Implementation of trash methods for the file repository
impl FileFsRepository {
// Obtiene la ruta completa a la papelera
// Gets the complete path to the trash directory
fn get_trash_dir(&self) -> PathBuf {
let trash_dir = self.get_root_path().join(".trash").join("files");
debug!("Base trash directory: {}", trash_dir.display());
trash_dir
}
// Obtiene la ruta de la papelera para un usuario específico (si se proporciona)
// Gets the trash directory path for a specific user (if provided)
fn get_user_trash_dir(&self, user_id: Option<&str>) -> PathBuf {
let base_trash_dir = self.get_trash_dir();
@@ -33,7 +33,7 @@ impl FileFsRepository {
}
}
// Crea una ruta única en la papelera para el archivo
// Creates a unique path in the trash for the file
async fn create_trash_file_path(&self, file_id: &str) -> FileRepositoryResult<PathBuf> {
debug!("Creating trash file path for file ID: {}", file_id);
@@ -62,7 +62,7 @@ impl FileFsRepository {
}
}
// Implementación de los métodos públicos del trait FileRepository relacionados con la papelera
// Implementation of the public methods of the FileRepository trait related to trash
// Note: The FileRepository trait implementation has been moved to file_fs_repository.rs
// to avoid duplicate implementations
@@ -70,101 +70,101 @@ impl FileFsRepository {
impl FileFsRepository {
/// Helper method that will be used for trash functionality
pub(crate) async fn _trash_move_to_trash(&self, file_id: &str) -> FileRepositoryResult<()> {
debug!("Moviendo archivo a la papelera: {}", file_id);
debug!("Moving file to trash: {}", file_id);
// Obtener la ruta física del archivo
// Creamos un método independiente para acceder al servicio de mapeo de IDs
debug!("Obteniendo ruta del archivo con ID: {}", file_id);
// Get the physical path of the file
// We create an independent method to access the ID mapping service
debug!("Getting file path with ID: {}", file_id);
let file_path = match self.id_mapping_service().get_file_path(file_id).await {
Ok(path) => {
debug!("Ruta del archivo obtenida: {}", path.display());
debug!("File path obtained: {}", path.display());
path
},
Err(e) => {
error!("Error obteniendo ruta del archivo {}: {:?}", file_id, e);
error!("Error getting file path {}: {:?}", file_id, e);
return Err(FileRepositoryError::IdMappingError(format!("Failed to get file path: {}", e)));
}
};
// Verificamos que el archivo existe
debug!("Verificando que el archivo existe: {}", file_path.display());
// Verify that the file exists
debug!("Verifying that the file exists: {}", file_path.display());
if !self.file_exists(&file_path).await? {
error!("Archivo no encontrado en la ruta especificada: {}", file_path.display());
error!("File not found at the specified path: {}", file_path.display());
return Err(FileRepositoryError::NotFound(format!("File not found: {}", file_id)));
}
debug!("Archivo encontrado, continuando con la operación");
debug!("File found, continuing with the operation");
// Crear directorio en la papelera si no existe
debug!("Creando path para archivo en papelera");
// Create directory in trash if it doesn't exist
debug!("Creating path for file in trash");
let trash_file_path = self.create_trash_file_path(file_id).await?;
debug!("Path en papelera: {}", trash_file_path.display());
debug!("Path in trash: {}", trash_file_path.display());
// Mover el archivo físicamente a la papelera (no actualiza mappings)
debug!("Moviendo archivo físicamente a papelera: {} -> {}", file_path.display(), trash_file_path.display());
// Physically move the file to trash (doesn't update mappings)
debug!("Physically moving file to trash: {} -> {}", file_path.display(), trash_file_path.display());
match fs::rename(&file_path, &trash_file_path).await {
Ok(_) => {
debug!("Archivo movido a papelera exitosamente: {} -> {}", file_path.display(), trash_file_path.display());
debug!("File successfully moved to trash: {} -> {}", file_path.display(), trash_file_path.display());
// Invalidar la caché del archivo original
debug!("Invalidando caché para: {}", file_path.display());
// Invalidate the cache for the original file
debug!("Invalidating cache for: {}", file_path.display());
self.metadata_cache().invalidate(&file_path).await;
// Actualizar el mapeo al nuevo path en la papelera
debug!("Actualizando mapeo de ID a nuevo path en papelera");
// Update the mapping to the new path in trash
debug!("Updating ID mapping to new path in trash");
if let Err(e) = self.id_mapping_service().update_file_path(file_id, &trash_file_path).await {
error!("Error actualizando mapeo de archivo en papelera: {}", e);
error!("Error updating file mapping in trash: {}", e);
return Err(FileRepositoryError::MappingError(format!("Failed to update mapping: {}", e)));
}
debug!("Mapeo actualizado exitosamente");
debug!("Mapping successfully updated");
debug!("Operación de mover a papelera completada con éxito para el archivo: {}", file_id);
debug!("Move to trash operation completed successfully for file: {}", file_id);
Ok(())
},
Err(e) => {
error!("Error moviendo archivo a papelera: {} -> {}: {}",
error!("Error moving file to trash: {} -> {}: {}",
file_path.display(), trash_file_path.display(), e);
Err(FileRepositoryError::IoError(e))
}
}
}
/// Restaura un archivo desde la papelera a su ubicación original
/// Restores a file from trash to its original location
#[instrument(skip(self))]
pub(crate) async fn _trash_restore_from_trash(&self, file_id: &str, original_path: &str) -> FileRepositoryResult<()> {
debug!("Restaurando archivo {} a {}", file_id, original_path);
debug!("Restoring file {} to {}", file_id, original_path);
// Try to get the current path from the ID mapping service
let current_path_result = self.id_mapping_service().get_file_path(file_id).await;
match current_path_result {
Ok(current_path) => {
debug!("Ruta actual en papelera: {}", current_path.display());
debug!("Current path in trash: {}", current_path.display());
// Check if the file exists in the trash
let file_exists = match fs::metadata(&current_path).await {
Ok(_) => {
debug!("Archivo existe en papelera");
debug!("File exists in trash");
true
},
Err(e) => {
debug!("Archivo no existe en papelera: {} - {}", current_path.display(), e);
debug!("File does not exist in trash: {} - {}", current_path.display(), e);
false
}
};
if !file_exists {
error!("El archivo no existe físicamente en la papelera: {}", current_path.display());
error!("The file does not physically exist in the trash: {}", current_path.display());
return Err(FileRepositoryError::NotFound(format!("File not found in trash: {}", file_id)));
}
// Parse the original path to a PathBuf
let original_path_buf = PathBuf::from(original_path);
debug!("Ruta original para restauración: {}", original_path_buf.display());
debug!("Original path for restoration: {}", original_path_buf.display());
// Check if a file already exists at the destination
let target_exists = fs::metadata(&original_path_buf).await.is_ok();
if target_exists {
debug!("Ya existe un archivo en la ruta de destino, generando ruta alternativa");
debug!("A file already exists at the destination path, generating alternative path");
// Generate a unique path by adding a suffix
// Extract filename and extension
@@ -187,16 +187,16 @@ impl FileFsRepository {
// Create the alternative path
let alternative_path = parent_dir.join(new_name);
debug!("Ruta alternativa para restauración: {}", alternative_path.display());
debug!("Alternative path for restoration: {}", alternative_path.display());
// Ensure the parent directory exists
if let Some(parent) = alternative_path.parent() {
if !parent.exists() {
debug!("Creando directorio padre para restauración: {}", parent.display());
debug!("Creating parent directory for restoration: {}", parent.display());
match fs::create_dir_all(parent).await {
Ok(_) => debug!("Directorio padre creado exitosamente"),
Ok(_) => debug!("Parent directory created successfully"),
Err(e) => {
error!("Error creando directorio padre: {} - {}", parent.display(), e);
error!("Error creating parent directory: {} - {}", parent.display(), e);
return Err(FileRepositoryError::IoError(e));
}
}
@@ -204,30 +204,30 @@ impl FileFsRepository {
}
// Move the file from trash to the alternative location
debug!("Moviendo archivo de papelera a ubicación alternativa: {} -> {}",
debug!("Moving file from trash to alternative location: {} -> {}",
current_path.display(), alternative_path.display());
match fs::rename(&current_path, &alternative_path).await {
Ok(_) => {
debug!("Archivo restaurado exitosamente a ubicación alternativa");
debug!("File successfully restored to alternative location");
// Invalidate cache entries
debug!("Invalidando caché para archivo en papelera");
debug!("Invalidating cache for file in trash");
self.metadata_cache().invalidate(&current_path).await;
// Update the ID mapping
debug!("Actualizando mapeo de ID a nueva ubicación");
debug!("Updating ID mapping to new location");
if let Err(e) = self.id_mapping_service().update_file_path(file_id, &alternative_path).await {
error!("Error actualizando mapeo de archivo restaurado: {}", e);
error!("Error updating mapping of restored file: {}", e);
return Err(FileRepositoryError::MappingError(
format!("Failed to update mapping: {}", e)
));
}
debug!("Restauración a ubicación alternativa completada con éxito");
debug!("Restoration to alternative location completed successfully");
Ok(())
},
Err(e) => {
error!("Error restaurando archivo a ubicación alternativa: {}", e);
error!("Error restoring file to alternative location: {}", e);
Err(FileRepositoryError::IoError(e))
}
}
@@ -235,11 +235,11 @@ impl FileFsRepository {
// Ensure the parent directory exists
if let Some(parent) = original_path_buf.parent() {
if !parent.exists() {
debug!("Creando directorio padre para restauración: {}", parent.display());
debug!("Creating parent directory for restoration: {}", parent.display());
match fs::create_dir_all(parent).await {
Ok(_) => debug!("Directorio padre creado exitosamente"),
Ok(_) => debug!("Parent directory created successfully"),
Err(e) => {
error!("Error creando directorio padre: {} - {}", parent.display(), e);
error!("Error creating parent directory: {} - {}", parent.display(), e);
return Err(FileRepositoryError::IoError(e));
}
}
@@ -247,41 +247,41 @@ impl FileFsRepository {
}
// Move the file from trash to its original location
debug!("Moviendo archivo de papelera a ubicación original: {} -> {}",
debug!("Moving file from trash to original location: {} -> {}",
current_path.display(), original_path_buf.display());
match fs::rename(&current_path, &original_path_buf).await {
Ok(_) => {
debug!("Archivo restaurado exitosamente a ubicación original");
debug!("File successfully restored to original location");
// Invalidate cache entries
debug!("Invalidando caché para archivo en papelera");
debug!("Invalidating cache for file in trash");
self.metadata_cache().invalidate(&current_path).await;
// Update the ID mapping
debug!("Actualizando mapeo de ID a ubicación original");
debug!("Updating ID mapping to original location");
if let Err(e) = self.id_mapping_service().update_file_path(file_id, &original_path_buf).await {
error!("Error actualizando mapeo de archivo restaurado: {}", e);
error!("Error updating mapping of restored file: {}", e);
return Err(FileRepositoryError::MappingError(
format!("Failed to update mapping: {}", e)
));
}
debug!("Restauración a ubicación original completada con éxito");
debug!("Restoration to original location completed successfully");
Ok(())
},
Err(e) => {
error!("Error restaurando archivo a ubicación original: {}", e);
error!("Error restoring file to original location: {}", e);
Err(FileRepositoryError::IoError(e))
}
}
}
},
Err(e) => {
error!("Error obteniendo ruta actual del archivo {}: {:?}", file_id, e);
error!("Error getting current path of file {}: {:?}", file_id, e);
// Check if the error is because the ID was not found
if format!("{}", e).contains("not found") {
debug!("ID no encontrado en mapeo, archivo ya no existe en papelera");
debug!("ID not found in mapping, file no longer exists in trash");
return Err(FileRepositoryError::NotFound(format!("File not found in trash: {}", file_id)));
}
@@ -292,48 +292,48 @@ impl FileFsRepository {
}
}
/// Elimina un archivo permanentemente (usado por la papelera)
/// Permanently deletes a file (used by trash)
#[instrument(skip(self))]
pub(crate) async fn _trash_delete_file_permanently(&self, file_id: &str) -> FileRepositoryResult<()> {
debug!("Eliminando archivo permanentemente: {}", file_id);
debug!("Permanently deleting file: {}", file_id);
// Get the file path using the ID mapping service
let file_path_result = self.id_mapping_service().get_file_path(file_id).await;
match file_path_result {
Ok(file_path) => {
debug!("Encontrada ruta para archivo: {} -> {}", file_id, file_path.display());
debug!("Found path for file: {} -> {}", file_id, file_path.display());
// Check if the file physically exists before attempting to delete
let file_exists = fs::metadata(&file_path).await.is_ok();
if file_exists {
debug!("Archivo existe físicamente, eliminando: {}", file_path.display());
debug!("File exists physically, deleting: {}", file_path.display());
// Delete the file physically
if let Err(e) = fs::remove_file(&file_path).await {
error!("Error eliminando archivo permanentemente: {} - {}", file_path.display(), e);
error!("Error permanently deleting file: {} - {}", file_path.display(), e);
// Don't report error if the file already doesn't exist
if e.kind() != std::io::ErrorKind::NotFound {
return Err(FileRepositoryError::IoError(e));
}
} else {
debug!("Archivo eliminado físicamente con éxito");
debug!("File physically deleted successfully");
}
// Invalidate cache for this file
debug!("Invalidando caché para el archivo: {}", file_path.display());
debug!("Invalidating cache for file: {}", file_path.display());
self.metadata_cache().invalidate(&file_path).await;
} else {
debug!("Archivo no existe físicamente, solo limpiando mapeos: {}", file_path.display());
debug!("File does not exist physically, only cleaning mappings: {}", file_path.display());
}
// Always remove the ID mapping regardless of whether the file exists
debug!("Eliminando mapeo de ID: {}", file_id);
debug!("Removing ID mapping: {}", file_id);
match self.id_mapping_service().remove_id(file_id).await {
Ok(_) => debug!("Mapeo de ID eliminado con éxito"),
Ok(_) => debug!("ID mapping successfully removed"),
Err(e) => {
error!("Error eliminando mapeo del archivo: {}", e);
error!("Error removing file mapping: {}", e);
// Only return error for critical mapping errors, otherwise continue
if format!("{}", e).contains("not found") {
debug!("ID mapping not found, ignoring this error for deletion");
@@ -343,16 +343,16 @@ impl FileFsRepository {
}
};
debug!("Archivo eliminado permanentemente con éxito: {}", file_id);
debug!("File permanently deleted successfully: {}", file_id);
Ok(())
},
Err(e) => {
// This could happen if the file is already deleted or wasn't properly indexed
error!("Error obteniendo ruta del archivo {}: {:?}", file_id, e);
error!("Error getting file path {}: {:?}", file_id, e);
// Check if the error is because the ID was not found
if format!("{}", e).contains("not found") {
debug!("ID no encontrado en mapeo, considerando borrado exitoso: {}", file_id);
debug!("ID not found in mapping, considering deletion successful: {}", file_id);
// In this case, we consider the file already deleted
return Ok(());
}
@@ -363,5 +363,5 @@ impl FileFsRepository {
}
}
// Re-exportaciones necesarias para el compilador
// Re-exports needed for the compiler
use crate::domain::repositories::file_repository::FileRepositoryError;