fix: critical bugs from deep audit

- Fix copy_files() data loss: implement real copy_file across full stack
  (FileWritePort, FileManagementUseCase, stubs, service, repository with
  atomic CTE + dedup ref_count increment, batch_operations caller)
- Fix plaintext password in replace_default_admin: hash password via
  PasswordHasherPort before User::new()
- Fix CalendarService hardcoded user_id: unify CalendarUseCase trait with
  explicit user_id parameter on all methods, remove zombie _for_user
  duplicates and hardcoded 'current_user_id', update 20 CalDAV handler
  call sites
- Previous session: migrate DedupService to PostgreSQL (storage.blobs),
  atomic CTEs with compensation for file/folder repository operations
This commit is contained in:
Dionisio
2026-02-14 20:22:19 +01:00
parent 3179e1dd91
commit fac0b5e77b
17 changed files with 2163 additions and 2185 deletions
+34 -57
View File
@@ -106,23 +106,33 @@ pub trait CalendarStoragePort: Send + Sync + 'static {
) -> Result<Vec<CalendarEventDto>, DomainError>;
}
/// Port for calendar use cases
/// Port for calendar use cases.
///
/// All methods require an explicit `user_id` parameter for authorization.
/// The CalDAV protocol handler extracts the user identity from JWT claims
/// and passes it through.
#[async_trait]
pub trait CalendarUseCase: Send + Sync + 'static {
// Calendar operations
async fn create_calendar(
&self,
calendar: CreateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError>;
async fn update_calendar(
&self,
calendar_id: &str,
update: UpdateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError>;
async fn delete_calendar(&self, calendar_id: &str) -> Result<(), DomainError>;
async fn get_calendar(&self, calendar_id: &str) -> Result<CalendarDto, DomainError>;
async fn list_my_calendars(&self) -> Result<Vec<CalendarDto>, DomainError>;
async fn list_shared_calendars(&self) -> Result<Vec<CalendarDto>, DomainError>;
async fn delete_calendar(&self, calendar_id: &str, user_id: &str) -> Result<(), DomainError>;
async fn get_calendar(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<CalendarDto, DomainError>;
async fn list_my_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError>;
async fn list_shared_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError>;
async fn list_public_calendars(
&self,
limit: Option<i64>,
@@ -133,90 +143,57 @@ pub trait CalendarUseCase: Send + Sync + 'static {
async fn share_calendar(
&self,
calendar_id: &str,
user_id: &str,
target_user_id: &str,
access_level: &str,
caller_user_id: &str,
) -> Result<(), DomainError>;
async fn remove_calendar_sharing(
&self,
calendar_id: &str,
user_id: &str,
target_user_id: &str,
caller_user_id: &str,
) -> Result<(), DomainError>;
async fn get_calendar_shares(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<Vec<(String, String)>, DomainError>;
// Event operations
async fn create_event(&self, event: CreateEventDto) -> Result<CalendarEventDto, DomainError>;
async fn create_event(
&self,
event: CreateEventDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError>;
async fn create_event_from_ical(
&self,
event: CreateEventICalDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError>;
async fn update_event(
&self,
event_id: &str,
update: UpdateEventDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError>;
async fn delete_event(&self, event_id: &str, user_id: &str) -> Result<(), DomainError>;
async fn get_event(
&self,
event_id: &str,
user_id: &str,
) -> Result<CalendarEventDto, DomainError>;
async fn delete_event(&self, event_id: &str) -> Result<(), DomainError>;
async fn get_event(&self, event_id: &str) -> Result<CalendarEventDto, DomainError>;
async fn list_events(
&self,
calendar_id: &str,
limit: Option<i64>,
offset: Option<i64>,
user_id: &str,
) -> Result<Vec<CalendarEventDto>, DomainError>;
async fn get_events_in_range(
&self,
calendar_id: &str,
start: DateTime<Utc>,
end: DateTime<Utc>,
) -> Result<Vec<CalendarEventDto>, DomainError>;
// ─── User-contextualized variants (for CalDAV protocol handler) ──
async fn create_calendar_for_user(
&self,
calendar: CreateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError>;
async fn update_calendar_for_user(
&self,
calendar_id: &str,
update: UpdateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError>;
async fn delete_calendar_for_user(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<(), DomainError>;
async fn get_calendar_for_user(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<CalendarDto, DomainError>;
async fn list_my_calendars_for_user(
&self,
user_id: &str,
) -> Result<Vec<CalendarDto>, DomainError>;
async fn list_events_for_user(
&self,
calendar_id: &str,
limit: Option<i64>,
offset: Option<i64>,
user_id: &str,
) -> Result<Vec<CalendarEventDto>, DomainError>;
async fn get_events_in_range_for_user(
&self,
calendar_id: &str,
start: DateTime<Utc>,
end: DateTime<Utc>,
user_id: &str,
) -> Result<Vec<CalendarEventDto>, DomainError>;
async fn create_event_from_ical_for_user(
&self,
event: CreateEventICalDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError>;
async fn delete_event_for_user(&self, event_id: &str, user_id: &str)
-> Result<(), DomainError>;
}
+7
View File
@@ -138,6 +138,13 @@ pub trait FileManagementUseCase: Send + Sync + 'static {
folder_id: Option<String>,
) -> Result<FileDto, DomainError>;
/// Copies a file to another folder (zero-copy with dedup).
async fn copy_file(
&self,
file_id: &str,
target_folder_id: Option<String>,
) -> Result<FileDto, DomainError>;
/// Renames a file
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError>;
+10
View File
@@ -115,6 +115,16 @@ pub trait FileWritePort: Send + Sync + 'static {
size: u64,
) -> Result<(File, PathBuf), DomainError>;
/// Copies a file to a (possibly different) folder.
///
/// With blob-dedup, this only creates a new metadata row and increments
/// the blob reference count — zero disk I/O for the content.
async fn copy_file(
&self,
file_id: &str,
target_folder_id: Option<String>,
) -> Result<File, DomainError>;
// ── Trash operations ──
/// Moves a file to the trash
@@ -168,7 +168,7 @@ impl AuthApplicationService {
/// Returns whether OIDC is configured and enabled
pub fn oidc_enabled(&self) -> bool {
let state = self.oidc.read().unwrap();
state.service.is_some() && state.config.as_ref().is_some_and(|c| c.enabled)
state.service.is_some() && state.config.as_ref().map_or(false, |c| c.enabled)
}
/// Returns whether password login is disabled (OIDC-only mode)
@@ -177,7 +177,7 @@ impl AuthApplicationService {
state
.config
.as_ref()
.is_some_and(|c| c.disable_password_login)
.map_or(false, |c| c.disable_password_login)
}
/// Returns a clone of the OIDC config if available
@@ -664,11 +664,23 @@ impl AuthApplicationService {
// Admin quota, capped to available disk space
let admin_quota = self.capped_quota(&admin_role);
// Hash the password (same as register / admin_create_user)
let password_hash = self
.password_hasher
.hash_password(&dto.password)
.map_err(|e| {
DomainError::new(
ErrorKind::InternalError,
"User",
format!("Error hashing password: {}", e),
)
})?;
// Create the new admin user
let user = User::new(
dto.username.clone(),
dto.email.clone(),
dto.password.clone(),
password_hash,
admin_role,
admin_quota,
)
+1 -1
View File
@@ -129,7 +129,7 @@ impl BatchOperationService {
// Acquire semaphore permit
let permit = semaphore.acquire().await.unwrap();
let copy_result = mgmt.move_file(&file_id, target_folder.clone()).await;
let copy_result = mgmt.copy_file(&file_id, target_folder.clone()).await;
// Release the permit explicitly (also released on drop)
drop(permit);
+34 -290
View File
@@ -24,13 +24,8 @@ impl CalendarUseCase for CalendarService {
async fn create_calendar(
&self,
calendar: CreateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError> {
// This function requires the current user context which will come from middleware
// For now, we'll use a dummy implementation that needs to be completed
// In a real implementation, get user_id from current user context
let user_id = "current_user_id"; // This should come from middleware
self.calendar_storage
.create_calendar(calendar, user_id)
.await
@@ -40,20 +35,12 @@ impl CalendarUseCase for CalendarService {
&self,
calendar_id: &str,
update: UpdateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError> {
// In a real implementation, we would:
// 1. Get the current user ID from middleware
// 2. Verify that the user has access to this calendar
// 3. Update the calendar if they have permission
let user_id = "current_user_id"; // This should come from middleware
// Check if user has access
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -61,21 +48,16 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to update this calendar",
));
}
self.calendar_storage
.update_calendar(calendar_id, update)
.await
}
async fn delete_calendar(&self, calendar_id: &str) -> Result<(), DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Check if user has access
async fn delete_calendar(&self, calendar_id: &str, user_id: &str) -> Result<(), DomainError> {
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -83,22 +65,19 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to delete this calendar",
));
}
self.calendar_storage.delete_calendar(calendar_id).await
}
async fn get_calendar(&self, calendar_id: &str) -> Result<CalendarDto, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Get the calendar
async fn get_calendar(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<CalendarDto, DomainError> {
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
// Check if user has access or if calendar is public
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
if !has_access && !calendar.is_public {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -106,19 +85,14 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to view this calendar",
));
}
Ok(calendar)
}
async fn list_my_calendars(&self) -> Result<Vec<CalendarDto>, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
async fn list_my_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError> {
self.calendar_storage.list_calendars_by_owner(user_id).await
}
async fn list_shared_calendars(&self) -> Result<Vec<CalendarDto>, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
async fn list_shared_calendars(&self, user_id: &str) -> Result<Vec<CalendarDto>, DomainError> {
self.calendar_storage
.list_calendars_shared_with_user(user_id)
.await
@@ -131,7 +105,6 @@ impl CalendarUseCase for CalendarService {
) -> Result<Vec<CalendarDto>, DomainError> {
let limit = limit.unwrap_or(100);
let offset = offset.unwrap_or(0);
self.calendar_storage
.list_public_calendars(limit, offset)
.await
@@ -140,24 +113,18 @@ impl CalendarUseCase for CalendarService {
async fn share_calendar(
&self,
calendar_id: &str,
user_id: &str,
target_user_id: &str,
access_level: &str,
caller_user_id: &str,
) -> Result<(), DomainError> {
let current_user_id = "current_user_id"; // This should come from middleware
// Check if current user has access
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
// Only the owner can share the calendar
if calendar.owner_id != current_user_id {
if calendar.owner_id != caller_user_id {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"Only the calendar owner can change sharing settings",
));
}
// Validate access_level
match access_level {
"read" | "write" | "owner" => {}
_ => {
@@ -171,66 +138,55 @@ impl CalendarUseCase for CalendarService {
));
}
}
self.calendar_storage
.share_calendar(calendar_id, user_id, access_level)
.share_calendar(calendar_id, target_user_id, access_level)
.await
}
async fn remove_calendar_sharing(
&self,
calendar_id: &str,
user_id: &str,
target_user_id: &str,
caller_user_id: &str,
) -> Result<(), DomainError> {
let current_user_id = "current_user_id"; // This should come from middleware
// Check if current user has access
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
// Only the owner can change sharing settings
if calendar.owner_id != current_user_id {
if calendar.owner_id != caller_user_id {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"Only the calendar owner can change sharing settings",
));
}
self.calendar_storage
.remove_calendar_sharing(calendar_id, user_id)
.remove_calendar_sharing(calendar_id, target_user_id)
.await
}
async fn get_calendar_shares(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<Vec<(String, String)>, DomainError> {
let current_user_id = "current_user_id"; // This should come from middleware
// Check if current user has access
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
// Only the owner can view sharing settings
if calendar.owner_id != current_user_id {
if calendar.owner_id != user_id {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"Only the calendar owner can view sharing settings",
));
}
self.calendar_storage.get_calendar_shares(calendar_id).await
}
async fn create_event(&self, event: CreateEventDto) -> Result<CalendarEventDto, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Check if user has access to the calendar
async fn create_event(
&self,
event: CreateEventDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError> {
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -238,22 +194,18 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to add events to this calendar",
));
}
self.calendar_storage.create_event(event).await
}
async fn create_event_from_ical(
&self,
event: CreateEventICalDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Check if user has access to the calendar
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -261,7 +213,6 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to add events to this calendar",
));
}
self.calendar_storage.create_event_from_ical(event).await
}
@@ -269,18 +220,13 @@ impl CalendarUseCase for CalendarService {
&self,
event_id: &str,
update: UpdateEventDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Get the event to find its calendar
let event = self.calendar_storage.get_event(event_id).await?;
// Check if user has access to the calendar
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -288,22 +234,15 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to update events in this calendar",
));
}
self.calendar_storage.update_event(event_id, update).await
}
async fn delete_event(&self, event_id: &str) -> Result<(), DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Get the event to find its calendar
async fn delete_event(&self, event_id: &str, user_id: &str) -> Result<(), DomainError> {
let event = self.calendar_storage.get_event(event_id).await?;
// Check if user has access to the calendar
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -311,28 +250,23 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to delete events in this calendar",
));
}
self.calendar_storage.delete_event(event_id).await
}
async fn get_event(&self, event_id: &str) -> Result<CalendarEventDto, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Get the event
async fn get_event(
&self,
event_id: &str,
user_id: &str,
) -> Result<CalendarEventDto, DomainError> {
let event = self.calendar_storage.get_event(event_id).await?;
// Check if user has access to the calendar
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
// Check if calendar is public
let calendar = self
.calendar_storage
.get_calendar(&event.calendar_id)
.await?;
if !has_access && !calendar.is_public {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -340,7 +274,6 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to view events in this calendar",
));
}
Ok(event)
}
@@ -349,18 +282,13 @@ impl CalendarUseCase for CalendarService {
calendar_id: &str,
limit: Option<i64>,
offset: Option<i64>,
user_id: &str,
) -> Result<Vec<CalendarEventDto>, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Check if user has access to the calendar
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
// Check if calendar is public
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
if !has_access && !calendar.is_public {
return Err(DomainError::new(
ErrorKind::AccessDenied,
@@ -368,12 +296,9 @@ impl CalendarUseCase for CalendarService {
"You don't have permission to view events in this calendar",
));
}
// Use pagination if provided
if limit.is_some() || offset.is_some() {
let limit = limit.unwrap_or(100);
let offset = offset.unwrap_or(0);
self.calendar_storage
.list_events_by_calendar_paginated(calendar_id, limit, offset)
.await
@@ -389,148 +314,6 @@ impl CalendarUseCase for CalendarService {
calendar_id: &str,
start: DateTime<Utc>,
end: DateTime<Utc>,
) -> Result<Vec<CalendarEventDto>, DomainError> {
let user_id = "current_user_id"; // This should come from middleware
// Check if user has access to the calendar
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
// Check if calendar is public
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
if !has_access && !calendar.is_public {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to view events in this calendar",
));
}
self.calendar_storage
.get_events_in_time_range(calendar_id, &start, &end)
.await
}
// ─── User-contextualized variants (for CalDAV protocol handler) ──
async fn create_calendar_for_user(
&self,
calendar: CreateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError> {
self.calendar_storage
.create_calendar(calendar, user_id)
.await
}
async fn update_calendar_for_user(
&self,
calendar_id: &str,
update: UpdateCalendarDto,
user_id: &str,
) -> Result<CalendarDto, DomainError> {
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to update this calendar",
));
}
self.calendar_storage
.update_calendar(calendar_id, update)
.await
}
async fn delete_calendar_for_user(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<(), DomainError> {
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to delete this calendar",
));
}
self.calendar_storage.delete_calendar(calendar_id).await
}
async fn get_calendar_for_user(
&self,
calendar_id: &str,
user_id: &str,
) -> Result<CalendarDto, DomainError> {
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
if !has_access && !calendar.is_public {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to view this calendar",
));
}
Ok(calendar)
}
async fn list_my_calendars_for_user(
&self,
user_id: &str,
) -> Result<Vec<CalendarDto>, DomainError> {
self.calendar_storage.list_calendars_by_owner(user_id).await
}
async fn list_events_for_user(
&self,
calendar_id: &str,
limit: Option<i64>,
offset: Option<i64>,
user_id: &str,
) -> Result<Vec<CalendarEventDto>, DomainError> {
let has_access = self
.calendar_storage
.check_calendar_access(calendar_id, user_id)
.await?;
let calendar = self.calendar_storage.get_calendar(calendar_id).await?;
if !has_access && !calendar.is_public {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to view events in this calendar",
));
}
if limit.is_some() || offset.is_some() {
let limit = limit.unwrap_or(100);
let offset = offset.unwrap_or(0);
self.calendar_storage
.list_events_by_calendar_paginated(calendar_id, limit, offset)
.await
} else {
self.calendar_storage
.list_events_by_calendar(calendar_id)
.await
}
}
async fn get_events_in_range_for_user(
&self,
calendar_id: &str,
start: DateTime<Utc>,
end: DateTime<Utc>,
user_id: &str,
) -> Result<Vec<CalendarEventDto>, DomainError> {
let has_access = self
@@ -549,43 +332,4 @@ impl CalendarUseCase for CalendarService {
.get_events_in_time_range(calendar_id, &start, &end)
.await
}
async fn create_event_from_ical_for_user(
&self,
event: CreateEventICalDto,
user_id: &str,
) -> Result<CalendarEventDto, DomainError> {
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to add events to this calendar",
));
}
self.calendar_storage.create_event_from_ical(event).await
}
async fn delete_event_for_user(
&self,
event_id: &str,
user_id: &str,
) -> Result<(), DomainError> {
let event = self.calendar_storage.get_event(event_id).await?;
let has_access = self
.calendar_storage
.check_calendar_access(&event.calendar_id, user_id)
.await?;
if !has_access {
return Err(DomainError::new(
ErrorKind::AccessDenied,
"Calendar",
"You don't have permission to delete events in this calendar",
));
}
self.calendar_storage.delete_event(event_id).await
}
}
@@ -121,6 +121,35 @@ impl FileManagementUseCase for FileManagementService {
Ok(FileDto::from(moved_file))
}
async fn copy_file(
&self,
file_id: &str,
target_folder_id: Option<String>,
) -> Result<FileDto, DomainError> {
info!(
"Copying file with ID: {} to folder: {:?}",
file_id, target_folder_id
);
let copied_file = self
.file_repository
.copy_file(file_id, target_folder_id)
.await
.map_err(|e| {
error!("Error copying file (ID: {}): {}", file_id, e);
e
})?;
info!(
"File copied successfully: {} (ID: {}) to folder: {:?}",
copied_file.name(),
copied_file.id(),
copied_file.folder_id()
);
Ok(FileDto::from(copied_file))
}
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<FileDto, DomainError> {
info!("Renaming file with ID: {} to \"{}\"", file_id, new_name);
+236 -144
View File
@@ -1,50 +1,54 @@
use sqlx::PgPool;
use std::path::PathBuf;
use std::sync::Arc;
use sqlx::PgPool;
use crate::application::services::auth_application_service::AuthApplicationService;
use crate::application::services::admin_settings_service::AdminSettingsService;
use crate::application::services::auth_application_service::AuthApplicationService;
use crate::infrastructure::services::path_service::PathService;
use crate::infrastructure::repositories::share_fs_repository::ShareFsRepository;
use crate::infrastructure::repositories::pg::{
FolderDbRepository, FileBlobReadRepository, FileBlobWriteRepository, TrashDbRepository,
};
use crate::infrastructure::services::file_system_i18n_service::FileSystemI18nService;
use crate::infrastructure::services::file_content_cache::{FileContentCache, FileContentCacheConfig};
use crate::infrastructure::services::trash_cleanup_service::TrashCleanupService;
use crate::application::services::folder_service::FolderService;
use crate::application::services::i18n_application_service::I18nApplicationService;
use crate::application::services::trash_service::TrashService;
use crate::application::services::search_service::SearchService;
use crate::application::services::share_service::ShareService;
use crate::application::services::favorites_service::FavoritesService;
use crate::application::services::recent_service::RecentService;
use crate::application::ports::trash_ports::TrashUseCase;
use crate::application::ports::inbound::{FolderUseCase, SearchUseCase};
use crate::application::ports::outbound::FolderStoragePort;
use crate::application::ports::favorites_ports::FavoritesUseCase;
use crate::application::ports::recent_ports::RecentItemsUseCase;
use crate::application::ports::file_ports::{FileUploadUseCase, FileRetrievalUseCase, FileManagementUseCase, FileUseCaseFactory};
use crate::application::ports::storage_ports::{FileReadPort, FileWritePort};
use crate::application::services::{FileUploadService, FileRetrievalService, FileManagementService, AppFileUseCaseFactory};
use crate::common::errors::DomainError;
use crate::domain::services::i18n_service::I18nService;
use crate::common::config::AppConfig;
use crate::application::ports::cache_ports::ContentCachePort;
use crate::application::ports::thumbnail_ports::ThumbnailPort;
use crate::application::ports::transcode_ports::ImageTranscodePort;
use crate::application::ports::dedup_ports::DedupPort;
use crate::application::ports::chunked_upload_ports::ChunkedUploadPort;
use crate::application::ports::compression_ports::CompressionPort;
use crate::application::ports::dedup_ports::DedupPort;
use crate::application::ports::favorites_ports::FavoritesUseCase;
use crate::application::ports::file_ports::{
FileManagementUseCase, FileRetrievalUseCase, FileUploadUseCase, FileUseCaseFactory,
};
use crate::application::ports::inbound::{FolderUseCase, SearchUseCase};
use crate::application::ports::outbound::FolderStoragePort;
use crate::application::ports::recent_ports::RecentItemsUseCase;
use crate::application::ports::storage_ports::{FileReadPort, FileWritePort};
use crate::application::ports::thumbnail_ports::ThumbnailPort;
use crate::application::ports::transcode_ports::ImageTranscodePort;
use crate::application::ports::trash_ports::TrashUseCase;
use crate::application::ports::zip_ports::ZipPort;
use crate::application::services::favorites_service::FavoritesService;
use crate::application::services::folder_service::FolderService;
use crate::application::services::i18n_application_service::I18nApplicationService;
use crate::application::services::recent_service::RecentService;
use crate::application::services::search_service::SearchService;
use crate::application::services::share_service::ShareService;
use crate::application::services::trash_service::TrashService;
use crate::application::services::{
AppFileUseCaseFactory, FileManagementService, FileRetrievalService, FileUploadService,
};
use crate::common::config::AppConfig;
use crate::common::errors::DomainError;
use crate::domain::services::i18n_service::I18nService;
use crate::infrastructure::repositories::pg::{
FileBlobReadRepository, FileBlobWriteRepository, FolderDbRepository, TrashDbRepository,
};
use crate::infrastructure::repositories::share_fs_repository::ShareFsRepository;
use crate::infrastructure::services::file_content_cache::{
FileContentCache, FileContentCacheConfig,
};
use crate::infrastructure::services::file_system_i18n_service::FileSystemI18nService;
use crate::infrastructure::services::path_service::PathService;
use crate::infrastructure::services::trash_cleanup_service::TrashCleanupService;
use crate::common::stubs::{
StubZipPort, StubCompressionPort,
StubFileReadPort, StubFileWritePort, StubFolderStoragePort,
StubI18nService, StubFolderUseCase, StubFileUploadUseCase,
StubFileRetrievalUseCase, StubFileManagementUseCase, StubFileUseCaseFactory,
StubSearchUseCase, StubDedupPort,
StubCompressionPort, StubDedupPort, StubFileManagementUseCase, StubFileReadPort,
StubFileRetrievalUseCase, StubFileUploadUseCase, StubFileUseCaseFactory, StubFileWritePort,
StubFolderStoragePort, StubFolderUseCase, StubI18nService, StubSearchUseCase, StubZipPort,
};
/// Factory for the different application components
@@ -89,15 +93,18 @@ impl AppServiceFactory {
/// Initializes the core system services.
///
/// Requires a `PgPool` because `DedupService` stores its index in PostgreSQL.
pub async fn create_core_services(&self, db_pool: &Arc<PgPool>) -> Result<CoreServices, DomainError> {
pub async fn create_core_services(
&self,
db_pool: &Arc<PgPool>,
) -> Result<CoreServices, DomainError> {
// Path service (still needed for blob storage root + thumbnails)
let path_service = Arc::new(PathService::new(self.storage_path.clone()));
// File content cache for ultra-fast file serving (hot files in RAM)
let file_content_cache = Arc::new(FileContentCache::new(FileContentCacheConfig {
max_file_size: 10 * 1024 * 1024, // 10MB max per file
max_total_size: 512 * 1024 * 1024, // 512MB total cache
max_entries: 10000, // Up to 10k files
max_file_size: 10 * 1024 * 1024, // 10MB max per file
max_total_size: 512 * 1024 * 1024, // 512MB total cache
max_entries: 10000, // Up to 10k files
}));
tracing::info!("FileContentCache initialized: max 10MB/file, 512MB total, 10k entries");
@@ -105,9 +112,9 @@ impl AppServiceFactory {
let thumbnail_service = Arc::new(
crate::infrastructure::services::thumbnail_service::ThumbnailService::new(
&self.storage_path,
5000, // max 5000 thumbnails in cache
100 * 1024 * 1024, // max 100MB cache
)
5000, // max 5000 thumbnails in cache
100 * 1024 * 1024, // max 100MB cache
),
);
// Initialize thumbnail directories
thumbnail_service.initialize().await?;
@@ -115,31 +122,38 @@ impl AppServiceFactory {
// Chunked upload service for large files (>10MB)
let chunked_temp_dir = std::path::PathBuf::from(&self.storage_path).join(".uploads");
let chunked_upload_service = Arc::new(
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(chunked_temp_dir)
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(
chunked_temp_dir,
),
);
// Image transcoding service for automatic WebP conversion
let image_transcode_service = Arc::new(
crate::infrastructure::services::image_transcode_service::ImageTranscodeService::new(
&self.storage_path,
2000, // max 2000 transcoded images in cache
50 * 1024 * 1024, // max 50MB in-memory cache
)
2000, // max 2000 transcoded images in cache
50 * 1024 * 1024, // max 50MB in-memory cache
),
);
image_transcode_service.initialize().await?;
// Deduplication service — PRIMARY blob storage engine (PostgreSQL-backed index)
let dedup_service = Arc::new(
crate::infrastructure::services::dedup_service::DedupService::new(&self.storage_path, db_pool.clone())
crate::infrastructure::services::dedup_service::DedupService::new(
&self.storage_path,
db_pool.clone(),
),
);
dedup_service.initialize().await?;
// Compression service (gzip)
let compression_service: Arc<dyn CompressionPort> = Arc::new(
crate::infrastructure::services::compression_service::GzipCompressionService::new()
crate::infrastructure::services::compression_service::GzipCompressionService::new(),
);
tracing::info!("Core services initialized: path service, file content cache, thumbnails, chunked upload, image transcode, dedup (PRIMARY blob storage), compression");
tracing::info!(
"Core services initialized: path service, file content cache, thumbnails, chunked upload, image transcode, dedup (PRIMARY blob storage), compression"
);
Ok(CoreServices {
path_service,
@@ -149,7 +163,7 @@ impl AppServiceFactory {
image_transcode_service,
dedup_service,
compression_service,
zip_service: Arc::new(StubZipPort), // Placeholder - replaced after app services init
zip_service: Arc::new(StubZipPort), // Placeholder - replaced after app services init
config: self.config.clone(),
})
}
@@ -157,7 +171,11 @@ impl AppServiceFactory {
/// Initializes the repository services (blob-storage model).
///
/// Requires a PgPool since all metadata lives in PostgreSQL.
pub fn create_repository_services(&self, core: &CoreServices, db_pool: &Arc<PgPool>) -> RepositoryServices {
pub fn create_repository_services(
&self,
core: &CoreServices,
db_pool: &Arc<PgPool>,
) -> RepositoryServices {
// Folder repository — PostgreSQL-backed virtual folders
let folder_repo_concrete = Arc::new(FolderDbRepository::new(db_pool.clone()));
let folder_repository: Arc<dyn FolderStoragePort> = folder_repo_concrete.clone();
@@ -176,21 +194,24 @@ impl AppServiceFactory {
));
// I18n repository
let i18n_repository = Arc::new(FileSystemI18nService::new(
self.locales_path.clone()
));
let i18n_repository = Arc::new(FileSystemI18nService::new(self.locales_path.clone()));
// Trash repository — reads soft-delete flags from storage.files/folders
let trash_repository = if core.config.features.enable_trash {
Some(Arc::new(TrashDbRepository::new(
db_pool.clone(),
core.config.storage.trash_retention_days,
)) as Arc<dyn crate::domain::repositories::trash_repository::TrashRepository>)
))
as Arc<
dyn crate::domain::repositories::trash_repository::TrashRepository,
>)
} else {
None
};
tracing::info!("Repository services initialized with 100% blob storage model (PG metadata + DedupService blobs)");
tracing::info!(
"Repository services initialized with 100% blob storage model (PG metadata + DedupService blobs)"
);
RepositoryServices {
folder_repository,
@@ -210,9 +231,7 @@ impl AppServiceFactory {
trash_service: Option<Arc<dyn TrashUseCase>>,
) -> ApplicationServices {
// Main services
let folder_service = Arc::new(FolderService::new(
repos.folder_repository.clone()
));
let folder_service = Arc::new(FolderService::new(repos.folder_repository.clone()));
// Refactored services with all infrastructure ports
// In blob model, dedup is handled by the repository — no separate write-behind needed
@@ -237,18 +256,16 @@ impl AppServiceFactory {
let file_use_case_factory = Arc::new(AppFileUseCaseFactory::new(
repos.file_read_repository.clone(),
repos.file_write_repository.clone()
repos.file_write_repository.clone(),
));
let i18n_service = Arc::new(I18nApplicationService::new(
repos.i18n_repository.clone()
));
let i18n_service = Arc::new(I18nApplicationService::new(repos.i18n_repository.clone()));
// Search service with cache
let search_service: Option<Arc<dyn SearchUseCase>> = Some(Arc::new(SearchService::new(
repos.file_read_repository.clone(),
repos.folder_repository.clone(),
300, // Cache TTL in seconds (5 minutes)
300, // Cache TTL in seconds (5 minutes)
1000, // Maximum cache entries
)));
@@ -266,9 +283,9 @@ impl AppServiceFactory {
i18n_service,
trash_service, // Already set via parameter
search_service,
share_service: None, // Configured later with create_share_service
share_service: None, // Configured later with create_share_service
favorites_service: None, // Configured later with create_favorites_service
recent_service: None, // Configured later with create_recent_service
recent_service: None, // Configured later with create_recent_service
}
}
@@ -316,9 +333,7 @@ impl AppServiceFactory {
return None;
}
let share_repository = Arc::new(ShareFsRepository::new(
Arc::new(self.config.clone())
));
let share_repository = Arc::new(ShareFsRepository::new(Arc::new(self.config.clone())));
// Build a password hasher for share password verification
let password_hasher: Arc<dyn crate::application::ports::auth_ports::PasswordHasherPort> =
@@ -337,12 +352,9 @@ impl AppServiceFactory {
}
/// Creates the favorites service (requires database)
pub fn create_favorites_service(
&self,
db_pool: &Arc<PgPool>,
) -> Arc<dyn FavoritesUseCase> {
pub fn create_favorites_service(&self, db_pool: &Arc<PgPool>) -> Arc<dyn FavoritesUseCase> {
let repo = Arc::new(
crate::infrastructure::repositories::pg::FavoritesPgRepository::new(db_pool.clone())
crate::infrastructure::repositories::pg::FavoritesPgRepository::new(db_pool.clone()),
);
let service = Arc::new(FavoritesService::new(repo));
tracing::info!("Favorites service initialized");
@@ -350,16 +362,12 @@ impl AppServiceFactory {
}
/// Creates the recent items service (requires database)
pub fn create_recent_service(
&self,
db_pool: &Arc<PgPool>,
) -> Arc<dyn RecentItemsUseCase> {
pub fn create_recent_service(&self, db_pool: &Arc<PgPool>) -> Arc<dyn RecentItemsUseCase> {
let repo = Arc::new(
crate::infrastructure::repositories::pg::RecentItemsPgRepository::new(db_pool.clone())
crate::infrastructure::repositories::pg::RecentItemsPgRepository::new(db_pool.clone()),
);
let service = Arc::new(RecentService::new(
repo,
50 // Maximum recent items per user
repo, 50, // Maximum recent items per user
));
tracing::info!("Recent items service initialized");
service
@@ -394,13 +402,13 @@ impl AppServiceFactory {
db_pool: &Arc<PgPool>,
) -> Arc<dyn crate::application::ports::storage_ports::StorageUsagePort> {
let user_repository = Arc::new(
crate::infrastructure::repositories::pg::UserPgRepository::new(db_pool.clone())
crate::infrastructure::repositories::pg::UserPgRepository::new(db_pool.clone()),
);
let service = Arc::new(
crate::application::services::storage_usage_service::StorageUsageService::new(
repos.file_read_repository.clone(),
user_repository,
)
),
);
tracing::info!("Storage usage service initialized");
service
@@ -415,7 +423,10 @@ impl AppServiceFactory {
) -> Result<AppState, DomainError> {
// Database is REQUIRED in 100% blob storage model
let pool = db_pool.clone().ok_or_else(|| {
DomainError::internal_error("Database", "PostgreSQL database is required for blob storage model")
DomainError::internal_error(
"Database",
"PostgreSQL database is required for blob storage model",
)
})?;
// 1. Core services (PgPool needed for DedupService index)
@@ -437,7 +448,9 @@ impl AppServiceFactory {
// 6. Database-dependent services (PgPool always available in blob model)
let favorites_service: Option<Arc<dyn FavoritesUseCase>>;
let recent_service: Option<Arc<dyn RecentItemsUseCase>>;
let storage_usage_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>>;
let storage_usage_service: Option<
Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>,
>;
let mut auth_services: Option<crate::common::di::AuthServices> = None;
{
@@ -457,7 +470,9 @@ impl AppServiceFactory {
&self.config,
pool.clone(),
Some(apps.folder_service_concrete.clone()),
).await {
)
.await
{
Ok(services) => {
tracing::info!("Authentication services initialized successfully");
auth_services = Some(services);
@@ -477,7 +492,7 @@ impl AppServiceFactory {
crate::infrastructure::services::zip_service::ZipService::new(
apps.file_retrieval_service.clone(),
apps.folder_service.clone(),
)
),
);
let mut core = core;
core.zip_service = zip_service;
@@ -505,7 +520,7 @@ impl AppServiceFactory {
// 9b. Wire admin settings service when auth is available
if let Some(auth_svc) = &app_state.auth_service {
let settings_repo = Arc::new(
crate::infrastructure::repositories::pg::SettingsPgRepository::new(pool.clone())
crate::infrastructure::repositories::pg::SettingsPgRepository::new(pool.clone()),
);
let server_base_url = self.config.base_url();
@@ -521,20 +536,30 @@ impl AppServiceFactory {
// Hot-reload OIDC from DB settings if configured
match admin_svc.load_effective_oidc_config().await {
Ok(eff) if eff.enabled && !eff.issuer_url.is_empty()
&& !eff.client_id.is_empty() && !eff.client_secret.is_empty() =>
Ok(eff)
if eff.enabled
&& !eff.issuer_url.is_empty()
&& !eff.client_id.is_empty()
&& !eff.client_secret.is_empty() =>
{
let oidc_svc = Arc::new(
crate::infrastructure::services::oidc_service::OidcService::new(eff.clone())
crate::infrastructure::services::oidc_service::OidcService::new(
eff.clone(),
),
);
auth_svc.auth_application_service.reload_oidc(oidc_svc, eff);
tracing::info!("OIDC config loaded from admin settings (database)");
}
Ok(_) => {
tracing::info!("No active OIDC config in admin settings — using env vars or defaults");
tracing::info!(
"No active OIDC config in admin settings — using env vars or defaults"
);
}
Err(e) => {
tracing::warn!("Failed to load OIDC settings from database (table may not exist yet): {}", e);
tracing::warn!(
"Failed to load OIDC settings from database (table may not exist yet): {}",
e
);
}
}
@@ -544,11 +569,17 @@ impl AppServiceFactory {
// 10. Wire CalDAV/CardDAV services
{
// CalDAV
let calendar_repo: Arc<dyn crate::domain::repositories::calendar_repository::CalendarRepository> = Arc::new(
crate::infrastructure::repositories::pg::CalendarPgRepository::new(pool.clone())
let calendar_repo: Arc<
dyn crate::domain::repositories::calendar_repository::CalendarRepository,
> = Arc::new(
crate::infrastructure::repositories::pg::CalendarPgRepository::new(pool.clone()),
);
let event_repo: Arc<dyn crate::domain::repositories::calendar_event_repository::CalendarEventRepository> = Arc::new(
crate::infrastructure::repositories::pg::CalendarEventPgRepository::new(pool.clone())
let event_repo: Arc<
dyn crate::domain::repositories::calendar_event_repository::CalendarEventRepository,
> = Arc::new(
crate::infrastructure::repositories::pg::CalendarEventPgRepository::new(
pool.clone(),
),
);
let calendar_storage = Arc::new(
crate::infrastructure::adapters::calendar_storage_adapter::CalendarStorageAdapter::new(
@@ -557,19 +588,32 @@ impl AppServiceFactory {
)
);
let calendar_service = Arc::new(
crate::application::services::calendar_service::CalendarService::new(calendar_storage)
crate::application::services::calendar_service::CalendarService::new(
calendar_storage,
),
);
app_state.calendar_use_case = Some(
calendar_service
as Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>,
);
app_state.calendar_use_case = Some(calendar_service as Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>);
// CardDAV
let address_book_repo: Arc<dyn crate::domain::repositories::address_book_repository::AddressBookRepository> = Arc::new(
crate::infrastructure::repositories::pg::AddressBookPgRepository::new(pool.clone())
let address_book_repo: Arc<
dyn crate::domain::repositories::address_book_repository::AddressBookRepository,
> = Arc::new(
crate::infrastructure::repositories::pg::AddressBookPgRepository::new(pool.clone()),
);
let contact_repo: Arc<dyn crate::domain::repositories::contact_repository::ContactRepository> = Arc::new(
crate::infrastructure::repositories::pg::ContactPgRepository::new(pool.clone())
let contact_repo: Arc<
dyn crate::domain::repositories::contact_repository::ContactRepository,
> = Arc::new(
crate::infrastructure::repositories::pg::ContactPgRepository::new(pool.clone()),
);
let group_repo: Arc<dyn crate::domain::repositories::contact_repository::ContactGroupRepository> = Arc::new(
crate::infrastructure::repositories::pg::ContactGroupPgRepository::new(pool.clone())
let group_repo: Arc<
dyn crate::domain::repositories::contact_repository::ContactGroupRepository,
> = Arc::new(
crate::infrastructure::repositories::pg::ContactGroupPgRepository::new(
pool.clone(),
),
);
let contact_storage = Arc::new(
crate::infrastructure::adapters::contact_storage_adapter::ContactStorageAdapter::new(
@@ -578,8 +622,12 @@ impl AppServiceFactory {
group_repo,
)
);
app_state.addressbook_use_case = Some(contact_storage.clone() as Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>);
app_state.contact_use_case = Some(contact_storage as Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>);
app_state.addressbook_use_case = Some(contact_storage.clone()
as Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>);
app_state.contact_use_case = Some(
contact_storage
as Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>,
);
tracing::info!("CalDAV and CardDAV services initialized with PostgreSQL repositories");
}
@@ -610,7 +658,8 @@ pub struct RepositoryServices {
pub file_read_repository: Arc<dyn FileReadPort>,
pub file_write_repository: Arc<dyn FileWritePort>,
pub i18n_repository: Arc<dyn I18nService>,
pub trash_repository: Option<Arc<dyn crate::domain::repositories::trash_repository::TrashRepository>>,
pub trash_repository:
Option<Arc<dyn crate::domain::repositories::trash_repository::TrashRepository>>,
}
/// Container for application services
@@ -652,11 +701,14 @@ pub struct AppState {
pub share_service: Option<Arc<dyn crate::application::ports::share_ports::ShareUseCase>>,
pub favorites_service: Option<Arc<dyn FavoritesUseCase>>,
pub recent_service: Option<Arc<dyn RecentItemsUseCase>>,
pub storage_usage_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>>,
pub storage_usage_service:
Option<Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>>,
pub calendar_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUseCase>>,
pub contact_service: Option<Arc<dyn crate::application::ports::storage_ports::StorageUseCase>>,
pub calendar_use_case: Option<Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>>,
pub addressbook_use_case: Option<Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>>,
pub calendar_use_case:
Option<Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>>,
pub addressbook_use_case:
Option<Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>>,
pub contact_use_case: Option<Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>>,
}
@@ -668,16 +720,22 @@ impl Default for AppState {
let config = crate::common::config::AppConfig::default();
let path_service = Arc::new(
crate::infrastructure::services::path_service::PathService::new(
std::path::PathBuf::from("./storage")
)
std::path::PathBuf::from("./storage"),
),
);
let i18n_repository = Arc::new(StubI18nService) as Arc<dyn crate::domain::services::i18n_service::I18nService>;
let folder_service = Arc::new(StubFolderUseCase) as Arc<dyn crate::application::ports::inbound::FolderUseCase>;
let file_upload_service = Arc::new(StubFileUploadUseCase) as Arc<dyn crate::application::ports::file_ports::FileUploadUseCase>;
let file_retrieval_service = Arc::new(StubFileRetrievalUseCase) as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>;
let file_management_service = Arc::new(StubFileManagementUseCase) as Arc<dyn crate::application::ports::file_ports::FileManagementUseCase>;
let file_use_case_factory = Arc::new(StubFileUseCaseFactory) as Arc<dyn crate::application::ports::file_ports::FileUseCaseFactory>;
let i18n_repository = Arc::new(StubI18nService)
as Arc<dyn crate::domain::services::i18n_service::I18nService>;
let folder_service = Arc::new(StubFolderUseCase)
as Arc<dyn crate::application::ports::inbound::FolderUseCase>;
let file_upload_service = Arc::new(StubFileUploadUseCase)
as Arc<dyn crate::application::ports::file_ports::FileUploadUseCase>;
let file_retrieval_service = Arc::new(StubFileRetrievalUseCase)
as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>;
let file_management_service = Arc::new(StubFileManagementUseCase)
as Arc<dyn crate::application::ports::file_ports::FileManagementUseCase>;
let file_use_case_factory = Arc::new(StubFileUseCaseFactory)
as Arc<dyn crate::application::ports::file_ports::FileUseCaseFactory>;
// Create file content cache for stub
let file_content_cache = Arc::new(FileContentCache::new(FileContentCacheConfig::default()));
@@ -688,14 +746,14 @@ impl Default for AppState {
&std::path::PathBuf::from("./storage"),
100,
10 * 1024 * 1024,
)
),
);
// Create dummy chunked upload service
let dummy_chunked_upload_service: Arc<dyn ChunkedUploadPort> = Arc::new(
crate::infrastructure::services::chunked_upload_service::ChunkedUploadService::new(
std::path::PathBuf::from("./storage/.uploads")
)
std::path::PathBuf::from("./storage/.uploads"),
),
);
// Create dummy image transcode service
@@ -704,7 +762,7 @@ impl Default for AppState {
&std::path::PathBuf::from("./storage"),
100,
10 * 1024 * 1024,
)
),
);
// Stub dedup service (Default is only used for routing stubs, never for real I/O)
@@ -729,22 +787,28 @@ impl Default for AppState {
// Repository services using stubs
let repository_services = RepositoryServices {
folder_repository: Arc::new(StubFolderStoragePort) as Arc<dyn crate::application::ports::outbound::FolderStoragePort>,
folder_repository: Arc::new(StubFolderStoragePort)
as Arc<dyn crate::application::ports::outbound::FolderStoragePort>,
folder_repo_concrete: dummy_folder_repo_concrete,
file_read_repository: Arc::new(StubFileReadPort) as Arc<dyn crate::application::ports::storage_ports::FileReadPort>,
file_write_repository: Arc::new(StubFileWritePort) as Arc<dyn crate::application::ports::storage_ports::FileWritePort>,
file_read_repository: Arc::new(StubFileReadPort)
as Arc<dyn crate::application::ports::storage_ports::FileReadPort>,
file_write_repository: Arc::new(StubFileWritePort)
as Arc<dyn crate::application::ports::storage_ports::FileWritePort>,
i18n_repository,
trash_repository: None,
};
// Dummy concrete services for compatibility
let dummy_folder_storage = Arc::new(StubFolderStoragePort) as Arc<dyn crate::application::ports::outbound::FolderStoragePort>;
let dummy_folder_storage = Arc::new(StubFolderStoragePort)
as Arc<dyn crate::application::ports::outbound::FolderStoragePort>;
let folder_service_concrete = Arc::new(FolderService::new(dummy_folder_storage));
// Dummy I18nApplicationService
let dummy_i18n_app_service = crate::application::services::i18n_application_service::I18nApplicationService::new(
Arc::new(StubI18nService) as Arc<dyn crate::domain::services::i18n_service::I18nService>
);
let dummy_i18n_app_service =
crate::application::services::i18n_application_service::I18nApplicationService::new(
Arc::new(StubI18nService)
as Arc<dyn crate::domain::services::i18n_service::I18nService>,
);
// Application services using stubs
let application_services = ApplicationServices {
@@ -756,7 +820,8 @@ impl Default for AppState {
file_use_case_factory,
i18n_service: Arc::new(dummy_i18n_app_service),
trash_service: None,
search_service: Some(Arc::new(StubSearchUseCase) as Arc<dyn crate::application::ports::inbound::SearchUseCase>),
search_service: Some(Arc::new(StubSearchUseCase)
as Arc<dyn crate::application::ports::inbound::SearchUseCase>),
share_service: None,
favorites_service: None,
recent_service: None,
@@ -821,11 +886,15 @@ impl AppState {
/// This keeps `routes.rs` free of any `crate::infrastructure` references.
pub fn for_routing(
folder_service: Arc<FolderService>,
file_retrieval_service: Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>,
file_retrieval_service: Arc<
dyn crate::application::ports::file_ports::FileRetrievalUseCase,
>,
file_upload_service: Arc<dyn FileUploadUseCase>,
file_management_service: Arc<dyn FileManagementUseCase>,
folder_use_case: Arc<dyn crate::application::ports::inbound::FolderUseCase>,
i18n_service: Option<Arc<crate::application::services::i18n_application_service::I18nApplicationService>>,
i18n_service: Option<
Arc<crate::application::services::i18n_application_service::I18nApplicationService>,
>,
trash_service: Option<Arc<dyn TrashUseCase>>,
search_service: Option<Arc<dyn crate::application::ports::inbound::SearchUseCase>>,
share_service: Option<Arc<dyn crate::application::ports::share_ports::ShareUseCase>>,
@@ -860,9 +929,11 @@ impl AppState {
// Create real ZipService with the actual file/folder services
state.core.zip_service = Arc::new(
crate::infrastructure::services::zip_service::ZipService::new(
file_retrieval_service as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>,
folder_service.clone() as Arc<dyn crate::application::ports::inbound::FolderUseCase>,
)
file_retrieval_service
as Arc<dyn crate::application::ports::file_ports::FileRetrievalUseCase>,
folder_service.clone()
as Arc<dyn crate::application::ports::inbound::FolderUseCase>,
),
);
state
@@ -878,7 +949,10 @@ impl AppState {
self
}
pub fn with_share_service(mut self, share_service: Arc<dyn crate::application::ports::share_ports::ShareUseCase>) -> Self {
pub fn with_share_service(
mut self,
share_service: Arc<dyn crate::application::ports::share_ports::ShareUseCase>,
) -> Self {
self.share_service = Some(share_service);
self
}
@@ -893,32 +967,50 @@ impl AppState {
self
}
pub fn with_storage_usage_service(mut self, storage_usage_service: Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>) -> Self {
pub fn with_storage_usage_service(
mut self,
storage_usage_service: Arc<dyn crate::application::ports::storage_ports::StorageUsagePort>,
) -> Self {
self.storage_usage_service = Some(storage_usage_service);
self
}
pub fn with_calendar_service(mut self, calendar_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>) -> Self {
pub fn with_calendar_service(
mut self,
calendar_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>,
) -> Self {
self.calendar_service = Some(calendar_service);
self
}
pub fn with_contact_service(mut self, contact_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>) -> Self {
pub fn with_contact_service(
mut self,
contact_service: Arc<dyn crate::application::ports::storage_ports::StorageUseCase>,
) -> Self {
self.contact_service = Some(contact_service);
self
}
pub fn with_calendar_use_case(mut self, calendar_use_case: Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>) -> Self {
pub fn with_calendar_use_case(
mut self,
calendar_use_case: Arc<dyn crate::application::ports::calendar_ports::CalendarUseCase>,
) -> Self {
self.calendar_use_case = Some(calendar_use_case);
self
}
pub fn with_addressbook_use_case(mut self, addressbook_use_case: Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>) -> Self {
pub fn with_addressbook_use_case(
mut self,
addressbook_use_case: Arc<dyn crate::application::ports::carddav_ports::AddressBookUseCase>,
) -> Self {
self.addressbook_use_case = Some(addressbook_use_case);
self
}
pub fn with_contact_use_case(mut self, contact_use_case: Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>) -> Self {
pub fn with_contact_use_case(
mut self,
contact_use_case: Arc<dyn crate::application::ports::carddav_ports::ContactUseCase>,
) -> Self {
self.contact_use_case = Some(contact_use_case);
self
}
+16
View File
@@ -168,6 +168,14 @@ impl FileWritePort for StubFileWritePort {
Ok(File::default())
}
async fn copy_file(
&self,
_file_id: &str,
_target_folder_id: Option<String>,
) -> Result<File, DomainError> {
Ok(File::default())
}
async fn rename_file(&self, _file_id: &str, _new_name: &str) -> Result<File, DomainError> {
Ok(File::default())
}
@@ -483,6 +491,14 @@ impl FileManagementUseCase for StubFileManagementUseCase {
Ok(FileDto::default())
}
async fn copy_file(
&self,
_file_id: &str,
_folder_id: Option<String>,
) -> Result<FileDto, DomainError> {
Ok(FileDto::default())
}
async fn rename_file(&self, _file_id: &str, _new_name: &str) -> Result<FileDto, DomainError> {
Ok(FileDto::default())
}
+2 -2
View File
@@ -5,6 +5,6 @@ pub mod pg;
// Re-exportar para facilitar acceso
pub use pg::{
FileBlobReadRepository, FileBlobWriteRepository, FolderDbRepository,
SessionPgRepository, TrashDbRepository, UserPgRepository,
FileBlobReadRepository, FileBlobWriteRepository, FolderDbRepository, SessionPgRepository,
TrashDbRepository, UserPgRepository,
};
@@ -64,9 +64,7 @@ impl FileBlobReadRepository {
created_at: i64,
modified_at: i64,
) -> Result<File, DomainError> {
let storage_path = self
.build_file_path(folder_id.as_deref(), &name)
.await?;
let storage_path = self.build_file_path(folder_id.as_deref(), &name).await?;
File::with_timestamps(
id,
name,
@@ -115,10 +113,7 @@ impl FileReadPort for FileBlobReadRepository {
.await
}
async fn list_files(
&self,
folder_id: Option<&str>,
) -> Result<Vec<File>, DomainError> {
async fn list_files(&self, folder_id: Option<&str>) -> Result<Vec<File>, DomainError> {
let rows: Vec<(String, String, Option<String>, i64, String, i64, i64)> =
if let Some(fid) = folder_id {
sqlx::query_as(
@@ -264,8 +259,7 @@ impl FileReadPort for FileBlobReadRepository {
}
}
current_parent.ok_or_else(|| {
DomainError::not_found("Folder", format!("parent for path: {path}"))
})
current_parent
.ok_or_else(|| DomainError::not_found("Folder", format!("parent for path: {path}")))
}
}
@@ -66,9 +66,7 @@ impl FileBlobWriteRepository {
created_at: i64,
modified_at: i64,
) -> Result<File, DomainError> {
let storage_path = self
.build_file_path(folder_id.as_deref(), &name)
.await?;
let storage_path = self.build_file_path(folder_id.as_deref(), &name).await?;
File::with_timestamps(
id,
name,
@@ -113,8 +111,8 @@ impl FileWritePort for FileBlobWriteRepository {
.await?;
let blob_hash = dedup_result.hash().to_string();
// Insert file metadata
let row = sqlx::query_as::<_, (String, i64, i64)>(
// Insert file metadata — if this fails, compensate by removing the blob ref
let row = match sqlx::query_as::<_, (String, i64, i64)>(
r#"
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
VALUES ($1, $2::uuid, $3, $4, $5, $6)
@@ -131,17 +129,31 @@ impl FileWritePort for FileBlobWriteRepository {
.bind(&content_type)
.fetch_one(self.pool.as_ref())
.await
.map_err(|e| {
if let sqlx::Error::Database(ref db_err) = e {
if db_err.code().as_deref() == Some("23505") {
return DomainError::already_exists(
"File",
format!("{name} already exists in folder"),
{
Ok(row) => row,
Err(e) => {
// ── Compensation: undo the blob ref so it doesn't become orphaned ──
if let Err(rollback_err) = self.dedup.remove_reference(&blob_hash).await {
tracing::error!(
"Blob orphaned after failed INSERT — hash: {}, err: {}",
&blob_hash[..12],
rollback_err
);
}
if let sqlx::Error::Database(ref db_err) = e {
if db_err.code().as_deref() == Some("23505") {
return Err(DomainError::already_exists(
"File",
format!("{name} already exists in folder"),
));
}
}
return Err(DomainError::internal_error(
"FileBlobWrite",
format!("insert: {e}"),
));
}
DomainError::internal_error("FileBlobWrite", format!("insert: {e}"))
})?;
};
tracing::info!(
"💾 BLOB WRITE: {} ({} bytes, hash: {})",
@@ -150,16 +162,8 @@ impl FileWritePort for FileBlobWriteRepository {
&blob_hash[..12]
);
self.row_to_file(
row.0,
name,
folder_id,
size,
content_type,
row.1,
row.2,
)
.await
self.row_to_file(row.0, name, folder_id, size, content_type, row.1, row.2)
.await
}
async fn save_file_from_stream(
@@ -211,11 +215,90 @@ impl FileWritePort for FileBlobWriteRepository {
.await
}
async fn rename_file(
async fn copy_file(
&self,
file_id: &str,
new_name: &str,
target_folder_id: Option<String>,
) -> Result<File, DomainError> {
// Atomic CTE: read source file → insert new row with same blob_hash → increment ref_count.
// Single round-trip; blob content is NOT copied (dedup makes this zero-copy).
let target_fid = target_folder_id.clone();
let row = sqlx::query_as::<
_,
(
String,
String,
Option<String>,
i64,
String,
i64,
i64,
String,
),
>(
r#"
WITH src AS (
SELECT name, folder_id, user_id, blob_hash, size, mime_type
FROM storage.files
WHERE id = $1::uuid AND NOT is_trashed
),
new_file AS (
INSERT INTO storage.files (name, folder_id, user_id, blob_hash, size, mime_type)
SELECT name,
COALESCE($2::uuid, folder_id),
user_id,
blob_hash,
size,
mime_type
FROM src
RETURNING id::text, name, folder_id::text, size, mime_type,
EXTRACT(EPOCH FROM created_at)::bigint,
EXTRACT(EPOCH FROM updated_at)::bigint,
blob_hash
)
SELECT * FROM new_file
"#,
)
.bind(file_id)
.bind(&target_fid)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| {
if let sqlx::Error::Database(ref db_err) = e {
if db_err.code().as_deref() == Some("23505") {
return DomainError::already_exists(
"File",
"File with that name already exists in target folder".to_string(),
);
}
}
DomainError::internal_error("FileBlobWrite", format!("copy: {e}"))
})?
.ok_or_else(|| DomainError::not_found("File", file_id))?;
let blob_hash = &row.7;
// Increment blob reference count (best-effort; INSERT already succeeded)
if let Err(e) = self.dedup.add_reference(blob_hash).await {
tracing::warn!(
"Failed to increment blob ref for copy {}: {}",
&blob_hash[..12],
e
);
}
tracing::info!(
"📋 BLOB COPY: {} (hash: {}, zero-copy via dedup)",
row.1,
&blob_hash[..12]
);
self.row_to_file(row.0, row.1, row.2, row.3, row.4, row.5, row.6)
.await
}
async fn rename_file(&self, file_id: &str, new_name: &str) -> Result<File, DomainError> {
let row = sqlx::query_as::<_, (String, String, Option<String>, i64, String, i64, i64)>(
r#"
UPDATE storage.files
@@ -248,30 +331,19 @@ impl FileWritePort for FileBlobWriteRepository {
}
async fn delete_file(&self, id: &str) -> Result<(), DomainError> {
// Get blob_hash before deleting so we can decrement ref
// Atomic DELETE RETURNING — one round-trip instead of SELECT + DELETE
let hash = sqlx::query_scalar::<_, String>(
"SELECT blob_hash FROM storage.files WHERE id = $1::uuid",
"DELETE FROM storage.files WHERE id = $1::uuid RETURNING blob_hash",
)
.bind(id)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("hash lookup: {e}")))?;
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("delete: {e}")))?
.ok_or_else(|| DomainError::not_found("File", id))?;
let result = sqlx::query("DELETE FROM storage.files WHERE id = $1::uuid")
.bind(id)
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("delete: {e}")))?;
if result.rows_affected() == 0 {
return Err(DomainError::not_found("File", id));
}
// Decrement blob reference
if let Some(h) = hash {
if let Err(e) = self.dedup.remove_reference(&h).await {
tracing::warn!("Failed to decrement blob ref for {}: {}", &h[..12], e);
}
// Decrement blob reference (best-effort after successful DELETE)
if let Err(e) = self.dedup.remove_reference(&hash).await {
tracing::warn!("Failed to decrement blob ref for {}: {}", &hash[..12], e);
}
Ok(())
@@ -282,37 +354,56 @@ impl FileWritePort for FileBlobWriteRepository {
file_id: &str,
content: Vec<u8>,
) -> Result<(), DomainError> {
// Get old blob hash to decrement ref
let old_hash = sqlx::query_scalar::<_, String>(
"SELECT blob_hash FROM storage.files WHERE id = $1::uuid",
)
.bind(file_id)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("old hash: {e}")))?
.ok_or_else(|| DomainError::not_found("File", file_id))?;
// Store new content
// Store new content first (blob store is idempotent)
let new_size = content.len() as i64;
let dedup_result = self.dedup.store_bytes(&content, None).await?;
let new_hash = dedup_result.hash().to_string();
// Update file metadata
sqlx::query(
// Atomic CTE: capture old hash then update in one round-trip, no TOCTOU.
// The `old` CTE locks + reads the row *before* the update touches it.
let old_hash = match sqlx::query_scalar::<_, String>(
r#"
UPDATE storage.files
WITH old AS (
SELECT id, blob_hash FROM storage.files WHERE id = $3::uuid FOR UPDATE
)
UPDATE storage.files f
SET blob_hash = $1, size = $2, updated_at = NOW()
WHERE id = $3::uuid
FROM old
WHERE f.id = old.id
RETURNING old.blob_hash
"#,
)
.bind(&new_hash)
.bind(new_size)
.bind(file_id)
.execute(self.pool.as_ref())
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("update: {e}")))?;
{
Ok(Some(old)) => old,
Ok(None) => {
// File not found — compensate: remove the new blob ref
if let Err(e) = self.dedup.remove_reference(&new_hash).await {
tracing::error!("Blob orphaned after missing file: {}", e);
}
return Err(DomainError::not_found("File", file_id));
}
Err(e) => {
// UPDATE failed — compensate: remove the new blob ref
if let Err(rollback_err) = self.dedup.remove_reference(&new_hash).await {
tracing::error!(
"Blob orphaned after failed UPDATE — hash: {}, err: {}",
&new_hash[..12],
rollback_err
);
}
return Err(DomainError::internal_error(
"FileBlobWrite",
format!("update: {e}"),
));
}
};
// Decrement old blob ref (only if hash changed)
// Decrement old blob ref (only if hash changed, best-effort)
if old_hash != new_hash {
if let Err(e) = self.dedup.remove_reference(&old_hash).await {
tracing::warn!(
@@ -34,7 +34,9 @@ impl FolderDbRepository {
/// Get the pool, panicking if stub.
fn pool(&self) -> &PgPool {
self.pool.as_deref().expect("FolderDbRepository: pool not available (stub instance)")
self.pool
.as_deref()
.expect("FolderDbRepository: pool not available (stub instance)")
}
// ── helpers ──────────────────────────────────────────────────
@@ -181,14 +183,10 @@ impl FolderRepository for FolderDbRepository {
.map_err(|e| DomainError::internal_error("FolderDb", format!("get: {e}")))?
.ok_or_else(|| DomainError::not_found("Folder", id))?;
self.row_to_folder(row.0, row.1, row.2, row.3, row.4)
.await
self.row_to_folder(row.0, row.1, row.2, row.3, row.4).await
}
async fn get_folder_by_path(
&self,
storage_path: &StoragePath,
) -> Result<Folder, DomainError> {
async fn get_folder_by_path(&self, storage_path: &StoragePath) -> Result<Folder, DomainError> {
// Walk the path segments to find the folder.
let path_str = storage_path.to_string();
let segments: Vec<&str> = path_str.split('/').filter(|s| !s.is_empty()).collect();
@@ -235,10 +233,7 @@ impl FolderRepository for FolderDbRepository {
self.get_folder(&current_id).await
}
async fn list_folders(
&self,
parent_id: Option<&str>,
) -> Result<Vec<Folder>, DomainError> {
async fn list_folders(&self, parent_id: Option<&str>) -> Result<Vec<Folder>, DomainError> {
let rows: Vec<(String, String, Option<String>, i64, i64)> = if let Some(pid) = parent_id {
sqlx::query_as(
r#"
@@ -347,11 +342,7 @@ impl FolderRepository for FolderDbRepository {
Ok((folders, total))
}
async fn rename_folder(
&self,
id: &str,
new_name: String,
) -> Result<Folder, DomainError> {
async fn rename_folder(&self, id: &str, new_name: String) -> Result<Folder, DomainError> {
sqlx::query(
r#"
UPDATE storage.folders
@@ -429,44 +420,43 @@ impl FolderRepository for FolderDbRepository {
// ── Trash operations ──
async fn move_to_trash(&self, folder_id: &str) -> Result<(), DomainError> {
// Soft-delete: set is_trashed = true and remember original parent
let result = sqlx::query(
// Atomic CTE: trash folder + all descendant files in a single statement.
// PostgreSQL executes the entire CTE as one atomic operation — no
// intermediate state where the folder is trashed but files are not.
let result = sqlx::query_scalar::<_, i64>(
r#"
UPDATE storage.folders
SET is_trashed = TRUE,
trashed_at = NOW(),
original_parent_id = parent_id,
updated_at = NOW()
WHERE id = $1::uuid AND NOT is_trashed
WITH trash_folder AS (
UPDATE storage.folders
SET is_trashed = TRUE,
trashed_at = NOW(),
original_parent_id = parent_id,
updated_at = NOW()
WHERE id = $1::uuid AND NOT is_trashed
RETURNING id
),
descendants AS (
SELECT id FROM trash_folder
UNION ALL
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
),
trash_files AS (
UPDATE storage.files
SET is_trashed = TRUE, trashed_at = NOW(), original_folder_id = folder_id
WHERE folder_id IN (SELECT id FROM descendants) AND NOT is_trashed
RETURNING 1
)
SELECT COUNT(*) FROM trash_folder
"#,
)
.bind(folder_id)
.execute(self.pool())
.fetch_one(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("trash: {e}")))?;
if result.rows_affected() == 0 {
if result == 0 {
return Err(DomainError::not_found("Folder", folder_id));
}
// Also trash all files inside the folder (recursively)
sqlx::query(
r#"
WITH RECURSIVE descendants AS (
SELECT id FROM storage.folders WHERE id = $1::uuid
UNION ALL
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
)
UPDATE storage.files
SET is_trashed = TRUE, trashed_at = NOW(), original_folder_id = folder_id
WHERE folder_id IN (SELECT id FROM descendants) AND NOT is_trashed
"#,
)
.bind(folder_id)
.execute(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("trash files: {e}")))?;
Ok(())
}
@@ -475,48 +465,45 @@ impl FolderRepository for FolderDbRepository {
folder_id: &str,
_original_path: &str,
) -> Result<(), DomainError> {
// Restore: set is_trashed = false, restore parent_id from original_parent_id
let result = sqlx::query(
// Atomic CTE: restore folder + all descendant files in a single statement.
let result = sqlx::query_scalar::<_, i64>(
r#"
UPDATE storage.folders
SET is_trashed = FALSE,
trashed_at = NULL,
parent_id = COALESCE(original_parent_id, parent_id),
original_parent_id = NULL,
updated_at = NOW()
WHERE id = $1::uuid AND is_trashed
WITH restore_folder AS (
UPDATE storage.folders
SET is_trashed = FALSE,
trashed_at = NULL,
parent_id = COALESCE(original_parent_id, parent_id),
original_parent_id = NULL,
updated_at = NOW()
WHERE id = $1::uuid AND is_trashed
RETURNING id
),
descendants AS (
SELECT id FROM restore_folder
UNION ALL
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
),
restore_files AS (
UPDATE storage.files
SET is_trashed = FALSE,
trashed_at = NULL,
folder_id = COALESCE(original_folder_id, folder_id),
original_folder_id = NULL
WHERE folder_id IN (SELECT id FROM descendants) AND is_trashed
RETURNING 1
)
SELECT COUNT(*) FROM restore_folder
"#,
)
.bind(folder_id)
.execute(self.pool())
.fetch_one(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("restore: {e}")))?;
if result.rows_affected() == 0 {
if result == 0 {
return Err(DomainError::not_found("Folder", folder_id));
}
// Also restore files that were trashed with this folder
sqlx::query(
r#"
WITH RECURSIVE descendants AS (
SELECT id FROM storage.folders WHERE id = $1::uuid
UNION ALL
SELECT f.id FROM storage.folders f JOIN descendants d ON f.parent_id = d.id
)
UPDATE storage.files
SET is_trashed = FALSE,
trashed_at = NULL,
folder_id = COALESCE(original_folder_id, folder_id),
original_folder_id = NULL
WHERE folder_id IN (SELECT id FROM descendants) AND is_trashed
"#,
)
.bind(folder_id)
.execute(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("restore files: {e}")))?;
Ok(())
}
@@ -562,9 +549,7 @@ impl FolderDbRepository {
.map_err(|e| DomainError::internal_error("FolderDb", format!("home folder: {e}")))?;
match row {
Some((id, ca, ma)) => {
self.row_to_folder(id, name.to_string(), None, ca, ma).await
}
Some((id, ca, ma)) => self.row_to_folder(id, name.to_string(), None, ca, ma).await,
None => {
// Already exists — fetch it
let existing = sqlx::query_as::<_, (String, i64, i64)>(
@@ -580,9 +565,7 @@ impl FolderDbRepository {
.bind(user_id)
.fetch_one(self.pool())
.await
.map_err(|e| {
DomainError::internal_error("FolderDb", format!("home fetch: {e}"))
})?;
.map_err(|e| DomainError::internal_error("FolderDb", format!("home fetch: {e}")))?;
self.row_to_folder(existing.0, name.to_string(), None, existing.1, existing.2)
.await
}
@@ -591,13 +574,11 @@ impl FolderDbRepository {
/// Returns user_id for a given folder. Used by file repositories.
pub async fn get_folder_user_id(&self, folder_id: &str) -> Result<String, DomainError> {
sqlx::query_scalar::<_, String>(
"SELECT user_id FROM storage.folders WHERE id = $1::uuid",
)
.bind(folder_id)
.fetch_optional(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("user_id lookup: {e}")))?
.ok_or_else(|| DomainError::not_found("Folder", folder_id))
sqlx::query_scalar::<_, String>("SELECT user_id FROM storage.folders WHERE id = $1::uuid")
.bind(folder_id)
.fetch_optional(self.pool())
.await
.map_err(|e| DomainError::internal_error("FolderDb", format!("user_id lookup: {e}")))?
.ok_or_else(|| DomainError::not_found("Folder", folder_id))
}
}
@@ -86,9 +86,7 @@ impl TrashRepository for TrashDbRepository {
.bind(user_id.to_string())
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("TrashDb", format!("list: {e}"))
})?;
.map_err(|e| DomainError::internal_error("TrashDb", format!("list: {e}")))?;
Ok(rows
.into_iter()
@@ -98,11 +96,7 @@ impl TrashRepository for TrashDbRepository {
.collect())
}
async fn get_trash_item(
&self,
id: &Uuid,
user_id: &Uuid,
) -> Result<Option<TrashedItem>> {
async fn get_trash_item(&self, id: &Uuid, user_id: &Uuid) -> Result<Option<TrashedItem>> {
let row = sqlx::query_as::<_, (Uuid, String, String, String, Option<DateTime<Utc>>)>(
r#"
SELECT id, name, item_type, user_id, trashed_at
@@ -114,9 +108,7 @@ impl TrashRepository for TrashDbRepository {
.bind(user_id.to_string())
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("TrashDb", format!("get: {e}"))
})?;
.map_err(|e| DomainError::internal_error("TrashDb", format!("get: {e}")))?;
Ok(row.map(|(id, name, item_type, uid, trashed_at)| {
self.row_to_trashed_item(id, name, item_type, uid, trashed_at)
@@ -139,26 +131,18 @@ impl TrashRepository for TrashDbRepository {
async fn clear_trash(&self, user_id: &Uuid) -> Result<()> {
// Delete all trashed files for this user
sqlx::query(
"DELETE FROM storage.files WHERE user_id = $1 AND is_trashed = TRUE",
)
.bind(user_id.to_string())
.execute(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("TrashDb", format!("clear files: {e}"))
})?;
sqlx::query("DELETE FROM storage.files WHERE user_id = $1 AND is_trashed = TRUE")
.bind(user_id.to_string())
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("TrashDb", format!("clear files: {e}")))?;
// Delete all trashed folders for this user
sqlx::query(
"DELETE FROM storage.folders WHERE user_id = $1 AND is_trashed = TRUE",
)
.bind(user_id.to_string())
.execute(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("TrashDb", format!("clear folders: {e}"))
})?;
sqlx::query("DELETE FROM storage.folders WHERE user_id = $1 AND is_trashed = TRUE")
.bind(user_id.to_string())
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::internal_error("TrashDb", format!("clear folders: {e}")))?;
Ok(())
}
@@ -177,9 +161,7 @@ impl TrashRepository for TrashDbRepository {
.bind(cutoff)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| {
DomainError::internal_error("TrashDb", format!("expired: {e}"))
})?;
.map_err(|e| DomainError::internal_error("TrashDb", format!("expired: {e}")))?;
Ok(rows
.into_iter()
+2 -7
View File
@@ -209,9 +209,7 @@ impl DedupService {
}
// Atomic write: temp file → rename
let temp_path = self
.temp_root
.join(format!("{}.tmp", uuid::Uuid::new_v4()));
let temp_path = self.temp_root.join(format!("{}.tmp", uuid::Uuid::new_v4()));
fs::write(&temp_path, content).await.map_err(|e| {
DomainError::internal_error("Dedup", format!("Failed to write temp blob: {}", e))
})?;
@@ -258,10 +256,7 @@ impl DedupService {
let file_size = fs::metadata(source_path)
.await
.map_err(|e| {
DomainError::internal_error(
"Dedup",
format!("Failed to get file metadata: {}", e),
)
DomainError::internal_error("Dedup", format!("Failed to get file metadata: {}", e))
})?
.len();
+20 -20
View File
@@ -171,7 +171,7 @@ async fn handle_propfind(
if path.is_empty() {
// Root CalDAV path — list user's calendars
let calendars = calendar_service
.list_my_calendars_for_user(&user.id)
.list_my_calendars(&user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list calendars: {}", e)))?;
@@ -198,13 +198,13 @@ async fn handle_propfind(
if parts.len() == 1 {
// Calendar collection
let calendar = calendar_service
.get_calendar_for_user(calendar_id, &user.id)
.get_calendar(calendar_id, &user.id)
.await
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
let events = if depth != "0" {
calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.unwrap_or_default()
} else {
@@ -235,7 +235,7 @@ async fn handle_propfind(
let ical_uid = event_file.trim_end_matches(".ics");
let events = calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
@@ -295,14 +295,14 @@ async fn handle_report(
CalDavReportType::CalendarQuery { time_range, .. } => {
if let Some((start, end)) = time_range {
calendar_service
.get_events_in_range_for_user(calendar_id, *start, *end, &user.id)
.get_events_in_range(calendar_id, *start, *end, &user.id)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to query events: {}", e))
})?
} else {
calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| {
AppError::internal_error(format!("Failed to list events: {}", e))
@@ -311,7 +311,7 @@ async fn handle_report(
}
CalDavReportType::CalendarMultiget { hrefs, .. } => {
let all_events = calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
@@ -321,7 +321,7 @@ async fn handle_report(
.collect()
}
CalDavReportType::SyncCollection { .. } => calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?,
};
@@ -377,7 +377,7 @@ async fn handle_mkcalendar(
};
calendar_service
.create_calendar_for_user(create_dto, &user.id)
.create_calendar(create_dto, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to create calendar: {}", e)))?;
@@ -417,7 +417,7 @@ async fn handle_put(
let existing = if let Some(ref uid) = ical_uid {
let events = calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.unwrap_or_default();
events.into_iter().find(|e| e.ical_uid == *uid)
@@ -428,7 +428,7 @@ async fn handle_put(
if let Some(existing_event) = existing {
// Update existing event — re-create from iCal for full fidelity
calendar_service
.delete_event_for_user(&existing_event.id, &user.id)
.delete_event(&existing_event.id, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to update event: {}", e)))?;
@@ -437,7 +437,7 @@ async fn handle_put(
ical_data,
};
let event = calendar_service
.create_event_from_ical_for_user(create_dto, &user.id)
.create_event_from_ical(create_dto, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to recreate event: {}", e)))?;
@@ -453,7 +453,7 @@ async fn handle_put(
};
let event = calendar_service
.create_event_from_ical_for_user(create_dto, &user.id)
.create_event_from_ical(create_dto, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to create event: {}", e)))?;
@@ -492,12 +492,12 @@ async fn handle_get(
if parts.len() < 2 {
// GET on calendar collection
let events = calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
let calendar = calendar_service
.get_calendar_for_user(calendar_id, &user.id)
.get_calendar(calendar_id, &user.id)
.await
.map_err(|e| AppError::not_found(format!("Calendar not found: {}", e)))?;
@@ -515,7 +515,7 @@ async fn handle_get(
let ical_uid = event_file.trim_end_matches(".ics");
let events = calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
@@ -602,7 +602,7 @@ async fn handle_delete(
if parts.len() < 2 {
calendar_service
.delete_calendar_for_user(calendar_id, &user.id)
.delete_calendar(calendar_id, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to delete calendar: {}", e)))?;
} else {
@@ -610,7 +610,7 @@ async fn handle_delete(
let ical_uid = event_file.trim_end_matches(".ics");
let events = calendar_service
.list_events_for_user(calendar_id, None, None, &user.id)
.list_events(calendar_id, None, None, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to list events: {}", e)))?;
@@ -620,7 +620,7 @@ async fn handle_delete(
.ok_or_else(|| AppError::not_found(format!("Event not found: {}", ical_uid)))?;
calendar_service
.delete_event_for_user(&event.id, &user.id)
.delete_event(&event.id, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to delete event: {}", e)))?;
}
@@ -675,7 +675,7 @@ async fn handle_proppatch(
if update.name.is_some() || update.description.is_some() || update.color.is_some() {
calendar_service
.update_calendar_for_user(calendar_id, update, &user.id)
.update_calendar(calendar_id, update, &user.id)
.await
.map_err(|e| AppError::internal_error(format!("Failed to update calendar: {}", e)))?;
}
+111 -63
View File
@@ -1,19 +1,19 @@
use std::sync::Arc;
use std::collections::HashMap;
use axum::{
extract::{Path, State, Query},
http::{StatusCode, header, HeaderName, HeaderValue, Response},
response::IntoResponse,
Json,
extract::{Path, Query, State},
http::{HeaderName, HeaderValue, Response, StatusCode, header},
response::IntoResponse,
};
use std::collections::HashMap;
use std::sync::Arc;
use crate::application::services::folder_service::FolderService;
use crate::application::dtos::folder_dto::{CreateFolderDto, RenameFolderDto, MoveFolderDto};
use crate::application::dtos::folder_dto::{CreateFolderDto, MoveFolderDto, RenameFolderDto};
use crate::application::dtos::pagination::PaginationRequestDto;
use crate::common::errors::ErrorKind;
use crate::application::ports::inbound::FolderUseCase;
use crate::application::services::folder_service::FolderService;
use crate::common::di::AppState as GlobalAppState;
use crate::interfaces::middleware::auth::{OptionalAuthUser, AuthUser};
use crate::common::errors::ErrorKind;
use crate::interfaces::middleware::auth::{AuthUser, OptionalAuthUser};
type AppState = Arc<FolderService>;
@@ -37,14 +37,16 @@ impl FolderHandler {
let home_folder_name = format!("My Folder - {}", auth_user.username);
tracing::info!(
"create_folder: parent_id is None for user '{}', looking up home folder '{}'",
auth_user.username, home_folder_name
auth_user.username,
home_folder_name
);
match service.list_folders(None).await {
Ok(folders) => {
if let Some(home) = folders.iter().find(|f| f.name == home_folder_name) {
tracing::info!(
"create_folder: resolved home folder ID '{}' for user '{}'",
home.id, auth_user.username
home.id,
auth_user.username
);
dto.parent_id = Some(home.id.clone());
} else {
@@ -55,7 +57,10 @@ impl FolderHandler {
}
}
Err(e) => {
tracing::error!("create_folder: failed to list folders for home resolution: {}", e);
tracing::error!(
"create_folder: failed to list folders for home resolution: {}",
e
);
}
}
}
@@ -145,18 +150,20 @@ impl FolderHandler {
parent_id: Option<&str>,
) -> axum::response::Response {
match service.list_folders(parent_id).await {
Ok(folders) => {
(StatusCode::OK, Json(folders)).into_response()
},
Ok(folders) => (StatusCode::OK, Json(folders)).into_response(),
Err(err) => {
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(serde_json::json!({
"error": err.to_string()
}))).into_response()
(
status,
Json(serde_json::json!({
"error": err.to_string()
})),
)
.into_response()
}
}
}
@@ -172,31 +179,38 @@ impl FolderHandler {
Ok(folders) => {
// Only filter at root level (parent_id == None)
let filtered = if parent_id.is_none() {
folders.into_iter().filter(|f| {
// Skip hidden/system folders
if f.name.starts_with('.') {
return false;
}
// If it's a user home folder, only show if it belongs to this user
if Self::is_user_home_folder(&f.name) {
return Self::folder_belongs_to_user(&f.name, &auth_user.username);
}
// Non-home folders are visible to everyone
true
}).collect()
folders
.into_iter()
.filter(|f| {
// Skip hidden/system folders
if f.name.starts_with('.') {
return false;
}
// If it's a user home folder, only show if it belongs to this user
if Self::is_user_home_folder(&f.name) {
return Self::folder_belongs_to_user(&f.name, &auth_user.username);
}
// Non-home folders are visible to everyone
true
})
.collect()
} else {
folders
};
(StatusCode::OK, Json(filtered)).into_response()
},
}
Err(err) => {
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(serde_json::json!({
"error": err.to_string()
}))).into_response()
(
status,
Json(serde_json::json!({
"error": err.to_string()
})),
)
.into_response()
}
}
}
@@ -208,9 +222,7 @@ impl FolderHandler {
parent_id: Option<&str>,
) -> axum::response::Response {
match service.list_folders_paginated(parent_id, &pagination).await {
Ok(paginated_result) => {
(StatusCode::OK, Json(paginated_result)).into_response()
},
Ok(paginated_result) => (StatusCode::OK, Json(paginated_result)).into_response(),
Err(err) => {
let status = match err.kind {
ErrorKind::NotFound => StatusCode::NOT_FOUND,
@@ -218,9 +230,13 @@ impl FolderHandler {
};
// Return a JSON error response
(status, Json(serde_json::json!({
"error": err.to_string()
}))).into_response()
(
status,
Json(serde_json::json!({
"error": err.to_string()
})),
)
.into_response()
}
}
}
@@ -241,9 +257,13 @@ impl FolderHandler {
};
// Return a proper JSON error response
(status, Json(serde_json::json!({
"error": err.to_string()
}))).into_response()
(
status,
Json(serde_json::json!({
"error": err.to_string()
})),
)
.into_response()
}
}
}
@@ -293,7 +313,10 @@ impl FolderHandler {
OptionalAuthUser(auth_user): OptionalAuthUser,
Path(id): Path<String>,
) -> impl IntoResponse {
let user_id = auth_user.as_ref().map(|u| u.id.as_str()).unwrap_or("anonymous");
let user_id = auth_user
.as_ref()
.map(|u| u.id.as_str())
.unwrap_or("anonymous");
// Check if trash service is available
if let Some(trash_service) = &state.trash_service {
tracing::info!("Moving folder to trash: {}", id);
@@ -303,9 +326,12 @@ impl FolderHandler {
Ok(_) => {
tracing::info!("Folder successfully moved to trash: {}", id);
return StatusCode::NO_CONTENT.into_response();
},
}
Err(err) => {
tracing::warn!("Could not move folder to trash, falling back to permanent delete: {}", err);
tracing::warn!(
"Could not move folder to trash, falling back to permanent delete: {}",
err
);
// Fall through to regular delete if trash fails
}
}
@@ -317,7 +343,7 @@ impl FolderHandler {
Ok(_) => {
tracing::info!("Folder permanently deleted: {}", id);
StatusCode::NO_CONTENT.into_response()
},
}
Err(err) => {
tracing::error!("Error deleting folder: {}", err);
@@ -326,9 +352,13 @@ impl FolderHandler {
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(serde_json::json!({
"error": format!("Error deleting folder: {}", err)
}))).into_response()
(
status,
Json(serde_json::json!({
"error": format!("Error deleting folder: {}", err)
})),
)
.into_response()
}
}
}
@@ -354,7 +384,10 @@ impl FolderHandler {
// Create the ZIP file
match zip_service.create_folder_zip(&id, &folder.name).await {
Ok(zip_data) => {
tracing::info!("ZIP file created successfully, size: {} bytes", zip_data.len());
tracing::info!(
"ZIP file created successfully, size: {} bytes",
zip_data.len()
);
// Setup headers for download
let filename = format!("{}.zip", folder.name);
@@ -362,9 +395,16 @@ impl FolderHandler {
// Build response with the ZIP data
let mut headers = HashMap::new();
headers.insert(header::CONTENT_TYPE.to_string(), "application/zip".to_string());
headers.insert(header::CONTENT_DISPOSITION.to_string(), content_disposition);
headers.insert(header::CONTENT_LENGTH.to_string(), zip_data.len().to_string());
headers.insert(
header::CONTENT_TYPE.to_string(),
"application/zip".to_string(),
);
headers
.insert(header::CONTENT_DISPOSITION.to_string(), content_disposition);
headers.insert(
header::CONTENT_LENGTH.to_string(),
zip_data.len().to_string(),
);
// Build the response
let mut response = Response::builder()
@@ -376,20 +416,24 @@ impl FolderHandler {
for (name, value) in headers {
response.headers_mut().insert(
HeaderName::from_bytes(name.as_bytes()).unwrap(),
HeaderValue::from_str(&value).unwrap()
HeaderValue::from_str(&value).unwrap(),
);
}
response
},
}
Err(err) => {
tracing::error!("Error creating ZIP file: {}", err);
(StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({
"error": format!("Error creating ZIP file: {}", err)
}))).into_response()
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"error": format!("Error creating ZIP file: {}", err)
})),
)
.into_response()
}
}
},
}
Err(err) => {
tracing::error!("Folder not found: {}", err);
let status = match err.kind {
@@ -397,9 +441,13 @@ impl FolderHandler {
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
(status, Json(serde_json::json!({
"error": format!("Error finding folder: {}", err)
}))).into_response()
(
status,
Json(serde_json::json!({
"error": format!("Error finding folder: {}", err)
})),
)
.into_response()
}
}
}