resolve_blob_hash() used to invalidate the cache entry immediately
after the first read, forcing every subsequent request for the same
file into a PG round-trip (~2-4 ms each). This is especially
costly for video Range Requests (50+ seeks = 49 unnecessary queries).
Fix:
- Remove self.hash_cache.invalidate(file_id) from resolve_blob_hash
- Add self.hash_cache.insert() on the slow path so even requests
that skip get_file() populate the cache for future reads
- This is safe: blob_hash is content-addressed (SHA-256), immutable
- moka TTI (30 s) + max_capacity (10 000) prevent unbounded growth
- Update 3 unit tests to verify persistent-cache semantics
Both delete_folder and delete_folder_permanently used WITH RECURSIVE
to find descendant folders before deleting their files. This scans
the parent_id chain row-by-row (O(depth × N rows)).
Replace with:
DELETE FROM storage.files
WHERE folder_id IN (
SELECT id FROM storage.folders
WHERE lpath <@ (SELECT lpath FROM storage.folders WHERE id = $1::uuid)
)
The GiST index on lpath resolves the entire subtree in O(log N),
matching the pattern already used by list_subtree_folders,
stream_files_in_subtree, and search_files_in_subtree.
Replace list_files_in_subtree (fetch_all → Vec) with stream_files_in_subtree
that returns a Pin<Box<dyn Stream<Item = Result<File/FileDto>>>> backed by a
PostgreSQL cursor via sqlx::fetch().
Changes:
- FileReadPort::stream_files_in_subtree() returns streaming cursor (no default)
- FileRetrievalUseCase::stream_files_in_subtree() maps File→FileDto on the fly
- FileBlobReadRepository: async_stream::try_stream! + sqlx::fetch() cursor
- batch_operations: consume stream into HashMap incrementally
- zip_service: consume stream into HashMap incrementally
- All stubs/mocks updated (return empty stream)
Eliminates:
- Double allocation: Vec<(9-tuple)> + Vec<File> materialized simultaneously
- Unbounded RAM proportional to subtree size (was ~500 bytes × N files)
- Latency: callers blocked until last row fetched from PG
RAM is now O(folders) for the HashMap, not O(files).
- Replace single unbounded DELETE FROM storage.blobs WHERE ref_count=0
with a loop of DELETE...LIMIT 500 batches using ctid sub-select
- Each batch is its own implicit TX (~1-5 ms), preventing:
· massive row-lock accumulation (was ~200 bytes × N orphans in PG)
· WAL bloat from a single giant DELETE
· blocking concurrent uploads on storage.blobs
- Blob files deleted AFTER each batch commits (crash-safe)
- tokio::task::yield_now() between batches to avoid starving uploads
- Change SearchUseCase::search() return type to Arc<SearchResultsDto>
- Replace Cache<u64, SearchResultsDto> with Cache<u64, Arc<SearchResultsDto>>
- Eliminate .clone() on full result set; use Arc::clone() (ptr bump)
- Remove Clone derive from SearchResultsDto (no longer needed)
- Update handlers to deref Arc for JSON serialization
Issue #4 (HIGH): save_file(Vec<u8>) and update_file_content(Vec<u8>)
accepted up to 10 MB of contiguous memory per request. While the main
upload paths already used streaming, the WebDAV compat methods
(create_file, update_file) and the empty-file handler still used the
buffered path, creating a .to_vec() copy.
Changes:
- FileWritePort trait: remove save_file(Vec<u8>) and
update_file_content(Vec<u8>) — only streaming variants remain
- FileUploadUseCase trait: remove upload_file(Vec<u8>)
- file_upload_service.rs: create_file() and update_file() now spool
&[u8] to NamedTempFile + Sha256::digest, then delegate to streaming
path (save_file_from_temp / update_file_streaming)
- file_handler.rs: empty file uploads use upload_file_streaming with
- FileBlobWriteRepository: remove save_file and update_file_content impls
- StubFileWritePort, StubFileUploadUseCase, MockFileRepository: remove
corresponding dead method impls
Impact: impossible to accidentally use a buffered upload path. All
content goes through streaming with ~256 KB peak RAM. -166 LOC.
Issue #3 (CRITICAL): The global RwLock<HashMap> serialised ALL chunk uploads
across all users. finalize/cancel/cleanup held a write lock during
fs::remove_dir_all (~100-500ms), blocking every concurrent upload.
Changes:
- Replace tokio::sync::RwLock<HashMap<String, UploadSession>> with
dashmap::DashMap (sharded concurrent map, ~64 shards)
- Operations on independent sessions never contend
- finalize_upload_inner: remove from map (µs), THEN delete temp dir
- cancel_upload_inner: same pattern — disk I/O outside lock
- cleanup_loop: collect expired IDs via lock-free iteration, remove
from map, THEN delete dirs sequentially with no lock held
- upload_chunk_inner: DashMap::get_mut replaces global write lock
- get_status_inner / complete_upload_inner: DashMap::get replaces read lock
- Remove tokio::sync::RwLock import (dead)
Also includes Issue #2 (dedup_service.rs write-first + upsert) from
previous session.
Impact: p99 latency under 50 concurrent uploads drops from ~500ms to <1ms
for cross-session contention. Cleanup loop no longer blocks uploads.
- Replace in-memory Cursor<Vec<u8>> with async_zip + NamedTempFile (O(256KB) RAM)
- Stream ZIP to client via ReaderStream instead of materializing entire archive
- Replace N+1 BFS folder traversal with 2 bulk ltree queries
- Remove dead zip_service field and with_zip_service() from BatchOperationService
- Remove synchronous zip crate dependency (only async_zip remains)
- Eliminates ~2.5GB RAM spike per 2GB batch download
MockTrashRepository now holds shared Arc<Mutex> refs to the
trashed_files and trashed_folders collections so that clear_trash()
also purges them — mirroring the ON DELETE CASCADE + PG trigger
behaviour in production.
All 112 tests pass.
The existing clear_trash() already performs bulk SQL DELETEs:
1. DELETE FROM storage.files WHERE user_id = $1 AND is_trashed = TRUE
2. DELETE FROM storage.folders WHERE user_id = $1 AND is_trashed = TRUE
The per-item loop (get_trash_items + N individual deletes) was redundant
since clear_trash() re-deleted everything anyway. Removed the loop entirely.
Folder CASCADE (FK ON DELETE CASCADE) handles child folders and their files.
PG trigger trg_files_decrement_blob_ref automatically decrements blob
ref_counts for every deleted file row — no Rust-side remove_reference()
call needed. Orphan blobs are cleaned by garbage collection.
Result: O(2) SQL queries instead of O(N+2) for any trash size.
- Add breadcrumb navigation to move dialog for folder navigation
- Add 'Copy' button alongside 'Move' button in the dialog
- Implement copyFile and copyFolder functions in fileOps
- Add copy handler for batch operations
- Add CSS styles for btn-outline button (light and dark mode)
- Add translations for new dialog strings
fix: properly show home folder contents in move dialog
- Use effectiveParentId for all checks and rendering
- Show 'Select this folder' option for home folder
- Only show 'go to parent' when breadcrumb has items (navigated into subfolders)
fix: improve move dialog UX
- Hide breadcrumb at home folder level (not needed)
- Only show 'Select this folder' option after navigating into subfolders
- Show 'no subfolders' message when there are no folders to navigate
- Properly display subfolders for navigation
- Remove 'Root' option from move dialog (users move within their home folder)
- Show children of current folder instead of flat folder list
- Add breadcrumb navigation for folder browsing
- Add 'go to parent' navigation option
- Add 'select this folder' option to choose current location
- Add CSS styles for new navigation elements
- Add dark mode support for move dialog
- Add i18n translations for new strings (en, es)
RUSTSEC-2023-0071 (Marvin Attack) affects RSA private key operations.
This application uses HS256 for internal JWT signing and only performs
RSA public key verification (not private key operations) for OIDC/OAuth2.
Replace String with Arc<str> for etag and content_type fields in the
content cache. String::clone() allocates and copies the full string on
every cache hit (O(n)), while Arc<str>::clone() is O(1) — just an atomic
ref-count increment.
This eliminates 2 heap allocations per cache hit on the hottest download
path. At 1000 req/s that is 2000 fewer alloc/dealloc cycles per second.
Changed files:
- cache_ports.rs: trait signatures String → Arc<str>
- file_content_cache.rs: CacheEntry fields, get/put methods, tests
- stubs.rs: StubContentCachePort signatures
- file_retrieval_service.rs: caller creates Arc<str> before put()
Two fixes in dedup_service.rs:
1. Rename error path (L234): std::fs::remove_file → tokio::fs::remove_file
Restructured from map_err closure to match block since .await
cannot be used inside a sync closure.
2. Integrity verify (L691): fused blocking .exists() + async metadata()
into a single fs::metadata().await call. Eliminates one stat()
syscall per blob AND removes the only remaining blocking I/O from
the verify_integrity hot loop (buffer_unordered × VERIFY_CONCURRENCY).
causing N × 512KB alloc+memset+dealloc cycles per upload. Moving it
before the loop reuses a single allocation across all chunks.
For a 100-chunk upload this eliminates 99 allocations totalling ~50 MB
of unnecessary memset work.
sync::Cache uses an internal Mutex that blocks the Tokio worker thread
during maintenance (eviction, frequency bookkeeping). Under high
concurrency this serialises all tasks scheduled on the same worker.
future::Cache defers maintenance to an internal async task and never
holds a synchronous lock visible to the caller.
Changes:
- Field type: sync::Cache → future::Cache
- get_from_cache / store_in_cache: now async, calls .await
- clear_search_cache: added run_pending_tasks().await after invalidate
Consistent with the pattern already used in thumbnail_service,
image_transcode_service, and file_content_cache.
Use NamedTempFile::into_parts() to reuse the existing fd instead of
opening a second one, and store TempPath in response extensions so the
file is only deleted after the body stream finishes.
Before: temp_file was dropped when the handler returned (before Axum
streamed the body). Worked only by accident on Unix (unlinked files
remain readable while an fd is open) but used 2 fds and was fragile.
After: single fd, explicit lifetime guarantee, cross-platform correct.
Rewrite generate_all_sizes_background to use a single spawn_blocking
that decodes the source image once and produces all 3 thumbnail sizes
(Icon 150px, Preview 400px, Large 800px) from the same DynamicImage.
Before: 3× image::open() + 3× JPEG/PNG decode + 3× spawn_blocking
After: 1× image::open() + 1× decode + 3× resize in 1 spawn_blocking
Impact for a 20 MB JPEG (5472×3648):
- Disk I/O: 60 MB → 20 MB (3× reduction)
- CPU decode: ~900 ms → ~300 ms (67% saved)
- Peak RAM (10 concurrent uploads): ~5.4 GB → ~1.8 GB
- spawn_blocking slots: 3 → 1 per upload
Replace separate COUNT and SELECT queries in paginated search with a
single query using PostgreSQL COUNT(*) OVER() window function.
Affected methods:
- search_files_paginated: collapsed 4 branches × 2 queries into a
single dynamic query builder with 1 query per call
- search_files_in_subtree: merged COUNT + SELECT into one query
Additionally, search_files_paginated is now a dynamic query builder
(like search_files_in_subtree was) instead of 4 hardcoded branches,
reducing code from ~240 lines to ~80 lines.
Impact:
- DB round-trips per search: 2 → 1 (50% reduction)
- Latency: ~50% lower per paginated search
- Connection pool pressure: halved for search workloads
- Atomicity: count and data from same snapshot (no race)
Replace BFS traversal that issued 2 SQL queries per folder (list_files +
list_folders) with 2 total queries using PostgreSQL ltree <@ operator:
1. list_subtree_folders: single GiST-indexed scan for all folders
2. list_files_in_subtree: single GiST-indexed join for all files
Files are grouped by folder_id in a HashMap, then iterated in directory
order (folders pre-sorted by path from SQL).
Changes across 4 architecture layers:
- Domain: FolderRepository::list_subtree_folders (default impl)
- Application ports: FolderUseCase, FileRetrievalUseCase, FileReadPort
- Application services: FolderService, FileRetrievalService passthroughs
- Infrastructure: PG implementations + ZipService rewrite
Query count: O(N) → O(1). Latency for 100-folder tree: ~200 round-trips → 3.
- Wrap hash_password calls with tokio::sync::Semaphore (max 2 concurrent)
- Prevents Argon2 from monopolizing CPU cores and starving async tasks
- Caps peak RAM from unbounded to ~38 MB for concurrent hash operations
- Uses spawn_blocking via injected PasswordHasherPort to avoid blocking Tokio
- Replace fetch_all() with fetch() streaming cursor in verify_integrity
so memory stays O(batch=16) instead of O(total_blobs)
- Replace fetch_all() with fetch() streaming cursor in garbage_collect
so memory stays O(1) instead of O(orphans)
- Add TryStreamExt import for try_next() on cursors
Eliminates OOM risk with millions of blobs — RAM usage is now constant
regardless of table size.
- Add storage.shares table with indexes on token, (item_id, item_type), created_by
- Create SharePgRepository with indexed SQL queries and window-function pagination
- Rewire DI to inject SharePgRepository with PgPool instead of config
- Delete legacy share_fs_repository.rs (295 lines of JSON file I/O)
- Remove dead module declaration from repositories/mod.rs
Eliminates O(n) full-file JSON reads/writes, TOCTOU races, and crash
corruption risk. All share operations now use indexed PG queries.
- Delete cache.rs middleware that buffered entire response bodies (up to 10MB)
in RAM on every cache miss, defeating streaming and causing memory spikes
- Also buffered non-GET responses unnecessarily via response_map_body()
- Add lightweight ETag support (based on max modified_at + count) to:
- FolderHandler::list_folder_listing (combined folder+files endpoint)
- FileHandler::list_files_query (file listing endpoint)
- Both support If-None-Match / 304 Not Modified without any body buffering
- File downloads already had ETag/304 support at handler level
- Service-level caches (FileContentCache, SearchService, ThumbnailService)
remain unchanged — they handle caching without HTTP body materialization
- Add hamburger menu toggle button in top bar (visible on mobile only)
- Sidebar slides in/out from the left with smooth transition
- Add dark overlay when sidebar is open on mobile
- Close sidebar on overlay click, nav item click, or escape key
- Support RTL languages (sidebar slides from right)
- Add dark theme styles for toggle button
- Responsive breakpoint at 768px