chore: translate all Spanish comments and log messages to English

This commit is contained in:
Dionisio
2026-02-12 09:41:25 +01:00
parent bc169de8f6
commit d31a413e57
89 changed files with 2480 additions and 2482 deletions
+42 -42
View File
@@ -1,12 +1,12 @@
//! Puerto de persistencia del dominio para la entidad File.
//! Domain persistence port for the File entity.
//!
//! Define el contrato que cualquier implementación de almacenamiento de archivos
//! debe cumplir. Este trait vive en el dominio porque File es una entidad core
//! del sistema y sus contratos de persistencia pertenecen a la capa de dominio,
//! siguiendo los principios de Clean/Hexagonal Architecture.
//! Defines the contract that any file storage implementation must fulfill.
//! This trait lives in the domain because File is a core entity of the system
//! and its persistence contracts belong to the domain layer, following
//! Clean/Hexagonal Architecture principles.
//!
//! Las implementaciones concretas (filesystem, PostgreSQL, S3, etc.) viven en
//! la capa de infraestructura.
//! Concrete implementations (filesystem, PostgreSQL, S3, etc.) live in
//! the infrastructure layer.
use std::path::PathBuf;
use std::pin::Pin;
@@ -20,31 +20,31 @@ use crate::domain::services::path_service::StoragePath;
use crate::common::errors::DomainError;
// ─────────────────────────────────────────────────────
// FileReadRepository — operaciones de lectura/consulta
// FileReadRepository — read/query operations
// ─────────────────────────────────────────────────────
/// Puerto del dominio para **lectura** de archivos.
/// Domain port for file **reading**.
///
/// Encapsula toda operación que consulta estado sin modificarlo:
/// obtener, listar, contenido, stream, mmap, rango, resolución de rutas.
/// Encapsulates every operation that queries state without modifying it:
/// get, list, content, stream, mmap, range, path resolution.
#[async_trait]
pub trait FileReadRepository: Send + Sync + 'static {
/// Obtiene un archivo por su ID.
/// Gets a file by its ID.
async fn get_file(&self, id: &str) -> Result<File, DomainError>;
/// Lista archivos en una carpeta.
/// Lists files in a folder.
async fn list_files(&self, folder_id: Option<&str>) -> Result<Vec<File>, DomainError>;
/// Obtiene contenido completo como bytes (solo archivos pequeños/medianos).
/// Gets full content as bytes (only for small/medium files).
async fn get_file_content(&self, id: &str) -> Result<Vec<u8>, DomainError>;
/// Obtiene contenido como stream (ideal para archivos grandes).
/// Gets content as a stream (ideal for large files).
async fn get_file_stream(
&self,
id: &str,
) -> Result<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>, DomainError>;
/// Stream de un rango de bytes (HTTP Range Requests, video seek).
/// Stream of a byte range (HTTP Range Requests, video seek).
async fn get_file_range_stream(
&self,
id: &str,
@@ -52,27 +52,27 @@ pub trait FileReadRepository: Send + Sync + 'static {
end: Option<u64>,
) -> Result<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>, DomainError>;
/// Memory-map de archivo para acceso zero-copy (10–100 MB).
/// Memory-mapped file for zero-copy access (10–100 MB).
async fn get_file_mmap(&self, id: &str) -> Result<Bytes, DomainError>;
/// Obtiene la ruta de almacenamiento lógica de un archivo.
/// Gets the logical storage path of a file.
async fn get_file_path(&self, id: &str) -> Result<StoragePath, DomainError>;
/// Obtiene el ID de la carpeta padre a partir de una ruta (WebDAV).
/// Gets the parent folder ID from a path (WebDAV).
async fn get_parent_folder_id(&self, path: &str) -> Result<String, DomainError>;
}
// ─────────────────────────────────────────────────────
// FileWriteRepository — operaciones de escritura/mutación
// FileWriteRepository — write/mutation operations
// ─────────────────────────────────────────────────────
/// Puerto del dominio para **escritura** de archivos.
/// Domain port for file **writing**.
///
/// Cubre: upload (buffered + streaming), move, delete, update,
/// y el registro diferido para write-behind cache.
/// Covers: upload (buffered + streaming), move, delete, update,
/// and deferred registration for write-behind cache.
#[async_trait]
pub trait FileWriteRepository: Send + Sync + 'static {
/// Guarda un nuevo archivo desde bytes.
/// Saves a new file from bytes.
async fn save_file(
&self,
name: String,
@@ -81,7 +81,7 @@ pub trait FileWriteRepository: Send + Sync + 'static {
content: Vec<u8>,
) -> Result<File, DomainError>;
/// Upload en streaming — escribe chunks a disco sin acumular en RAM.
/// Streaming upload — writes chunks to disk without accumulating in RAM.
async fn save_file_from_stream(
&self,
name: String,
@@ -90,30 +90,30 @@ pub trait FileWriteRepository: Send + Sync + 'static {
stream: Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>,
) -> Result<File, DomainError>;
/// Mueve un archivo a otra carpeta.
/// Moves a file to another folder.
async fn move_file(
&self,
file_id: &str,
target_folder_id: Option<String>,
) -> Result<File, DomainError>;
/// Renombra un archivo (same folder, different name).
/// Renames a file (same folder, different name).
async fn rename_file(
&self,
file_id: &str,
new_name: &str,
) -> Result<File, DomainError>;
/// Elimina un archivo.
/// Deletes a file.
async fn delete_file(&self, id: &str) -> Result<(), DomainError>;
/// Actualiza el contenido de un archivo existente.
/// Updates the content of an existing file.
async fn update_file_content(&self, file_id: &str, content: Vec<u8>) -> Result<(), DomainError>;
/// Registra metadatos de archivo SIN escribir contenido a disco (write-behind).
/// Registers file metadata WITHOUT writing content to disk (write-behind).
///
/// Devuelve `(File, PathBuf)` donde `PathBuf` es la ruta destino para la
/// escritura diferida que realizará el `WriteBehindCache`.
/// Returns `(File, PathBuf)` where `PathBuf` is the destination path for
/// the deferred write that the `WriteBehindCache` will perform.
async fn register_file_deferred(
&self,
name: String,
@@ -124,27 +124,27 @@ pub trait FileWriteRepository: Send + Sync + 'static {
// ── Trash operations ──
/// Mueve un archivo a la papelera
/// Moves a file to the trash
async fn move_to_trash(&self, file_id: &str) -> Result<(), DomainError>;
/// Restaura un archivo desde la papelera a su ubicación original
/// Restores a file from the trash to its original location
async fn restore_from_trash(&self, file_id: &str, original_path: &str) -> Result<(), DomainError>;
/// Elimina un archivo permanentemente (usado por la papelera)
/// Permanently deletes a file (used by the trash)
async fn delete_file_permanently(&self, file_id: &str) -> Result<(), DomainError>;
}
// ─────────────────────────────────────────────────────
// FileRepository — supertrait unificado
// FileRepository — unified supertrait
// ─────────────────────────────────────────────────────
/// Puerto unificado para persistencia de archivos.
/// Unified port for file persistence.
///
/// Es un supertrait de `FileReadRepository + FileWriteRepository`.
/// Cualquier tipo que implemente ambos ports obtiene `FileRepository`
/// automáticamente vía blanket impl.
/// It is a supertrait of `FileReadRepository + FileWriteRepository`.
/// Any type that implements both ports gets `FileRepository`
/// automatically via blanket impl.
pub trait FileRepository: FileReadRepository + FileWriteRepository {}
/// Blanket implementation: cualquier tipo que implemente ambos ports
/// es automáticamente un FileRepository.
/// Blanket implementation: any type that implements both ports
/// is automatically a FileRepository.
impl<T: FileReadRepository + FileWriteRepository> FileRepository for T {}
+23 -23
View File
@@ -1,12 +1,12 @@
//! Puerto de persistencia del dominio para la entidad Folder.
//! Domain persistence port for the Folder entity.
//!
//! Define el contrato que cualquier implementación de almacenamiento de carpetas
//! debe cumplir. Este trait vive en el dominio porque Folder es una entidad core
//! del sistema y sus contratos de persistencia pertenecen a la capa de dominio,
//! siguiendo los principios de Clean/Hexagonal Architecture.
//! Defines the contract that any folder storage implementation
//! must fulfill. This trait lives in the domain because Folder is a core entity
//! of the system and its persistence contracts belong to the domain layer,
//! following the principles of Clean/Hexagonal Architecture.
//!
//! Las implementaciones concretas (filesystem, PostgreSQL, S3, etc.) viven en
//! la capa de infraestructura.
//! Concrete implementations (filesystem, PostgreSQL, S3, etc.) live in
//! the infrastructure layer.
use async_trait::async_trait;
@@ -14,25 +14,25 @@ use crate::domain::entities::folder::Folder;
use crate::domain::services::path_service::StoragePath;
use crate::common::errors::DomainError;
/// Puerto del dominio para persistencia de carpetas.
/// Domain port for folder persistence.
///
/// Define las operaciones CRUD y de gestión necesarias para
/// la entidad Folder en el sistema de almacenamiento.
/// Defines the CRUD and management operations required for
/// the Folder entity in the storage system.
#[async_trait]
pub trait FolderRepository: Send + Sync + 'static {
/// Crea una nueva carpeta
/// Creates a new folder
async fn create_folder(&self, name: String, parent_id: Option<String>) -> Result<Folder, DomainError>;
/// Obtiene una carpeta por su ID
/// Gets a folder by its ID
async fn get_folder(&self, id: &str) -> Result<Folder, DomainError>;
/// Obtiene una carpeta por su ruta de almacenamiento
/// Gets a folder by its storage path
async fn get_folder_by_path(&self, storage_path: &StoragePath) -> Result<Folder, DomainError>;
/// Lista carpetas dentro de una carpeta padre
/// Lists folders within a parent folder
async fn list_folders(&self, parent_id: Option<&str>) -> Result<Vec<Folder>, DomainError>;
/// Lista carpetas con paginación
/// Lists folders with pagination
async fn list_folders_paginated(
&self,
parent_id: Option<&str>,
@@ -41,29 +41,29 @@ pub trait FolderRepository: Send + Sync + 'static {
include_total: bool
) -> Result<(Vec<Folder>, Option<usize>), DomainError>;
/// Renombra una carpeta
/// Renames a folder
async fn rename_folder(&self, id: &str, new_name: String) -> Result<Folder, DomainError>;
/// Mueve una carpeta a otro padre
/// Moves a folder to another parent
async fn move_folder(&self, id: &str, new_parent_id: Option<&str>) -> Result<Folder, DomainError>;
/// Elimina una carpeta
/// Deletes a folder
async fn delete_folder(&self, id: &str) -> Result<(), DomainError>;
/// Verifica si existe una carpeta en la ruta dada
/// Checks if a folder exists at the given path
async fn folder_exists(&self, storage_path: &StoragePath) -> Result<bool, DomainError>;
/// Obtiene la ruta de una carpeta
/// Gets the path of a folder
async fn get_folder_path(&self, id: &str) -> Result<StoragePath, DomainError>;
// ── Trash operations ──
/// Mueve una carpeta a la papelera
/// Moves a folder to the trash
async fn move_to_trash(&self, folder_id: &str) -> Result<(), DomainError>;
/// Restaura una carpeta desde la papelera a su ubicación original
/// Restores a folder from the trash to its original location
async fn restore_from_trash(&self, folder_id: &str, original_path: &str) -> Result<(), DomainError>;
/// Elimina una carpeta permanentemente (usado por la papelera)
/// Permanently deletes a folder (used by the trash)
async fn delete_folder_permanently(&self, folder_id: &str) -> Result<(), DomainError>;
}
+11 -11
View File
@@ -4,19 +4,19 @@ use crate::common::errors::DomainError;
#[derive(Debug, thiserror::Error)]
pub enum SessionRepositoryError {
#[error("Sesión no encontrada: {0}")]
#[error("Session not found: {0}")]
NotFound(String),
#[error("Error de base de datos: {0}")]
#[error("Database error: {0}")]
DatabaseError(String),
#[error("Error de tiempo de espera: {0}")]
#[error("Timeout error: {0}")]
Timeout(String),
}
pub type SessionRepositoryResult<T> = Result<T, SessionRepositoryError>;
// Conversión de SessionRepositoryError a DomainError
// Conversion from SessionRepositoryError to DomainError
impl From<SessionRepositoryError> for DomainError {
fn from(err: SessionRepositoryError) -> Self {
match err {
@@ -35,24 +35,24 @@ impl From<SessionRepositoryError> for DomainError {
#[async_trait]
pub trait SessionRepository: Send + Sync + 'static {
/// Crea una nueva sesión
/// Creates a new session
async fn create_session(&self, session: Session) -> SessionRepositoryResult<Session>;
/// Obtiene una sesión por ID
/// Gets a session by ID
async fn get_session_by_id(&self, id: &str) -> SessionRepositoryResult<Session>;
/// Obtiene una sesión por token de actualización
/// Gets a session by refresh token
async fn get_session_by_refresh_token(&self, refresh_token: &str) -> SessionRepositoryResult<Session>;
/// Obtiene todas las sesiones de un usuario
/// Gets all sessions for a user
async fn get_sessions_by_user_id(&self, user_id: &str) -> SessionRepositoryResult<Vec<Session>>;
/// Revoca una sesión específica
/// Revokes a specific session
async fn revoke_session(&self, session_id: &str) -> SessionRepositoryResult<()>;
/// Revoca todas las sesiones de un usuario
/// Revokes all sessions for a user
async fn revoke_all_user_sessions(&self, user_id: &str) -> SessionRepositoryResult<u64>;
/// Elimina sesiones expiradas
/// Deletes expired sessions
async fn delete_expired_sessions(&self) -> SessionRepositoryResult<u64>;
}
+24 -24
View File
@@ -4,28 +4,28 @@ use crate::common::errors::DomainError;
#[derive(Debug, thiserror::Error)]
pub enum UserRepositoryError {
#[error("Usuario no encontrado: {0}")]
#[error("User not found: {0}")]
NotFound(String),
#[error("Usuario ya existe: {0}")]
#[error("User already exists: {0}")]
AlreadyExists(String),
#[error("Error de base de datos: {0}")]
#[error("Database error: {0}")]
DatabaseError(String),
#[error("Error de validación: {0}")]
#[error("Validation error: {0}")]
ValidationError(String),
#[error("Error de tiempo de espera: {0}")]
#[error("Timeout error: {0}")]
Timeout(String),
#[error("Operación no permitida: {0}")]
#[error("Operation not allowed: {0}")]
OperationNotAllowed(String),
}
pub type UserRepositoryResult<T> = Result<T, UserRepositoryError>;
// Conversión de UserRepositoryError a DomainError
// Conversion from UserRepositoryError to DomainError
impl From<UserRepositoryError> for DomainError {
fn from(err: UserRepositoryError) -> Self {
match err {
@@ -53,59 +53,59 @@ impl From<UserRepositoryError> for DomainError {
#[async_trait]
pub trait UserRepository: Send + Sync + 'static {
/// Crea un nuevo usuario
/// Creates a new user
async fn create_user(&self, user: User) -> UserRepositoryResult<User>;
/// Obtiene un usuario por ID
/// Gets a user by ID
async fn get_user_by_id(&self, id: &str) -> UserRepositoryResult<User>;
/// Obtiene un usuario por nombre de usuario
/// Gets a user by username
async fn get_user_by_username(&self, username: &str) -> UserRepositoryResult<User>;
/// Obtiene un usuario por correo electrónico
/// Gets a user by email
async fn get_user_by_email(&self, email: &str) -> UserRepositoryResult<User>;
/// Actualiza un usuario existente
/// Updates an existing user
async fn update_user(&self, user: User) -> UserRepositoryResult<User>;
/// Actualiza solo el uso de almacenamiento de un usuario
/// Updates only a user's storage usage
async fn update_storage_usage(&self, user_id: &str, usage_bytes: i64) -> UserRepositoryResult<()>;
/// Actualiza la fecha de último inicio de sesión
/// Updates the last login date
async fn update_last_login(&self, user_id: &str) -> UserRepositoryResult<()>;
/// Lista usuarios con paginación
/// Lists users with pagination
async fn list_users(&self, limit: i64, offset: i64) -> UserRepositoryResult<Vec<User>>;
/// Activa o desactiva un usuario
/// Activates or deactivates a user
async fn set_user_active_status(&self, user_id: &str, active: bool) -> UserRepositoryResult<()>;
/// Cambia la contraseña de un usuario
/// Changes a user's password
async fn change_password(&self, user_id: &str, password_hash: &str) -> UserRepositoryResult<()>;
/// Cambia el rol de un usuario
/// Changes a user's role
async fn change_role(&self, user_id: &str, role: UserRole) -> UserRepositoryResult<()>;
/// Lista usuarios por rol (admin o user)
/// Lists users by role (admin or user)
async fn list_users_by_role(&self, role: &str) -> UserRepositoryResult<Vec<User>>;
/// Elimina un usuario
/// Deletes a user
async fn delete_user(&self, user_id: &str) -> UserRepositoryResult<()>;
/// Finds a user by OIDC provider + subject pair
async fn get_user_by_oidc_subject(&self, provider: &str, subject: &str) -> UserRepositoryResult<User>;
/// Actualiza la cuota de almacenamiento de un usuario
/// Updates a user's storage quota
async fn update_storage_quota(&self, user_id: &str, quota_bytes: i64) -> UserRepositoryResult<()>;
/// Cuenta el número total de usuarios
/// Counts the total number of users
async fn count_users(&self) -> UserRepositoryResult<i64>;
/// Obtiene estadísticas de almacenamiento agregadas
/// Gets aggregated storage statistics
async fn get_storage_stats(&self) -> UserRepositoryResult<StorageStats>;
}
/// Estadísticas de almacenamiento agregadas
/// Aggregated storage statistics
#[derive(Debug, Clone)]
pub struct StorageStats {
pub total_users: i64,