perf: round 11 — StoragePath joined-only, classifier fusion, memoized bodies, query-shape pack, SPA fine-grained stars
Backend (each change benchmark-gated with BEFORE replicas + equivalence gates; see examples/bench_round11_micro.rs, bench_round11_queries.rs, bench_log_writer.rs and benches/ROUND11.md — final numbers land in the follow-up doc commit): - StoragePath re-representation: single canonical joined String, segments derived on demand; File/Folder drop the duplicated path_string field (4000→1000 allocs per 500-row listing page) - Display classifier fusion: classify_display shares one stack-lowered extension across the three decision trees; call sites in FileDto, folder/favorites/recent handlers, trash, path-resolver (+ interning where Arc::from was still used) - /status.php and /openapi.json memoized into OnceLock<Bytes> (openapi rebuilt a 171 KiB spec per request: 2.8 ms → 18 ns) - NC upload-session PROPFIND: write! + pre-sized body + stack RFC2822 dates (2.3-2.6x, 2582→772 allocs at 256 chunks) - REST download: dead FileDto clone removed (capture mime/size + move) - CalendarEventDto/TrashedItem into_parts moves (11 KiB ical_data memcpy gone per CalDAV row); CardDAV getlastmodified stack render - 4xx path: borrowed ErrorResponse serialize, ErrorKind::as_str, not_found/already_exists clone kill - vCard emit via write!; search page moved out with into_iter skip/take; content-hit UUIDs parsed once; group last-user check via HashSet - RateLimiter: lock-free get + insert (and_upsert_with variant REJECTED by benchmark); CSRF token borrow-compare + borrowed cookie extraction - Thumbnail/preview ETags built from as_str (Debug-identical bytes) - Encrypted backend: encrypt_in_place_detached single-buffer write path, chunk-sized reserve in collect_stream; retry labels made lazy - PG: deferred upload registration 3→1 round-trips (persist_file CTE template); direct_grant_cache for Calendar/AddressBook/Playlist authz (single-flight + set_role/clear_role invalidation); expand_user tokio::join!; geo clusters min(uuid)::text; recluster face assignment batched into one UNNEST update - People recluster cosine: norms precomputed once (bit-identical gate) - NC capabilities poll logs demoted to debug; tracing-appender dep added for the log-writer benchmark Frontend: - ResourceList.selectedEntries O(N)-per-toggle → id-index projection O(k log k); favorites/recent consume the batchToolbar snippet param and drop their duplicate filter + dead selectedIds mirror - Recent: star state via new favoriteIds prop — a star click no longer rebuilds all N entries - admin timeAgo >30d fallback uses the cached Intl.DateTimeFormat - vitest gates in src/lib/components/round11.bench.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ABhTEHuGujvwoodh67Kga7
This commit is contained in:
@@ -22,6 +22,25 @@ pub use super::entity_errors::CalendarEventError;
|
||||
* Represents a calendar event or appointment that can be synced via CalDAV.
|
||||
* Follows the iCalendar format (RFC 5545) for compatibility with CalDAV clients.
|
||||
*/
|
||||
/// Owned decomposition of a [`CalendarEvent`] (see
|
||||
/// [`CalendarEvent::into_parts`]).
|
||||
pub struct CalendarEventParts {
|
||||
pub id: Uuid,
|
||||
pub calendar_id: Uuid,
|
||||
pub summary: String,
|
||||
pub description: Option<String>,
|
||||
pub location: Option<String>,
|
||||
pub start_time: DateTime<Utc>,
|
||||
pub end_time: DateTime<Utc>,
|
||||
pub all_day: bool,
|
||||
pub rrule: Option<String>,
|
||||
pub recurrence_id: Option<DateTime<Utc>>,
|
||||
pub ical_uid: String,
|
||||
pub ical_data: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CalendarEvent {
|
||||
/// Unique identifier for the event
|
||||
@@ -456,6 +475,30 @@ impl CalendarEvent {
|
||||
&self.updated_at
|
||||
}
|
||||
|
||||
/// Decompose into owned parts for DTO conversion — the `File`/`Folder`/
|
||||
/// `Contact` pattern. Moving the owned `String`s (most importantly the
|
||||
/// unbounded `ical_data` blob, ~11 KB with attendees/VALARMs) replaces
|
||||
/// the per-event deep copies `CalendarEventDto::from` used to make via
|
||||
/// getters (benches/ROUND11.md §19).
|
||||
pub fn into_parts(self) -> CalendarEventParts {
|
||||
CalendarEventParts {
|
||||
id: self.id,
|
||||
calendar_id: self.calendar_id,
|
||||
summary: self.summary,
|
||||
description: self.description,
|
||||
location: self.location,
|
||||
start_time: self.start_time,
|
||||
end_time: self.end_time,
|
||||
all_day: self.all_day,
|
||||
rrule: self.rrule,
|
||||
recurrence_id: self.recurrence_id,
|
||||
ical_uid: self.ical_uid,
|
||||
ical_data: self.ical_data,
|
||||
created_at: self.created_at,
|
||||
updated_at: self.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the duration of the event
|
||||
pub fn duration(&self) -> Duration {
|
||||
self.end_time - self.start_time
|
||||
|
||||
@@ -16,7 +16,6 @@ pub struct FileParts {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub storage_path: StoragePath,
|
||||
pub path_string: String,
|
||||
pub size: u64,
|
||||
pub mime_type: String,
|
||||
pub folder_id: Option<String>,
|
||||
@@ -48,12 +47,11 @@ pub struct File {
|
||||
/// Name of the file including extension
|
||||
name: String,
|
||||
|
||||
/// Path to the file in the domain model
|
||||
/// Path to the file in the domain model. Owns the canonical joined
|
||||
/// string; `path_string()` borrows it (the separate duplicate field
|
||||
/// was removed in ROUND11 §20 along with per-segment allocations).
|
||||
storage_path: StoragePath,
|
||||
|
||||
/// String representation of the path for API compatibility
|
||||
path_string: String,
|
||||
|
||||
/// Size of the file in bytes
|
||||
size: u64,
|
||||
|
||||
@@ -99,7 +97,6 @@ impl Default for File {
|
||||
id: "stub-id".to_string(),
|
||||
name: "stub-file.txt".to_string(),
|
||||
storage_path: StoragePath::from_string("/"),
|
||||
path_string: "/".to_string(),
|
||||
size: 0,
|
||||
mime_type: "application/octet-stream".to_string(),
|
||||
folder_id: None,
|
||||
@@ -132,14 +129,10 @@ impl File {
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
// Store the path string for serialization compatibility
|
||||
let path_string = storage_path.to_path_string();
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
size,
|
||||
mime_type,
|
||||
folder_id,
|
||||
@@ -165,14 +158,10 @@ impl File {
|
||||
return Err(FileError::InvalidFileName(format!("{name}: {reason}")));
|
||||
}
|
||||
|
||||
// Store the path string for serialization compatibility
|
||||
let path_string = storage_path.to_path_string();
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
size: 0, // Folders have zero size
|
||||
mime_type: "directory".to_string(), // Standard MIME type for directories
|
||||
folder_id: parent_id,
|
||||
@@ -257,14 +246,10 @@ impl File {
|
||||
return Err(FileError::InvalidFileName(format!("{name}: {reason}")));
|
||||
}
|
||||
|
||||
// Store the path string for serialization compatibility
|
||||
let path_string = storage_path.to_path_string();
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
size,
|
||||
mime_type,
|
||||
folder_id,
|
||||
@@ -304,7 +289,7 @@ impl File {
|
||||
created_by: Option<Uuid>,
|
||||
updated_by: Option<Uuid>,
|
||||
) -> FileResult<Self> {
|
||||
let (storage_path, path_string) = StoragePath::from_folder_and_name(folder_path, &name);
|
||||
let storage_path = StoragePath::from_folder_and_name(folder_path, &name);
|
||||
|
||||
let name = normalize_storage_name_owned(name);
|
||||
if let Err(reason) = validate_storage_name(&name) {
|
||||
@@ -315,7 +300,6 @@ impl File {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
size,
|
||||
mime_type,
|
||||
folder_id,
|
||||
@@ -336,7 +320,6 @@ impl File {
|
||||
id: self.id,
|
||||
name: self.name,
|
||||
storage_path: self.storage_path,
|
||||
path_string: self.path_string,
|
||||
size: self.size,
|
||||
mime_type: self.mime_type,
|
||||
folder_id: self.folder_id,
|
||||
@@ -438,7 +421,7 @@ impl File {
|
||||
}
|
||||
|
||||
pub fn path_string(&self) -> &str {
|
||||
&self.path_string
|
||||
self.storage_path.as_str()
|
||||
}
|
||||
|
||||
pub fn size(&self) -> u64 {
|
||||
@@ -487,8 +470,9 @@ impl File {
|
||||
created_at: u64,
|
||||
modified_at: u64,
|
||||
) -> Self {
|
||||
// Create storage_path from string
|
||||
let storage_path = StoragePath::from_string(&path);
|
||||
// Adopt the DTO path (canonical inputs are reused with zero
|
||||
// copies; non-canonical ones are normalized like from_string did).
|
||||
let storage_path = StoragePath::from_joined(path);
|
||||
|
||||
// Create directly without validation to avoid errors in DTO
|
||||
// conversions. Still NFC-normalize so even DTO-reconstructed
|
||||
@@ -499,7 +483,6 @@ impl File {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string: path,
|
||||
size,
|
||||
mime_type,
|
||||
folder_id,
|
||||
@@ -536,7 +519,6 @@ impl File {
|
||||
// Consume `self` and mutate in place — only the path, name and mtime
|
||||
// change; id / mime_type / folder_id / blob_hash are carried over
|
||||
// without the per-field clone the old `&self` builder paid.
|
||||
self.path_string = new_storage_path.to_path_string();
|
||||
self.storage_path = new_storage_path;
|
||||
self.name = new_name;
|
||||
self.modified_at = now;
|
||||
@@ -561,7 +543,6 @@ impl File {
|
||||
.as_secs();
|
||||
|
||||
// Consume `self`: only the path, folder_id and mtime change.
|
||||
self.path_string = new_storage_path.to_path_string();
|
||||
self.storage_path = new_storage_path;
|
||||
self.folder_id = folder_id;
|
||||
self.modified_at = now;
|
||||
|
||||
@@ -17,7 +17,6 @@ pub struct FolderParts {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub storage_path: StoragePath,
|
||||
pub path_string: String,
|
||||
pub parent_id: Option<String>,
|
||||
/// Drive that owns this folder. See [`Folder::drive_id`].
|
||||
pub drive_id: Uuid,
|
||||
@@ -40,12 +39,10 @@ pub struct Folder {
|
||||
/// Name of the folder
|
||||
name: String,
|
||||
|
||||
/// Path to the folder in the domain model
|
||||
/// Path to the folder in the domain model. Owns the canonical joined
|
||||
/// string; `path_string()` borrows it (ROUND11 §20).
|
||||
storage_path: StoragePath,
|
||||
|
||||
/// String representation of the path (for API compatibility)
|
||||
path_string: String,
|
||||
|
||||
/// Parent folder ID (None if it's a root folder)
|
||||
parent_id: Option<String>,
|
||||
|
||||
@@ -94,7 +91,6 @@ impl Default for Folder {
|
||||
id: "stub-id".to_string(),
|
||||
name: "stub-folder".to_string(),
|
||||
storage_path: StoragePath::from_string("/"),
|
||||
path_string: "/".to_string(),
|
||||
parent_id: None,
|
||||
drive_id: Uuid::nil(),
|
||||
created_at: 0,
|
||||
@@ -130,13 +126,10 @@ impl Folder {
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
let path_string = storage_path.to_path_string();
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
parent_id,
|
||||
drive_id: Uuid::nil(),
|
||||
created_at: now,
|
||||
@@ -226,13 +219,10 @@ impl Folder {
|
||||
return Err(FolderError::InvalidFolderName(format!("{name}: {reason}")));
|
||||
}
|
||||
|
||||
let path_string = storage_path.to_path_string();
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
parent_id,
|
||||
drive_id,
|
||||
created_at,
|
||||
@@ -270,13 +260,12 @@ impl Folder {
|
||||
return Err(FolderError::InvalidFolderName(format!("{name}: {reason}")));
|
||||
}
|
||||
|
||||
let (storage_path, path_string) = StoragePath::from_joined(path);
|
||||
let storage_path = StoragePath::from_joined(path);
|
||||
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string,
|
||||
parent_id,
|
||||
drive_id,
|
||||
created_at,
|
||||
@@ -296,7 +285,6 @@ impl Folder {
|
||||
id: self.id,
|
||||
name: self.name,
|
||||
storage_path: self.storage_path,
|
||||
path_string: self.path_string,
|
||||
parent_id: self.parent_id,
|
||||
drive_id: self.drive_id,
|
||||
created_at: self.created_at,
|
||||
@@ -321,7 +309,7 @@ impl Folder {
|
||||
}
|
||||
|
||||
pub fn path_string(&self) -> &str {
|
||||
&self.path_string
|
||||
self.storage_path.as_str()
|
||||
}
|
||||
|
||||
pub fn parent_id(&self) -> Option<&str> {
|
||||
@@ -445,8 +433,8 @@ impl Folder {
|
||||
created_at: u64,
|
||||
modified_at: u64,
|
||||
) -> Self {
|
||||
// Create storage_path from the string
|
||||
let storage_path = StoragePath::from_string(&path);
|
||||
// Adopt the DTO path (canonical inputs reused with zero copies).
|
||||
let storage_path = StoragePath::from_joined(path);
|
||||
|
||||
// Create directly without validation to avoid errors in DTO
|
||||
// conversions. Still NFC-normalize so DTO-reconstructed
|
||||
@@ -460,7 +448,6 @@ impl Folder {
|
||||
id,
|
||||
name,
|
||||
storage_path,
|
||||
path_string: path,
|
||||
parent_id,
|
||||
// DTO round-trips lose drive_id (FolderDto carries it,
|
||||
// but the legacy `from_dto` signature predates this
|
||||
@@ -495,9 +482,6 @@ impl Folder {
|
||||
None => StoragePath::from_string(&new_name),
|
||||
};
|
||||
|
||||
// Update string representation
|
||||
let new_path_string = new_storage_path.to_path_string();
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
@@ -507,7 +491,6 @@ impl Folder {
|
||||
id: self.id.clone(),
|
||||
name: new_name,
|
||||
storage_path: new_storage_path,
|
||||
path_string: new_path_string,
|
||||
parent_id: self.parent_id.clone(),
|
||||
drive_id: self.drive_id,
|
||||
created_at: self.created_at,
|
||||
@@ -535,9 +518,6 @@ impl Folder {
|
||||
None => StoragePath::from_string(&self.name), // Root
|
||||
};
|
||||
|
||||
// Update string representation
|
||||
let new_path_string = new_storage_path.to_path_string();
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
@@ -547,7 +527,6 @@ impl Folder {
|
||||
id: self.id.clone(),
|
||||
name: self.name.clone(),
|
||||
storage_path: new_storage_path,
|
||||
path_string: new_path_string,
|
||||
parent_id,
|
||||
drive_id: self.drive_id,
|
||||
created_at: self.created_at,
|
||||
@@ -562,12 +541,9 @@ impl Folder {
|
||||
pub fn get_absolute_path<P: AsRef<std::path::Path>>(&self, root_path: P) -> std::path::PathBuf {
|
||||
let mut result = std::path::PathBuf::from(root_path.as_ref());
|
||||
|
||||
// Skip leading '/' from path_string to avoid creating absolute path incorrectly
|
||||
let relative_path = if self.path_string.starts_with('/') {
|
||||
&self.path_string[1..]
|
||||
} else {
|
||||
&self.path_string
|
||||
};
|
||||
// Skip leading '/' to avoid creating an absolute path incorrectly
|
||||
let path_string = self.storage_path.as_str();
|
||||
let relative_path = path_string.strip_prefix('/').unwrap_or(path_string);
|
||||
|
||||
if !relative_path.is_empty() {
|
||||
result.push(relative_path);
|
||||
|
||||
@@ -8,6 +8,17 @@ pub enum TrashedItemType {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
/// Owned decomposition of a [`TrashedItem`] (see
|
||||
/// [`TrashedItem::into_parts`]).
|
||||
pub struct TrashedItemParts {
|
||||
pub id: Uuid,
|
||||
pub original_id: Uuid,
|
||||
pub item_type: TrashedItemType,
|
||||
pub name: String,
|
||||
pub original_path: String,
|
||||
pub trashed_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub struct TrashedItem {
|
||||
id: Uuid,
|
||||
original_id: Uuid,
|
||||
@@ -98,6 +109,20 @@ impl TrashedItem {
|
||||
self.deletion_date
|
||||
}
|
||||
|
||||
/// Decompose into owned parts for DTO conversion — moves `name` /
|
||||
/// `original_path` instead of the getter clones `to_dto` used to make
|
||||
/// per trash row (benches/ROUND11.md; the File/Folder/Contact pattern).
|
||||
pub fn into_parts(self) -> TrashedItemParts {
|
||||
TrashedItemParts {
|
||||
id: self.id,
|
||||
original_id: self.original_id,
|
||||
item_type: self.item_type,
|
||||
name: self.name,
|
||||
original_path: self.original_path,
|
||||
trashed_at: self.trashed_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn days_until_deletion(&self) -> i64 {
|
||||
let now = Utc::now();
|
||||
(self.deletion_date - now).num_days().max(0)
|
||||
|
||||
+30
-17
@@ -41,21 +41,30 @@ pub enum ErrorKind {
|
||||
Conflict,
|
||||
}
|
||||
|
||||
impl ErrorKind {
|
||||
/// Stable human-readable name; `Display` delegates here so the two can
|
||||
/// never drift. Being `&'static` it lets the HTTP error path borrow the
|
||||
/// value instead of allocating per response (benches/ROUND11.md §9).
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
ErrorKind::NotFound => "Not Found",
|
||||
ErrorKind::AlreadyExists => "Already Exists",
|
||||
ErrorKind::InvalidInput => "Invalid Input",
|
||||
ErrorKind::AccessDenied => "Access Denied",
|
||||
ErrorKind::Timeout => "Timeout",
|
||||
ErrorKind::InternalError => "Internal Error",
|
||||
ErrorKind::NotImplemented => "Not Implemented",
|
||||
ErrorKind::UnsupportedOperation => "Unsupported Operation",
|
||||
ErrorKind::DatabaseError => "Database Error",
|
||||
ErrorKind::QuotaExceeded => "Quota Exceeded",
|
||||
ErrorKind::Conflict => "Conflict",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ErrorKind {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
|
||||
match self {
|
||||
ErrorKind::NotFound => write!(f, "Not Found"),
|
||||
ErrorKind::AlreadyExists => write!(f, "Already Exists"),
|
||||
ErrorKind::InvalidInput => write!(f, "Invalid Input"),
|
||||
ErrorKind::AccessDenied => write!(f, "Access Denied"),
|
||||
ErrorKind::Timeout => write!(f, "Timeout"),
|
||||
ErrorKind::InternalError => write!(f, "Internal Error"),
|
||||
ErrorKind::NotImplemented => write!(f, "Not Implemented"),
|
||||
ErrorKind::UnsupportedOperation => write!(f, "Unsupported Operation"),
|
||||
ErrorKind::DatabaseError => write!(f, "Database Error"),
|
||||
ErrorKind::QuotaExceeded => write!(f, "Quota Exceeded"),
|
||||
ErrorKind::Conflict => write!(f, "Conflict"),
|
||||
}
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,11 +100,14 @@ impl DomainError {
|
||||
/// Creates an entity not found error
|
||||
pub fn not_found<S: Into<String>>(entity_type: &'static str, entity_id: S) -> Self {
|
||||
let id = entity_id.into();
|
||||
// Message first, then move the id — the old `Some(id.clone())`
|
||||
// paid an extra allocation on every 404 construction.
|
||||
let message = format!("{} not found: {}", entity_type, id);
|
||||
Self {
|
||||
kind: ErrorKind::NotFound,
|
||||
entity_type,
|
||||
entity_id: Some(id.clone()),
|
||||
message: format!("{} not found: {}", entity_type, id),
|
||||
entity_id: Some(id),
|
||||
message,
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
@@ -103,11 +115,12 @@ impl DomainError {
|
||||
/// Creates an entity already exists error
|
||||
pub fn already_exists<S: Into<String>>(entity_type: &'static str, entity_id: S) -> Self {
|
||||
let id = entity_id.into();
|
||||
let message = format!("{} already exists: {}", entity_type, id);
|
||||
Self {
|
||||
kind: ErrorKind::AlreadyExists,
|
||||
entity_type,
|
||||
entity_id: Some(id.clone()),
|
||||
message: format!("{} already exists: {}", entity_type, id),
|
||||
entity_id: Some(id),
|
||||
message,
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
+123
-138
@@ -76,10 +76,25 @@ pub fn validate_storage_name(name: &str) -> Result<(), &'static str> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Represents a storage path in the domain (Value Object)
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||
/// Represents a storage path in the domain (Value Object).
|
||||
///
|
||||
/// Stored as the single **canonical joined form**: `"/"` for the root, or
|
||||
/// `/seg(/seg)*` with every segment safe (non-empty, not `.`/`..`, no
|
||||
/// `/`). Round 11 replaced the old `segments: Vec<String>` representation
|
||||
/// — one heap `String` per component built on EVERY hydrated listing row
|
||||
/// even though the DTO path only ever consumed the joined form — with this
|
||||
/// one-allocation shape; segment views are derived on demand
|
||||
/// (benches/ROUND11.md §20: 4 000 → 1 000 allocs on a 500-row page).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StoragePath {
|
||||
segments: Vec<String>,
|
||||
/// Canonical joined rendering (`Display`'s output).
|
||||
joined: String,
|
||||
}
|
||||
|
||||
impl Default for StoragePath {
|
||||
fn default() -> Self {
|
||||
Self::root()
|
||||
}
|
||||
}
|
||||
|
||||
impl StoragePath {
|
||||
@@ -88,20 +103,30 @@ impl StoragePath {
|
||||
!s.is_empty() && s != "." && s != ".." && !s.contains('/')
|
||||
}
|
||||
|
||||
/// Builds the canonical joined form from an iterator of raw segments,
|
||||
/// silently dropping unsafe ones. `cap` pre-sizes the buffer.
|
||||
fn build<'a>(segments: impl Iterator<Item = &'a str>, cap: usize) -> Self {
|
||||
let mut joined = String::with_capacity(cap);
|
||||
for seg in segments.filter(|s| Self::is_safe_segment(s)) {
|
||||
joined.push('/');
|
||||
joined.push_str(seg);
|
||||
}
|
||||
if joined.is_empty() {
|
||||
joined.push('/');
|
||||
}
|
||||
Self { joined }
|
||||
}
|
||||
|
||||
/// Creates a new storage path, silently dropping any traversal segments
|
||||
pub fn new(segments: Vec<String>) -> Self {
|
||||
Self {
|
||||
segments: segments
|
||||
.into_iter()
|
||||
.filter(|s| Self::is_safe_segment(s))
|
||||
.collect(),
|
||||
}
|
||||
let cap = segments.iter().map(|s| s.len() + 1).sum();
|
||||
Self::build(segments.iter().map(String::as_str), cap)
|
||||
}
|
||||
|
||||
/// Creates an empty path (root)
|
||||
pub fn root() -> Self {
|
||||
Self {
|
||||
segments: Vec::new(),
|
||||
joined: "/".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,81 +135,38 @@ impl StoragePath {
|
||||
/// Traversal segments (`.`, `..`) are silently stripped to prevent
|
||||
/// path-traversal attacks.
|
||||
pub fn from_string(path: &str) -> Self {
|
||||
let segments = path
|
||||
.split('/')
|
||||
.filter(|s| Self::is_safe_segment(s))
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
Self { segments }
|
||||
Self::build(path.split('/'), path.len() + 1)
|
||||
}
|
||||
|
||||
/// One-pass builder for PG listing rows: materialized folder path +
|
||||
/// file name → `(StoragePath, path_string)`.
|
||||
/// file name → the canonical joined path.
|
||||
///
|
||||
/// Replaces the old per-row chain
|
||||
/// `StoragePath::from_string(&format!("{fp}/{name}"))` +
|
||||
/// `storage_path.to_string()`, which allocated a joined temporary,
|
||||
/// split it back into per-segment `String`s, and then re-joined those
|
||||
/// segments (via `join` + `write!`) into the `path_string` the DTOs
|
||||
/// actually serve. Here both representations are built in a single
|
||||
/// pass with exactly one `String` for the joined form and no
|
||||
/// intermediate temporaries.
|
||||
///
|
||||
/// Byte-equivalence with the old chain holds because concatenating
|
||||
/// with a `/` separator distributes over `split('/')`:
|
||||
/// Byte-equivalence with the historical segment chain holds because
|
||||
/// concatenating with a `/` separator distributes over `split('/')`:
|
||||
/// `(fp + "/" + name).split('/') == fp.split('/') ⧺ name.split('/')`,
|
||||
/// and the joined form is exactly `Display`'s `/`-prefixed rendering
|
||||
/// of the surviving segments (root renders as `"/"`).
|
||||
pub fn from_folder_and_name(folder_path: Option<&str>, file_name: &str) -> (Self, String) {
|
||||
pub fn from_folder_and_name(folder_path: Option<&str>, file_name: &str) -> Self {
|
||||
let fp = folder_path.unwrap_or("");
|
||||
// Upper bounds: every byte of both inputs survives at most once,
|
||||
// plus one leading '/' per segment (≤ segment count) — sizing to
|
||||
// input length + 2 covers the worst case without a second scan.
|
||||
let mut joined = String::with_capacity(fp.len() + file_name.len() + 2);
|
||||
let mut segments: Vec<String> =
|
||||
Vec::with_capacity(fp.bytes().filter(|&b| b == b'/').count() + 2);
|
||||
for seg in fp
|
||||
.split('/')
|
||||
.chain(file_name.split('/'))
|
||||
.filter(|s| Self::is_safe_segment(s))
|
||||
{
|
||||
joined.push('/');
|
||||
joined.push_str(seg);
|
||||
segments.push(seg.to_string());
|
||||
}
|
||||
if segments.is_empty() {
|
||||
joined.push('/');
|
||||
}
|
||||
(Self { segments }, joined)
|
||||
Self::build(
|
||||
fp.split('/').chain(file_name.split('/')),
|
||||
fp.len() + file_name.len() + 2,
|
||||
)
|
||||
}
|
||||
|
||||
/// One-pass splitter for a pre-joined materialized path (the
|
||||
/// `storage.folders.path` column) → `(StoragePath, path_string)`.
|
||||
/// Wrapper for a pre-joined materialized path (the
|
||||
/// `storage.folders.path` column).
|
||||
///
|
||||
/// When the input is already in canonical joined form (leading `/`,
|
||||
/// no empty/`.`/`..` segments, no trailing `/`) — which is every row
|
||||
/// the repository writes — the input `String` is reused as the
|
||||
/// `path_string` with zero copies. Non-canonical inputs fall back to
|
||||
/// the filtering rebuild and produce exactly what
|
||||
/// `from_string(&path).to_string()` used to.
|
||||
pub fn from_joined(path: String) -> (Self, String) {
|
||||
/// When the input is already canonical (leading `/`, no empty/`.`/`..`
|
||||
/// segments, no trailing `/`) — which is every row the repository
|
||||
/// writes — the input `String` is adopted with zero copies.
|
||||
/// Non-canonical inputs fall back to the filtering rebuild and produce
|
||||
/// exactly what `from_string(&path)` yields.
|
||||
pub fn from_joined(path: String) -> Self {
|
||||
if Self::is_canonical_joined(&path) {
|
||||
let segments: Vec<String> = if path.len() == 1 {
|
||||
Vec::new()
|
||||
} else {
|
||||
path[1..].split('/').map(str::to_string).collect()
|
||||
};
|
||||
return (Self { segments }, path);
|
||||
return Self { joined: path };
|
||||
}
|
||||
// Fallback: identical to the old from_string + to_string pair.
|
||||
let segments: Vec<String> = path
|
||||
.split('/')
|
||||
.filter(|s| Self::is_safe_segment(s))
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
let sp = Self { segments };
|
||||
let joined = sp.to_path_string();
|
||||
(sp, joined)
|
||||
Self::from_string(&path)
|
||||
}
|
||||
|
||||
/// `true` when `path` is exactly `Display`'s canonical rendering of
|
||||
@@ -202,99 +184,99 @@ impl StoragePath {
|
||||
|
||||
/// Creates a path from a PathBuf
|
||||
pub fn from(path_buf: PathBuf) -> Self {
|
||||
let segments = path_buf
|
||||
.components()
|
||||
.filter_map(|c| match c {
|
||||
std::path::Component::Normal(os_str) => Some(os_str.to_string_lossy().to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
Self { segments }
|
||||
let mut joined = String::new();
|
||||
for c in path_buf.components() {
|
||||
if let std::path::Component::Normal(os_str) = c {
|
||||
let seg = os_str.to_string_lossy();
|
||||
if Self::is_safe_segment(&seg) {
|
||||
joined.push('/');
|
||||
joined.push_str(&seg);
|
||||
}
|
||||
}
|
||||
}
|
||||
if joined.is_empty() {
|
||||
joined.push('/');
|
||||
}
|
||||
Self { joined }
|
||||
}
|
||||
|
||||
/// Appends a segment to the path, consuming `self` so the existing
|
||||
/// segment buffer is reused instead of deep-cloned.
|
||||
/// buffer is reused instead of deep-cloned.
|
||||
///
|
||||
/// Traversal segments (`.`, `..`) and segments containing `/` are
|
||||
/// silently ignored to prevent path-traversal attacks.
|
||||
pub fn join(mut self, segment: &str) -> Self {
|
||||
if Self::is_safe_segment(segment) {
|
||||
self.segments.push(segment.to_string());
|
||||
if self.joined == "/" {
|
||||
self.joined.clear();
|
||||
}
|
||||
self.joined.push('/');
|
||||
self.joined.push_str(segment);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Gets the file name (last segment)
|
||||
pub fn file_name(&self) -> Option<String> {
|
||||
self.segments.last().cloned()
|
||||
if self.joined == "/" {
|
||||
None
|
||||
} else {
|
||||
self.joined.rsplit('/').next().map(str::to_string)
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the parent directory path
|
||||
pub fn parent(&self) -> Option<Self> {
|
||||
if self.segments.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let parent_segments = self.segments[..self.segments.len() - 1].to_vec();
|
||||
Some(Self {
|
||||
segments: parent_segments,
|
||||
})
|
||||
if self.joined == "/" {
|
||||
return None;
|
||||
}
|
||||
let cut = self.joined.rfind('/').expect("canonical path has '/'");
|
||||
Some(if cut == 0 {
|
||||
Self::root()
|
||||
} else {
|
||||
Self {
|
||||
joined: self.joined[..cut].to_string(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks if the path is empty (is the root)
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.segments.is_empty()
|
||||
self.joined == "/"
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for StoragePath {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.segments.is_empty() {
|
||||
return f.write_str("/");
|
||||
}
|
||||
// Write segments directly — the old `self.segments.join("/")`
|
||||
// allocated a full joined temporary inside every `format!`/
|
||||
// `to_string` of a path.
|
||||
for seg in &self.segments {
|
||||
f.write_str("/")?;
|
||||
f.write_str(seg)?;
|
||||
}
|
||||
Ok(())
|
||||
f.write_str(&self.joined)
|
||||
}
|
||||
}
|
||||
|
||||
impl StoragePath {
|
||||
/// The canonical joined form (`Display`'s output) in exactly one
|
||||
/// pre-sized allocation.
|
||||
///
|
||||
/// `to_string()` routes through `Display` into an unsized `String`
|
||||
/// that grows geometrically (multiple reallocs + copies for typical
|
||||
/// path lengths). Entity constructors call this once per row on
|
||||
/// every listing, so the sized single-alloc variant is the default
|
||||
/// there.
|
||||
/// The canonical joined form as an owned `String` (one memcpy).
|
||||
pub fn to_path_string(&self) -> String {
|
||||
if self.segments.is_empty() {
|
||||
return "/".to_string();
|
||||
}
|
||||
let mut s = String::with_capacity(self.segments.iter().map(|seg| seg.len() + 1).sum());
|
||||
for seg in &self.segments {
|
||||
s.push('/');
|
||||
s.push_str(seg);
|
||||
}
|
||||
s
|
||||
self.joined.clone()
|
||||
}
|
||||
|
||||
/// Returns the path representation as a string
|
||||
/// Consume `self`, yielding the canonical joined `String` with zero
|
||||
/// copies. This is the row→entity→DTO hand-off path.
|
||||
pub fn into_joined(self) -> String {
|
||||
self.joined
|
||||
}
|
||||
|
||||
/// Returns the path representation as a string (canonical joined form).
|
||||
pub fn as_str(&self) -> &str {
|
||||
// Note: The implementation should really store the string,
|
||||
// but here we do a temporary implementation that always returns "/"
|
||||
// This is only used for the get_folder_path_str implementation
|
||||
"/"
|
||||
&self.joined
|
||||
}
|
||||
|
||||
/// Gets the path segments
|
||||
pub fn segments(&self) -> &[String] {
|
||||
&self.segments
|
||||
/// Iterates the path segments (derived views over the joined form).
|
||||
pub fn segments(&self) -> impl Iterator<Item = &str> {
|
||||
let inner = if self.joined == "/" {
|
||||
""
|
||||
} else {
|
||||
&self.joined[1..]
|
||||
};
|
||||
inner.split('/').filter(|s| !s.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -305,7 +287,10 @@ mod tests {
|
||||
#[test]
|
||||
fn test_storage_path_from_string() {
|
||||
let path = StoragePath::from_string("folder/subfolder/file.txt");
|
||||
assert_eq!(path.segments(), &["folder", "subfolder", "file.txt"]);
|
||||
assert_eq!(
|
||||
path.segments().collect::<Vec<_>>(),
|
||||
&["folder", "subfolder", "file.txt"]
|
||||
);
|
||||
assert_eq!(path.to_string(), "/folder/subfolder/file.txt");
|
||||
}
|
||||
|
||||
@@ -341,19 +326,19 @@ mod tests {
|
||||
#[test]
|
||||
fn test_from_string_strips_dot_dot() {
|
||||
let path = StoragePath::from_string("../../etc/passwd");
|
||||
assert_eq!(path.segments(), &["etc", "passwd"]);
|
||||
assert_eq!(path.segments().collect::<Vec<_>>(), &["etc", "passwd"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_string_strips_single_dot() {
|
||||
let path = StoragePath::from_string("folder/./file.txt");
|
||||
assert_eq!(path.segments(), &["folder", "file.txt"]);
|
||||
assert_eq!(path.segments().collect::<Vec<_>>(), &["folder", "file.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_from_string_strips_mixed_traversal() {
|
||||
let path = StoragePath::from_string("a/../b/./c/../../d");
|
||||
assert_eq!(path.segments(), &["a", "b", "c", "d"]);
|
||||
assert_eq!(path.segments().collect::<Vec<_>>(), &["a", "b", "c", "d"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -366,13 +351,13 @@ mod tests {
|
||||
#[test]
|
||||
fn test_new_strips_traversal_segments() {
|
||||
let path = StoragePath::new(vec!["..".into(), "etc".into(), ".".into(), "passwd".into()]);
|
||||
assert_eq!(path.segments(), &["etc", "passwd"]);
|
||||
assert_eq!(path.segments().collect::<Vec<_>>(), &["etc", "passwd"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_strips_empty_segments() {
|
||||
let path = StoragePath::new(vec!["a".into(), "".into(), "b".into()]);
|
||||
assert_eq!(path.segments(), &["a", "b"]);
|
||||
assert_eq!(path.segments().collect::<Vec<_>>(), &["a", "b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -380,14 +365,14 @@ mod tests {
|
||||
let base = StoragePath::from_string("folder");
|
||||
let joined = base.join("..");
|
||||
// ".." is silently ignored — path stays unchanged
|
||||
assert_eq!(joined.segments(), &["folder"]);
|
||||
assert_eq!(joined.segments().collect::<Vec<_>>(), &["folder"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_join_rejects_single_dot() {
|
||||
let base = StoragePath::from_string("folder");
|
||||
let joined = base.join(".");
|
||||
assert_eq!(joined.segments(), &["folder"]);
|
||||
assert_eq!(joined.segments().collect::<Vec<_>>(), &["folder"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -395,7 +380,7 @@ mod tests {
|
||||
let base = StoragePath::from_string("folder");
|
||||
let joined = base.join("sub/../../etc/passwd");
|
||||
// Segment contains '/' → silently ignored
|
||||
assert_eq!(joined.segments(), &["folder"]);
|
||||
assert_eq!(joined.segments().collect::<Vec<_>>(), &["folder"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -404,8 +389,8 @@ mod tests {
|
||||
// PathBuf Component::Normal only yields the normal parts
|
||||
// On most platforms this strips . and ..
|
||||
// but regardless, our from() only accepts Component::Normal
|
||||
assert!(!path.segments().contains(&"..".to_string()));
|
||||
assert!(!path.segments().contains(&".".to_string()));
|
||||
assert!(!path.segments().any(|s| s == ".."));
|
||||
assert!(!path.segments().any(|s| s == "."));
|
||||
}
|
||||
|
||||
// ── NFC normalization tests ─────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user