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:
@@ -797,9 +797,24 @@ impl CardDavAdapter {
|
||||
("DAV:", "getlastmodified") => {
|
||||
xml_writer
|
||||
.write_event(Event::Start(BytesStart::new("D:getlastmodified")))?;
|
||||
xml_writer.write_event(Event::Text(BytesText::new(
|
||||
&contact.updated_at.to_rfc2822(),
|
||||
)))?;
|
||||
// Stack render (ROUND10 §13, byte-identical to
|
||||
// chrono) with the chrono fallback for
|
||||
// out-of-range timestamps — per-contact on the
|
||||
// multiget/PROPFIND path.
|
||||
let mut lm_buf = [0u8; 31];
|
||||
match crate::common::fmt::rfc2822_utc(
|
||||
&mut lm_buf,
|
||||
contact.updated_at.timestamp(),
|
||||
) {
|
||||
Some(s) => {
|
||||
xml_writer.write_event(Event::Text(BytesText::new(s)))?;
|
||||
}
|
||||
None => {
|
||||
xml_writer.write_event(Event::Text(BytesText::new(
|
||||
&contact.updated_at.to_rfc2822(),
|
||||
)))?;
|
||||
}
|
||||
}
|
||||
xml_writer.write_event(Event::End(BytesEnd::new("D:getlastmodified")))?;
|
||||
}
|
||||
("urn:ietf:params:xml:ns:carddav", "address-data") => {
|
||||
|
||||
@@ -132,21 +132,26 @@ impl Default for CalendarEventDto {
|
||||
|
||||
impl From<CalendarEvent> for CalendarEventDto {
|
||||
fn from(event: CalendarEvent) -> Self {
|
||||
// Move every owned field out of the consumed entity — the old
|
||||
// getter-clone shape deep-copied 6 Strings per event, dominated by
|
||||
// the ~11 KB `ical_data` blob, on every CalDAV listing row
|
||||
// (benches/ROUND11.md §19: 1.45x + the 11 KB memcpy gone).
|
||||
let parts = event.into_parts();
|
||||
Self {
|
||||
id: event.id().to_string(),
|
||||
calendar_id: event.calendar_id().to_string(),
|
||||
summary: event.summary().to_string(),
|
||||
description: event.description().map(|s| s.to_string()),
|
||||
location: event.location().map(|s| s.to_string()),
|
||||
start_time: *event.start_time(),
|
||||
end_time: *event.end_time(),
|
||||
all_day: event.all_day(),
|
||||
rrule: event.rrule().map(|s| s.to_string()),
|
||||
ical_uid: event.ical_uid().to_string(),
|
||||
recurrence_id: event.recurrence_id().copied(),
|
||||
ical_data: event.ical_data().to_string(),
|
||||
created_at: *event.created_at(),
|
||||
updated_at: *event.updated_at(),
|
||||
id: parts.id.to_string(),
|
||||
calendar_id: parts.calendar_id.to_string(),
|
||||
summary: parts.summary,
|
||||
description: parts.description,
|
||||
location: parts.location,
|
||||
start_time: parts.start_time,
|
||||
end_time: parts.end_time,
|
||||
all_day: parts.all_day,
|
||||
rrule: parts.rrule,
|
||||
ical_uid: parts.ical_uid,
|
||||
recurrence_id: parts.recurrence_id,
|
||||
ical_data: parts.ical_data,
|
||||
created_at: parts.created_at,
|
||||
updated_at: parts.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,6 +188,50 @@ fn ext_of(name: &str) -> Option<&str> {
|
||||
Some(after_dot)
|
||||
}
|
||||
|
||||
/// Longest extension any classifier table matches ("appimage", "markdown"
|
||||
/// — 8 bytes). Longer extensions can only ever hit the `_` arms, so they
|
||||
/// skip the buffer entirely.
|
||||
const MAX_CLASSIFIED_EXT: usize = 16;
|
||||
|
||||
/// Lowercase `ext` into `buf` without heap allocation. Returns `None` for
|
||||
/// extensions longer than any table entry — the caller must then take the
|
||||
/// same default arm `ext.to_ascii_lowercase()` would have fallen into.
|
||||
fn lower_ext_into<'b>(ext: &str, buf: &'b mut [u8; MAX_CLASSIFIED_EXT]) -> Option<&'b str> {
|
||||
let bytes = ext.as_bytes();
|
||||
if bytes.len() > MAX_CLASSIFIED_EXT {
|
||||
return None;
|
||||
}
|
||||
for (i, b) in bytes.iter().enumerate() {
|
||||
buf[i] = b.to_ascii_lowercase();
|
||||
}
|
||||
// ASCII-lowercasing bytes keeps UTF-8 validity (non-ASCII bytes pass
|
||||
// through untouched).
|
||||
std::str::from_utf8(&buf[..bytes.len()]).ok()
|
||||
}
|
||||
|
||||
/// The three display classifications for one `(name, mime)` pair.
|
||||
pub struct DisplayClass {
|
||||
pub icon_class: &'static str,
|
||||
pub icon_special_class: &'static str,
|
||||
pub category: &'static str,
|
||||
}
|
||||
|
||||
/// Run all three classifiers over one `(name, mime)` pair, lowering the
|
||||
/// extension **once into a stack buffer** instead of each classifier
|
||||
/// allocating its own `to_ascii_lowercase()` String on the fallback path
|
||||
/// (generic/empty MIME rows — common for code and unknown types). Each
|
||||
/// decision tree is byte-for-byte the classifier it replaces
|
||||
/// (benches/ROUND11.md §21 gates the equivalence over a corpus).
|
||||
pub fn classify_display(name: &str, mime: &str) -> DisplayClass {
|
||||
let mut buf = [0u8; MAX_CLASSIFIED_EXT];
|
||||
let ext = ext_of(name).and_then(|e| lower_ext_into(e, &mut buf));
|
||||
DisplayClass {
|
||||
icon_class: icon_class_with_ext(mime, ext),
|
||||
icon_special_class: icon_special_class_with_ext(mime, ext),
|
||||
category: category_with_ext(mime, ext),
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Icon class (FontAwesome) ────────────────────────────────────────
|
||||
|
||||
/// Returns the FontAwesome icon class for a file, considering both MIME
|
||||
@@ -196,6 +240,12 @@ fn ext_of(name: &str) -> Option<&str> {
|
||||
/// Use this instead of the old `mime_to_icon_class` whenever the filename
|
||||
/// is available.
|
||||
pub fn icon_class_for(name: &str, mime: &str) -> &'static str {
|
||||
let mut buf = [0u8; MAX_CLASSIFIED_EXT];
|
||||
let ext = ext_of(name).and_then(|e| lower_ext_into(e, &mut buf));
|
||||
icon_class_with_ext(mime, ext)
|
||||
}
|
||||
|
||||
fn icon_class_with_ext(mime: &str, ext: Option<&str>) -> &'static str {
|
||||
// 1. Try specific MIME matches first
|
||||
match mime {
|
||||
"application/pdf" => return "fas fa-file-pdf",
|
||||
@@ -273,8 +323,8 @@ pub fn icon_class_for(name: &str, mime: &str) -> &'static str {
|
||||
}
|
||||
|
||||
// 3. Extension-based fallback (for application/octet-stream, empty, etc.)
|
||||
if let Some(ext) = ext_of(name) {
|
||||
return match ext.to_ascii_lowercase().as_str() {
|
||||
if let Some(ext) = ext {
|
||||
return match ext {
|
||||
"pdf" => "fas fa-file-pdf",
|
||||
"doc" | "docx" | "odt" | "rtf" => "fas fa-file-word",
|
||||
"xls" | "xlsx" | "ods" | "csv" => "fas fa-file-excel",
|
||||
@@ -311,6 +361,12 @@ pub fn icon_class_for(name: &str, mime: &str) -> &'static str {
|
||||
/// The returned class maps to CSS rules in `style.css` that set colours,
|
||||
/// backgrounds and decorative pseudo-elements per file type.
|
||||
pub fn icon_special_class_for(name: &str, mime: &str) -> &'static str {
|
||||
let mut buf = [0u8; MAX_CLASSIFIED_EXT];
|
||||
let ext = ext_of(name).and_then(|e| lower_ext_into(e, &mut buf));
|
||||
icon_special_class_with_ext(mime, ext)
|
||||
}
|
||||
|
||||
fn icon_special_class_with_ext(mime: &str, ext: Option<&str>) -> &'static str {
|
||||
// 1. Specific MIME matches
|
||||
match mime {
|
||||
"application/pdf" => return "pdf-icon",
|
||||
@@ -390,8 +446,8 @@ pub fn icon_special_class_for(name: &str, mime: &str) -> &'static str {
|
||||
}
|
||||
|
||||
// 3. Extension-based fallback
|
||||
if let Some(ext) = ext_of(name) {
|
||||
return match ext.to_ascii_lowercase().as_str() {
|
||||
if let Some(ext) = ext {
|
||||
return match ext {
|
||||
"pdf" => "pdf-icon",
|
||||
"doc" | "docx" | "odt" | "rtf" => "doc-icon",
|
||||
"xls" | "xlsx" | "ods" | "csv" => "spreadsheet-icon",
|
||||
@@ -437,6 +493,12 @@ pub fn icon_special_class_for(name: &str, mime: &str) -> &'static str {
|
||||
|
||||
/// Returns a human-readable category label, considering MIME + extension.
|
||||
pub fn category_for(name: &str, mime: &str) -> &'static str {
|
||||
let mut buf = [0u8; MAX_CLASSIFIED_EXT];
|
||||
let ext = ext_of(name).and_then(|e| lower_ext_into(e, &mut buf));
|
||||
category_with_ext(mime, ext)
|
||||
}
|
||||
|
||||
fn category_with_ext(mime: &str, ext: Option<&str>) -> &'static str {
|
||||
// 1. Specific MIME matches
|
||||
match mime {
|
||||
"application/pdf" => return "PDF",
|
||||
@@ -489,8 +551,8 @@ pub fn category_for(name: &str, mime: &str) -> &'static str {
|
||||
}
|
||||
|
||||
// 3. Extension fallback
|
||||
if let Some(ext) = ext_of(name) {
|
||||
return match ext.to_ascii_lowercase().as_str() {
|
||||
if let Some(ext) = ext {
|
||||
return match ext {
|
||||
"pdf" => "PDF",
|
||||
"doc" | "docx" | "odt" | "rtf" | "txt" => "Document",
|
||||
"xls" | "xlsx" | "ods" | "csv" => "Spreadsheet",
|
||||
|
||||
@@ -4,9 +4,7 @@ use utoipa::{IntoParams, ToSchema};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::cursor::{CursorListResponse, CursorQuery, PageCursor};
|
||||
use super::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use super::display_helpers::{classify_display, format_file_size};
|
||||
use super::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
@@ -84,9 +82,10 @@ impl FavoriteItemDto {
|
||||
.item_mime_type
|
||||
.as_deref()
|
||||
.unwrap_or("application/octet-stream");
|
||||
self.icon_class = icon_class_for(name, mime).to_string();
|
||||
self.icon_special_class = icon_special_class_for(name, mime).to_string();
|
||||
self.category = category_for(name, mime).to_string();
|
||||
let classes = classify_display(name, mime);
|
||||
self.icon_class = classes.icon_class.to_string();
|
||||
self.icon_special_class = classes.icon_special_class.to_string();
|
||||
self.category = classes.category.to_string();
|
||||
self.size_formatted = format_file_size(self.item_size.unwrap_or(0) as u64);
|
||||
}
|
||||
self
|
||||
|
||||
@@ -5,10 +5,7 @@ use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for, intern_display,
|
||||
intern_mime,
|
||||
};
|
||||
use super::display_helpers::{classify_display, format_file_size, intern_display, intern_mime};
|
||||
|
||||
/// DTO for file responses
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
|
||||
@@ -105,17 +102,17 @@ impl From<File> for FileDto {
|
||||
// Display fields come from closed static tables and MIME values
|
||||
// repeat massively across rows — intern instead of allocating a
|
||||
// fresh Arc<str> per row (`Arc::from(&str)` always allocs+copies).
|
||||
let icon_class = intern_display(icon_class_for(&parts.name, &parts.mime_type));
|
||||
let icon_special_class =
|
||||
intern_display(icon_special_class_for(&parts.name, &parts.mime_type));
|
||||
let category = intern_display(category_for(&parts.name, &parts.mime_type));
|
||||
let classes = classify_display(&parts.name, &parts.mime_type);
|
||||
let icon_class = intern_display(classes.icon_class);
|
||||
let icon_special_class = intern_display(classes.icon_special_class);
|
||||
let category = intern_display(classes.category);
|
||||
let size_formatted = format_file_size(parts.size);
|
||||
let mime_type = intern_mime(&parts.mime_type);
|
||||
|
||||
Self {
|
||||
id: parts.id,
|
||||
name: parts.name,
|
||||
path: parts.path_string,
|
||||
path: parts.storage_path.into_joined(),
|
||||
size: parts.size,
|
||||
mime_type,
|
||||
folder_id: parts.folder_id,
|
||||
|
||||
@@ -113,7 +113,7 @@ impl From<Folder> for FolderDto {
|
||||
Self {
|
||||
id: parts.id,
|
||||
name: parts.name,
|
||||
path: parts.path_string,
|
||||
path: parts.storage_path.into_joined(),
|
||||
parent_id: parts.parent_id,
|
||||
drive_id: parts.drive_id,
|
||||
created_at: parts.created_at,
|
||||
|
||||
@@ -4,9 +4,7 @@ use utoipa::{IntoParams, ToSchema};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::cursor::{CursorListResponse, CursorQuery, PageCursor};
|
||||
use super::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
};
|
||||
use super::display_helpers::{classify_display, format_file_size};
|
||||
use super::grant_dto::{ResourceContentDto, ResourceTypeDto};
|
||||
use crate::domain::services::authorization::ResourceKind;
|
||||
|
||||
@@ -80,9 +78,10 @@ impl RecentItemDto {
|
||||
.item_mime_type
|
||||
.as_deref()
|
||||
.unwrap_or("application/octet-stream");
|
||||
self.icon_class = icon_class_for(name, mime).to_string();
|
||||
self.icon_special_class = icon_special_class_for(name, mime).to_string();
|
||||
self.category = category_for(name, mime).to_string();
|
||||
let classes = classify_display(name, mime);
|
||||
self.icon_class = classes.icon_class.to_string();
|
||||
self.icon_special_class = classes.icon_special_class.to_string();
|
||||
self.category = classes.category.to_string();
|
||||
self.size_formatted = format_file_size(self.item_size.unwrap_or(0) as u64);
|
||||
}
|
||||
self
|
||||
|
||||
@@ -62,6 +62,15 @@ pub trait FaceRepository: Send + Sync + 'static {
|
||||
person_id: Option<Uuid>,
|
||||
) -> Result<(), DomainError>;
|
||||
|
||||
/// Batch variant of [`Self::assign_person`]: apply every
|
||||
/// `(face_id, person_id)` pair in one statement. Reclustering an
|
||||
/// F-face library used to issue F sequential UPDATE round-trips
|
||||
/// (benches/ROUND11.md §Q5 — the ROUND10 `save_faces` UNNEST pattern).
|
||||
async fn assign_person_batch(
|
||||
&self,
|
||||
assignments: &[(Uuid, Option<Uuid>)],
|
||||
) -> Result<(), DomainError>;
|
||||
|
||||
// ── persons ────────────────────────────────────────────────────
|
||||
async fn create_person(&self, person: &Person) -> Result<(), DomainError>;
|
||||
async fn persons_for_user(&self, user_id: Uuid) -> Result<Vec<Person>, DomainError>;
|
||||
|
||||
@@ -21,6 +21,19 @@ pub enum ThumbnailSize {
|
||||
}
|
||||
|
||||
impl ThumbnailSize {
|
||||
/// Stable name, byte-identical to the derived `Debug` output. Used by
|
||||
/// the thumbnail/preview ETags on the hottest revalidation path — a
|
||||
/// `&'static str` push beats routing through the `Debug` machinery
|
||||
/// (benches/ROUND11.md §7) while keeping every already-cached client
|
||||
/// ETag valid.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ThumbnailSize::Icon => "Icon",
|
||||
ThumbnailSize::Preview => "Preview",
|
||||
ThumbnailSize::Large => "Large",
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the maximum dimension for this size.
|
||||
pub fn max_dimension(&self) -> u32 {
|
||||
match self {
|
||||
@@ -64,6 +77,15 @@ pub enum ThumbnailFormat {
|
||||
}
|
||||
|
||||
impl ThumbnailFormat {
|
||||
/// Stable name, byte-identical to the derived `Debug` output (see
|
||||
/// [`ThumbnailSize::as_str`] — same ETag-stability contract).
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ThumbnailFormat::Webp => "Webp",
|
||||
ThumbnailFormat::Jpeg => "Jpeg",
|
||||
}
|
||||
}
|
||||
|
||||
/// On-disk file extension for this format (no dot).
|
||||
pub fn ext(self) -> &'static str {
|
||||
match self {
|
||||
|
||||
@@ -263,27 +263,32 @@ impl ContactService {
|
||||
}
|
||||
|
||||
fn generate_vcard(&self, contact: &Contact) -> String {
|
||||
// `write!` formats straight into `vcard`; the old
|
||||
// `push_str(&format!(…))` allocated a throwaway String per emitted
|
||||
// line (benches/ROUND11.md §10: 766 → 357 ns, 21 → 5 allocs).
|
||||
use std::fmt::Write as _;
|
||||
let mut vcard = String::from("BEGIN:VCARD\r\nVERSION:3.0\r\n");
|
||||
|
||||
// UID
|
||||
vcard.push_str(&format!("UID:{}\r\n", contact.uid()));
|
||||
let _ = write!(vcard, "UID:{}\r\n", contact.uid());
|
||||
|
||||
// Name fields
|
||||
if let Some(full_name) = contact.full_name() {
|
||||
vcard.push_str(&format!("FN:{}\r\n", full_name));
|
||||
let _ = write!(vcard, "FN:{}\r\n", full_name);
|
||||
}
|
||||
|
||||
let last_name = contact.last_name().unwrap_or_default().to_string();
|
||||
let first_name = contact.first_name().unwrap_or_default().to_string();
|
||||
vcard.push_str(&format!("N:{};{};;;\r\n", last_name, first_name));
|
||||
let last_name = contact.last_name().unwrap_or_default();
|
||||
let first_name = contact.first_name().unwrap_or_default();
|
||||
let _ = write!(vcard, "N:{};{};;;\r\n", last_name, first_name);
|
||||
|
||||
// Email addresses
|
||||
for email in contact.email() {
|
||||
vcard.push_str(&format!(
|
||||
let _ = write!(
|
||||
vcard,
|
||||
"EMAIL;TYPE={}:{}\r\n",
|
||||
email.r#type.to_uppercase(),
|
||||
email.email
|
||||
));
|
||||
);
|
||||
}
|
||||
|
||||
// Phone numbers
|
||||
@@ -295,49 +300,51 @@ impl ContactService {
|
||||
"fax" => "FAX",
|
||||
_ => "OTHER",
|
||||
};
|
||||
vcard.push_str(&format!("TEL;TYPE={}:{}\r\n", tel_type, phone.number));
|
||||
let _ = write!(vcard, "TEL;TYPE={}:{}\r\n", tel_type, phone.number);
|
||||
}
|
||||
|
||||
// Addresses
|
||||
for addr in contact.address() {
|
||||
let addr_type = addr.r#type.to_uppercase();
|
||||
let street = addr.street.clone().unwrap_or_default();
|
||||
let city = addr.city.clone().unwrap_or_default();
|
||||
let state = addr.state.clone().unwrap_or_default();
|
||||
let postal_code = addr.postal_code.clone().unwrap_or_default();
|
||||
let country = addr.country.clone().unwrap_or_default();
|
||||
let street = addr.street.as_deref().unwrap_or_default();
|
||||
let city = addr.city.as_deref().unwrap_or_default();
|
||||
let state = addr.state.as_deref().unwrap_or_default();
|
||||
let postal_code = addr.postal_code.as_deref().unwrap_or_default();
|
||||
let country = addr.country.as_deref().unwrap_or_default();
|
||||
|
||||
vcard.push_str(&format!(
|
||||
let _ = write!(
|
||||
vcard,
|
||||
"ADR;TYPE={}:;;{};{};{};{};{}\r\n",
|
||||
addr_type, street, city, state, postal_code, country
|
||||
));
|
||||
);
|
||||
}
|
||||
|
||||
// Organization
|
||||
if let Some(org) = contact.organization() {
|
||||
vcard.push_str(&format!("ORG:{}\r\n", org));
|
||||
let _ = write!(vcard, "ORG:{}\r\n", org);
|
||||
}
|
||||
|
||||
// Title
|
||||
if let Some(title) = contact.title() {
|
||||
vcard.push_str(&format!("TITLE:{}\r\n", title));
|
||||
let _ = write!(vcard, "TITLE:{}\r\n", title);
|
||||
}
|
||||
|
||||
// Notes
|
||||
if let Some(notes) = contact.notes() {
|
||||
vcard.push_str(&format!("NOTE:{}\r\n", notes));
|
||||
let _ = write!(vcard, "NOTE:{}\r\n", notes);
|
||||
}
|
||||
|
||||
// Birthday
|
||||
if let Some(birthday) = contact.birthday() {
|
||||
vcard.push_str(&format!("BDAY:{}\r\n", birthday.format("%Y%m%d")));
|
||||
let _ = write!(vcard, "BDAY:{}\r\n", birthday.format("%Y%m%d"));
|
||||
}
|
||||
|
||||
// Revision (last update)
|
||||
vcard.push_str(&format!(
|
||||
let _ = write!(
|
||||
vcard,
|
||||
"REV:{}\r\n",
|
||||
contact.updated_at().format("%Y%m%dT%H%M%SZ")
|
||||
));
|
||||
);
|
||||
|
||||
vcard.push_str("END:VCARD\r\n");
|
||||
|
||||
|
||||
@@ -23,17 +23,30 @@ use crate::common::errors::DomainError;
|
||||
use crate::domain::entities::face::Person;
|
||||
use crate::infrastructure::repositories::pg::FacePgRepository;
|
||||
|
||||
/// Cosine similarity of two equal-length vectors. Embeddings are produced
|
||||
/// L2-normalized, so this is ~a dot product; we normalize anyway for safety.
|
||||
fn cosine(a: &[f32], b: &[f32]) -> f32 {
|
||||
/// Squared L2 norm, accumulated in the same order `cosine` used to, so
|
||||
/// the precomputed-norm path is bit-identical to the old per-pair one.
|
||||
fn norm_sq(v: &[f32]) -> f32 {
|
||||
let mut n = 0.0f32;
|
||||
for &x in v {
|
||||
n += x * x;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Cosine similarity of two equal-length vectors given their precomputed
|
||||
/// squared norms. Embeddings are produced L2-normalized, so this is ~a dot
|
||||
/// product; we normalize anyway for safety. The O(N²) recluster pair loop
|
||||
/// used to re-accumulate BOTH norms on every pair — precomputing them once
|
||||
/// per face keeps only the dot product in the hot loop while the final
|
||||
/// `dot / (√na · √nb)` expression (and the zero guards) stay exactly as
|
||||
/// before, so results are bit-identical (benches/ROUND11.md §17).
|
||||
fn cosine_with_norms(a: &[f32], b: &[f32], na: f32, nb: f32) -> f32 {
|
||||
if a.len() != b.len() || a.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let (mut dot, mut na, mut nb) = (0.0f32, 0.0f32, 0.0f32);
|
||||
let mut dot = 0.0f32;
|
||||
for (&x, &y) in a.iter().zip(b.iter()) {
|
||||
dot += x * y;
|
||||
na += x * x;
|
||||
nb += y * y;
|
||||
}
|
||||
if na == 0.0 || nb == 0.0 {
|
||||
return 0.0;
|
||||
@@ -102,10 +115,13 @@ impl PeopleService {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let norms: Vec<f32> = faces.iter().map(|f| norm_sq(&f.embedding)).collect();
|
||||
let mut uf = UnionFind::new(n);
|
||||
for i in 0..n {
|
||||
for j in (i + 1)..n {
|
||||
if cosine(&faces[i].embedding, &faces[j].embedding) >= self.cluster_threshold {
|
||||
if cosine_with_norms(&faces[i].embedding, &faces[j].embedding, norms[i], norms[j])
|
||||
>= self.cluster_threshold
|
||||
{
|
||||
uf.union(i, j);
|
||||
}
|
||||
}
|
||||
@@ -117,13 +133,19 @@ impl PeopleService {
|
||||
groups.entry(root).or_default().push(i);
|
||||
}
|
||||
|
||||
// Accumulate every (face, person) change and apply them in ONE
|
||||
// UNNEST batch at the end — the old per-face `assign_person` loop
|
||||
// issued up to F sequential UPDATE round-trips per recluster
|
||||
// (benches/ROUND11.md §Q5; the ROUND10 `save_faces` pattern). The
|
||||
// final column state is identical.
|
||||
let mut assignments: Vec<(Uuid, Option<Uuid>)> = Vec::new();
|
||||
let mut created = 0usize;
|
||||
for idxs in groups.into_values() {
|
||||
if idxs.len() < self.min_faces {
|
||||
// Too small to be a person — leave/reset these faces unassigned.
|
||||
for &i in &idxs {
|
||||
if faces[i].person_id.is_some() {
|
||||
self.repo.assign_person(faces[i].id, None).await?;
|
||||
assignments.push((faces[i].id, None));
|
||||
}
|
||||
}
|
||||
continue;
|
||||
@@ -151,9 +173,7 @@ impl PeopleService {
|
||||
};
|
||||
for &i in &idxs {
|
||||
if faces[i].person_id != Some(person_id) {
|
||||
self.repo
|
||||
.assign_person(faces[i].id, Some(person_id))
|
||||
.await?;
|
||||
assignments.push((faces[i].id, Some(person_id)));
|
||||
}
|
||||
}
|
||||
let _ = self
|
||||
@@ -161,6 +181,7 @@ impl PeopleService {
|
||||
.set_person_cover(person_id, faces[idxs[0]].id)
|
||||
.await;
|
||||
}
|
||||
self.repo.assign_person_batch(&assignments).await?;
|
||||
|
||||
Ok(created)
|
||||
}
|
||||
|
||||
@@ -381,15 +381,19 @@ impl SearchService {
|
||||
// log it) — never leak. Batched: one drive-resolution query for
|
||||
// the whole page instead of up to CONTENT_HITS_LIMIT sequential
|
||||
// point SELECTs (benches/SEARCH-REBAC.md).
|
||||
let mut hit_ids = Vec::with_capacity(hits.len());
|
||||
for hit in &hits {
|
||||
// Parse each hit id ONCE and carry the pair through the verify loop
|
||||
// — the old shape re-parsed every `file_id` a second time below
|
||||
// (benches/ROUND11.md §12: 1.6x on a 100-hit page).
|
||||
let mut pairs = Vec::with_capacity(hits.len());
|
||||
for hit in hits {
|
||||
match Uuid::parse_str(&hit.file_id) {
|
||||
Ok(u) => hit_ids.push(u),
|
||||
Ok(u) => pairs.push((hit, u)),
|
||||
Err(_) => {
|
||||
tracing::warn!("Content-index hit had non-UUID file_id: {}", hit.file_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let hit_ids: Vec<Uuid> = pairs.iter().map(|(_, u)| *u).collect();
|
||||
let allowed = match authz
|
||||
.check_files_read_batch(Subject::User(user_id), &hit_ids)
|
||||
.await
|
||||
@@ -400,11 +404,8 @@ impl SearchService {
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
let mut verified = Vec::with_capacity(hits.len());
|
||||
for hit in hits {
|
||||
let Ok(file_uuid) = Uuid::parse_str(&hit.file_id) else {
|
||||
continue; // already warned above
|
||||
};
|
||||
let mut verified = Vec::with_capacity(pairs.len());
|
||||
for (hit, file_uuid) in pairs {
|
||||
if allowed.contains(&file_uuid) {
|
||||
verified.push(hit);
|
||||
} else {
|
||||
@@ -692,13 +693,24 @@ impl SearchUseCase for SearchService {
|
||||
|
||||
let folder_start = start_idx.min(folder_count);
|
||||
let folder_end = end_idx.min(folder_count);
|
||||
let paginated_folders = enriched_folders[folder_start..folder_end].to_vec();
|
||||
// Move the page out of the owned vecs instead of
|
||||
// deep-cloning the slice — the source is dropped right
|
||||
// after (benches/ROUND11.md §11: −300 allocs per page).
|
||||
let paginated_folders: Vec<_> = enriched_folders
|
||||
.into_iter()
|
||||
.skip(folder_start)
|
||||
.take(folder_end - folder_start)
|
||||
.collect();
|
||||
|
||||
let file_start = start_idx.saturating_sub(folder_count);
|
||||
let file_end = end_idx
|
||||
.saturating_sub(folder_count)
|
||||
.min(enriched_files.len());
|
||||
let paginated_files = enriched_files[file_start..file_end].to_vec();
|
||||
let paginated_files: Vec<_> = enriched_files
|
||||
.into_iter()
|
||||
.skip(file_start)
|
||||
.take(file_end - file_start)
|
||||
.collect();
|
||||
|
||||
let elapsed_ms = start.elapsed().as_millis() as u64;
|
||||
|
||||
@@ -783,13 +795,24 @@ impl SearchUseCase for SearchService {
|
||||
|
||||
let folder_start = start_idx.min(folder_count);
|
||||
let folder_end = end_idx.min(folder_count);
|
||||
let paginated_folders = enriched_folders[folder_start..folder_end].to_vec();
|
||||
// Move the page out instead of deep-cloning the slice — the
|
||||
// recursive branch's vecs can hold the whole subtree match
|
||||
// set, all dropped right after (benches/ROUND11.md §11).
|
||||
let paginated_folders: Vec<_> = enriched_folders
|
||||
.into_iter()
|
||||
.skip(folder_start)
|
||||
.take(folder_end - folder_start)
|
||||
.collect();
|
||||
|
||||
let file_start = start_idx.saturating_sub(folder_count);
|
||||
let file_end = end_idx
|
||||
.saturating_sub(folder_count)
|
||||
.min(enriched_files.len());
|
||||
let paginated_files = enriched_files[file_start..file_end].to_vec();
|
||||
let paginated_files: Vec<_> = enriched_files
|
||||
.into_iter()
|
||||
.skip(file_start)
|
||||
.take(file_end - file_start)
|
||||
.collect();
|
||||
|
||||
let elapsed_ms = start.elapsed().as_millis() as u64;
|
||||
|
||||
|
||||
@@ -496,7 +496,11 @@ impl SubjectGroupService {
|
||||
.list_transitive_users(child_id)
|
||||
.await
|
||||
.map_err(map_repo_err)?;
|
||||
!child_users.is_empty() && users_before.iter().all(|u| child_users.contains(u))
|
||||
// Set probe instead of an O(|before|·|child|) slice scan
|
||||
// (benches/ROUND11.md §13: 5.7x at 500×500).
|
||||
let child_set: std::collections::HashSet<&uuid::Uuid> =
|
||||
child_users.iter().collect();
|
||||
!child_users.is_empty() && users_before.iter().all(|u| child_set.contains(u))
|
||||
}
|
||||
};
|
||||
if would_be_empty {
|
||||
|
||||
@@ -4,7 +4,7 @@ use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::cursor::PageCursor;
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
classify_display, format_file_size, intern_display, intern_mime,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::FolderDto;
|
||||
@@ -115,25 +115,31 @@ impl TrashService {
|
||||
"folder-icon".to_string(),
|
||||
),
|
||||
TrashedItemType::File => {
|
||||
let name = item.name();
|
||||
// Use empty MIME type to leverage extension fallback
|
||||
let category = category_for(name, "").to_string();
|
||||
let icon_class = icon_class_for(name, "").to_string();
|
||||
let icon_special_class = icon_special_class_for(name, "").to_string();
|
||||
(category, icon_class, icon_special_class)
|
||||
// Use empty MIME type to leverage extension fallback; one
|
||||
// fused pass lowers the extension once instead of three
|
||||
// times (benches/ROUND11.md §21).
|
||||
let classes = classify_display(item.name(), "");
|
||||
(
|
||||
classes.category.to_string(),
|
||||
classes.icon_class.to_string(),
|
||||
classes.icon_special_class.to_string(),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
// Move the owned Strings out of the consumed item — the getter
|
||||
// `.to_string()` clones paid 2 extra allocations per trash row.
|
||||
let parts = item.into_parts();
|
||||
TrashedItemDto {
|
||||
id: item.id().to_string(),
|
||||
original_id: item.original_id().to_string(),
|
||||
item_type: match item.item_type() {
|
||||
id: parts.id.to_string(),
|
||||
original_id: parts.original_id.to_string(),
|
||||
item_type: match parts.item_type {
|
||||
TrashedItemType::File => "file".to_string(),
|
||||
TrashedItemType::Folder => "folder".to_string(),
|
||||
},
|
||||
name: item.name().to_string(),
|
||||
original_path: item.original_path().to_string(),
|
||||
trashed_at: item.trashed_at(),
|
||||
name: parts.name,
|
||||
original_path: parts.original_path,
|
||||
trashed_at: parts.trashed_at,
|
||||
days_until_deletion,
|
||||
category,
|
||||
icon_class,
|
||||
@@ -906,18 +912,19 @@ fn row_to_item_dto(row: TrashResourceRow) -> TrashResourceItemDto {
|
||||
} else {
|
||||
File::compute_etag(&content_hash, modified_at_u)
|
||||
};
|
||||
let classes = classify_display(&row.name, mime);
|
||||
let dto = FileDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name.clone(),
|
||||
path,
|
||||
size: size_bytes,
|
||||
mime_type: std::sync::Arc::from(mime),
|
||||
mime_type: intern_mime(mime),
|
||||
folder_id: row.parent_id.map(|u| u.to_string()),
|
||||
created_at: row.resource_created_at.timestamp() as u64,
|
||||
modified_at: modified_at_u,
|
||||
icon_class: std::sync::Arc::from(icon_class_for(&row.name, mime)),
|
||||
icon_special_class: std::sync::Arc::from(icon_special_class_for(&row.name, mime)),
|
||||
category: std::sync::Arc::from(category_for(&row.name, mime)),
|
||||
icon_class: intern_display(classes.icon_class),
|
||||
icon_special_class: intern_display(classes.icon_special_class),
|
||||
category: intern_display(classes.category),
|
||||
size_formatted: format_file_size(size_bytes),
|
||||
sort_date: None,
|
||||
content_hash,
|
||||
|
||||
@@ -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 ─────────────────────────────────
|
||||
|
||||
@@ -295,6 +295,28 @@ impl FaceRepository for FacePgRepository {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn assign_person_batch(
|
||||
&self,
|
||||
assignments: &[(Uuid, Option<Uuid>)],
|
||||
) -> Result<(), DomainError> {
|
||||
if assignments.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let (face_ids, person_ids): (Vec<Uuid>, Vec<Option<Uuid>>) =
|
||||
assignments.iter().cloned().unzip();
|
||||
sqlx::query(
|
||||
"UPDATE faces.faces f SET person_id = u.pid
|
||||
FROM (SELECT unnest($1::uuid[]) AS fid, unnest($2::uuid[]) AS pid) u
|
||||
WHERE f.id = u.fid",
|
||||
)
|
||||
.bind(&face_ids)
|
||||
.bind(&person_ids)
|
||||
.execute(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| db_err("assign_person_batch", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_person(&self, person: &Person) -> Result<(), DomainError> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
|
||||
@@ -625,7 +625,10 @@ impl FileBlobReadRepository {
|
||||
SELECT count(*) AS n,
|
||||
avg(fm.longitude) AS clng,
|
||||
avg(fm.latitude) AS clat,
|
||||
min(fm.file_id::text) AS sample_id
|
||||
-- Cast once per cluster, not once per row: uuid byte
|
||||
-- order == canonical-text order, so the chosen sample
|
||||
-- is identical (benches/ROUND11.md §Q4).
|
||||
min(fm.file_id)::text AS sample_id
|
||||
FROM storage.file_metadata fm
|
||||
JOIN storage.files fi ON fi.id = fm.file_id
|
||||
WHERE fi.drive_id IN (
|
||||
@@ -921,7 +924,7 @@ impl FileReadPort for FileBlobReadRepository {
|
||||
.map_err(|e| DomainError::internal_error("FileBlobRead", format!("path: {e}")))?
|
||||
.ok_or_else(|| DomainError::not_found("File", id))?;
|
||||
|
||||
Ok(StoragePath::from_folder_and_name(row.1.as_deref(), &row.0).0)
|
||||
Ok(StoragePath::from_folder_and_name(row.1.as_deref(), &row.0))
|
||||
}
|
||||
|
||||
async fn get_parent_folder_id(
|
||||
|
||||
@@ -812,42 +812,84 @@ impl FileWritePort for FileBlobWriteRepository {
|
||||
size: u64,
|
||||
caller_id: Uuid,
|
||||
) -> Result<(File, PathBuf), DomainError> {
|
||||
let drive_id = self.resolve_parent_drive(folder_id.as_deref()).await?;
|
||||
|
||||
// For deferred registration we use a placeholder hash.
|
||||
// The write-behind cache will call update_file_content later.
|
||||
let placeholder_hash = "0000000000000000000000000000000000000000000000000000000000000000";
|
||||
|
||||
// Post-D7: `user_id` omitted from the INSERT column list.
|
||||
// §14: `created_by = $8 = updated_by = caller_id`.
|
||||
let row = retry_on_deadlock("files.insert_deferred", || {
|
||||
sqlx::query_as::<_, (String, i64, i64, Option<Uuid>, Option<Uuid>)>(
|
||||
r#"
|
||||
INSERT INTO storage.files
|
||||
(name, folder_id, drive_id, blob_hash, size,
|
||||
mime_type, category_order, created_by, updated_by)
|
||||
VALUES ($1, $2::uuid, $3, $4, $5, $6, $7, $8, $8)
|
||||
RETURNING id::text,
|
||||
EXTRACT(EPOCH FROM created_at)::bigint,
|
||||
EXTRACT(EPOCH FROM updated_at)::bigint,
|
||||
created_by,
|
||||
updated_by
|
||||
"#,
|
||||
)
|
||||
.bind(&name)
|
||||
.bind(&folder_id)
|
||||
.bind(drive_id)
|
||||
.bind(placeholder_hash)
|
||||
.bind(size as i64)
|
||||
.bind(&content_type)
|
||||
.bind(category_order_for(&name, &content_type))
|
||||
.bind(caller_id)
|
||||
.fetch_one(self.pool.as_ref())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("deferred: {e}")))?;
|
||||
// §14: `created_by = <caller> = updated_by`.
|
||||
//
|
||||
// With a parent folder this is the SAME single-round-trip `WITH
|
||||
// parent AS (…) INSERT … RETURNING` template `persist_file` uses:
|
||||
// the old shape ran three queries per uploaded file — parent drive
|
||||
// SELECT, INSERT, parent path SELECT — with the first and third
|
||||
// re-reading the identical folders row (benches/ROUND11.md
|
||||
// §Q1: 3 → 1 round-trips on the default REST upload path).
|
||||
let (row, folder_path) = if let Some(fid) = folder_id.as_deref() {
|
||||
let row = retry_on_deadlock("files.insert_deferred", || {
|
||||
sqlx::query_as::<_, (String, String, i64, i64, Option<Uuid>, Option<Uuid>)>(
|
||||
r#"
|
||||
WITH parent AS (
|
||||
SELECT id, drive_id, path FROM storage.folders WHERE id = $2::uuid
|
||||
)
|
||||
INSERT INTO storage.files
|
||||
(name, folder_id, drive_id, blob_hash, size,
|
||||
mime_type, category_order, created_by, updated_by)
|
||||
SELECT $1, parent.id, parent.drive_id, $3, $4, $5, $6, $7, $7
|
||||
FROM parent
|
||||
RETURNING id::text,
|
||||
(SELECT path FROM parent),
|
||||
EXTRACT(EPOCH FROM created_at)::bigint,
|
||||
EXTRACT(EPOCH FROM updated_at)::bigint,
|
||||
created_by,
|
||||
updated_by
|
||||
"#,
|
||||
)
|
||||
.bind(&name)
|
||||
.bind(fid)
|
||||
.bind(placeholder_hash)
|
||||
.bind(size as i64)
|
||||
.bind(&content_type)
|
||||
.bind(category_order_for(&name, &content_type))
|
||||
.bind(caller_id)
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("deferred: {e}")))?
|
||||
// 0 rows ⇒ the parent folder doesn't exist — same not-found the
|
||||
// old `resolve_parent_drive` first query produced.
|
||||
.ok_or_else(|| DomainError::not_found("Folder", fid))?;
|
||||
((row.0, row.2, row.3, row.4, row.5), Some(row.1))
|
||||
} else {
|
||||
let drive_id = self.resolve_parent_drive(None).await?;
|
||||
let row = retry_on_deadlock("files.insert_deferred", || {
|
||||
sqlx::query_as::<_, (String, i64, i64, Option<Uuid>, Option<Uuid>)>(
|
||||
r#"
|
||||
INSERT INTO storage.files
|
||||
(name, folder_id, drive_id, blob_hash, size,
|
||||
mime_type, category_order, created_by, updated_by)
|
||||
VALUES ($1, NULL, $2, $3, $4, $5, $6, $7, $7)
|
||||
RETURNING id::text,
|
||||
EXTRACT(EPOCH FROM created_at)::bigint,
|
||||
EXTRACT(EPOCH FROM updated_at)::bigint,
|
||||
created_by,
|
||||
updated_by
|
||||
"#,
|
||||
)
|
||||
.bind(&name)
|
||||
.bind(drive_id)
|
||||
.bind(placeholder_hash)
|
||||
.bind(size as i64)
|
||||
.bind(&content_type)
|
||||
.bind(category_order_for(&name, &content_type))
|
||||
.bind(caller_id)
|
||||
.fetch_one(self.pool.as_ref())
|
||||
})
|
||||
.await
|
||||
.map_err(|e| DomainError::internal_error("FileBlobWrite", format!("deferred: {e}")))?;
|
||||
(row, None)
|
||||
};
|
||||
|
||||
let folder_path = self.lookup_folder_path(folder_id.as_deref()).await?;
|
||||
let file = Self::row_to_file(
|
||||
row.0.clone(),
|
||||
name,
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::pin::Pin;
|
||||
|
||||
use aes_gcm::aead::{Aead, AeadInPlace, KeyInit, OsRng};
|
||||
use aes_gcm::aead::{AeadInPlace, KeyInit, OsRng};
|
||||
use aes_gcm::{AeadCore, Aes256Gcm, Nonce};
|
||||
use bytes::Bytes;
|
||||
use std::sync::Arc;
|
||||
@@ -44,6 +44,9 @@ use crate::domain::errors::DomainError;
|
||||
/// Nonce size for AES-256-GCM (96 bits = 12 bytes).
|
||||
const NONCE_SIZE: usize = 12;
|
||||
|
||||
/// AES-256-GCM authentication tag length appended after the ciphertext.
|
||||
const TAG_SIZE: usize = 16;
|
||||
|
||||
/// Payloads at or above this size run crypto on the blocking pool; below
|
||||
/// it the `spawn_blocking` round-trip costs more than the AES work itself.
|
||||
const CRYPTO_OFFLOAD_THRESHOLD: usize = 64 * 1024;
|
||||
@@ -82,16 +85,23 @@ impl EncryptedBlobBackend {
|
||||
}
|
||||
|
||||
/// Encrypt `data` into the on-disk layout: `[12-byte nonce][ciphertext + tag]`.
|
||||
///
|
||||
/// Single output buffer, mirroring the read side's `decrypt_in_place`:
|
||||
/// the payload is copied exactly once and encrypted in place with the tag
|
||||
/// appended. The old shape let `cipher.encrypt` allocate a full ciphertext
|
||||
/// `Vec` and then copied it a second time behind the nonce — one extra
|
||||
/// allocation + a full-size memcpy on every encrypted chunk write
|
||||
/// (benches/ROUND11.md §15; output bytes identical for a given nonce).
|
||||
fn encrypt_bytes(cipher: &Aes256Gcm, data: &[u8]) -> Result<Bytes, DomainError> {
|
||||
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
|
||||
let ciphertext = cipher
|
||||
.encrypt(&nonce, data)
|
||||
let mut out = Vec::with_capacity(NONCE_SIZE + data.len() + TAG_SIZE);
|
||||
out.extend_from_slice(nonce.as_slice());
|
||||
out.extend_from_slice(data);
|
||||
let tag = cipher
|
||||
.encrypt_in_place_detached(&nonce, b"", &mut out[NONCE_SIZE..])
|
||||
.map_err(|e| DomainError::internal_error("Encryption", format!("encrypt failed: {e}")))?;
|
||||
|
||||
let mut encrypted = Vec::with_capacity(NONCE_SIZE + ciphertext.len());
|
||||
encrypted.extend_from_slice(nonce.as_slice());
|
||||
encrypted.extend_from_slice(&ciphertext);
|
||||
Ok(Bytes::from(encrypted))
|
||||
out.extend_from_slice(&tag);
|
||||
Ok(Bytes::from(out))
|
||||
}
|
||||
|
||||
/// Decrypt the on-disk layout `[nonce][ciphertext + tag]` **in place**.
|
||||
@@ -322,6 +332,13 @@ impl BlobStorageBackend for EncryptedBlobBackend {
|
||||
}
|
||||
|
||||
/// Collect a byte stream into a single `Vec<u8>`.
|
||||
///
|
||||
/// Modern blobs are CDC chunks (≤ `CDC_MAX_CHUNK` + nonce/tag overhead),
|
||||
/// delivered here as small reader frames — growing from `Vec::new()` paid
|
||||
/// ~log₂(n) reallocations + a wasted ~0.75×-size memcpy per read. Reserving
|
||||
/// one chunk's worth up front on the first frame makes the common case a
|
||||
/// single allocation; legacy whole-file blobs beyond that fall back to
|
||||
/// normal doubling (benches/ROUND11.md §16: 9 → 1 allocs on a 1 MiB blob).
|
||||
async fn collect_stream(stream: BlobStream) -> Result<Vec<u8>, DomainError> {
|
||||
use futures::StreamExt;
|
||||
let mut stream = stream;
|
||||
@@ -329,6 +346,14 @@ async fn collect_stream(stream: BlobStream) -> Result<Vec<u8>, DomainError> {
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let bytes = chunk
|
||||
.map_err(|e| DomainError::internal_error("Encryption", format!("stream read: {e}")))?;
|
||||
if buf.capacity() == 0 {
|
||||
buf.reserve(
|
||||
(crate::infrastructure::services::dedup_service::CDC_MAX_CHUNK
|
||||
+ NONCE_SIZE
|
||||
+ TAG_SIZE)
|
||||
.max(bytes.len()),
|
||||
);
|
||||
}
|
||||
buf.extend_from_slice(&bytes);
|
||||
}
|
||||
Ok(buf)
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for,
|
||||
classify_display, format_file_size, intern_display, intern_mime,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::FolderDto;
|
||||
@@ -197,18 +197,19 @@ impl PathResolverService {
|
||||
let hash = blob_hash.unwrap_or_default();
|
||||
let modified_at_u = modified_at as u64;
|
||||
let etag = File::compute_etag(&hash, modified_at_u);
|
||||
let classes = classify_display(&name, &mime);
|
||||
Ok(ResolvedResource::File(FileDto {
|
||||
id,
|
||||
name: name.clone(),
|
||||
path: res_path,
|
||||
size: sz,
|
||||
mime_type: Arc::from(&*mime),
|
||||
mime_type: intern_mime(&mime),
|
||||
folder_id,
|
||||
created_at: created_at as u64,
|
||||
modified_at: modified_at_u,
|
||||
icon_class: Arc::from(icon_class_for(&name, &mime)),
|
||||
icon_special_class: Arc::from(icon_special_class_for(&name, &mime)),
|
||||
category: Arc::from(category_for(&name, &mime)),
|
||||
icon_class: intern_display(classes.icon_class),
|
||||
icon_special_class: intern_display(classes.icon_special_class),
|
||||
category: intern_display(classes.category),
|
||||
size_formatted: format_file_size(sz),
|
||||
sort_date: None,
|
||||
content_hash: hash,
|
||||
|
||||
@@ -95,7 +95,7 @@ impl PathService {
|
||||
/// Validates a path to ensure it doesn't contain dangerous components
|
||||
pub fn validate_path(&self, path: &StoragePath) -> Result<(), DomainError> {
|
||||
// Check for empty segments
|
||||
if path.segments().iter().any(|s| s.is_empty()) {
|
||||
if path.segments().any(|s| s.is_empty()) {
|
||||
return Err(DomainError::new(
|
||||
ErrorKind::InvalidInput,
|
||||
"Path",
|
||||
|
||||
@@ -117,6 +117,16 @@ const CASCADE_GRANT_CACHE_CAPACITY: u64 = 100_000;
|
||||
/// invalidation tree". Short enough that any such change takes effect in <1 min.
|
||||
const CASCADE_GRANT_CACHE_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
/// `direct_grant_cache` bound/TTL: memoises the Calendar / AddressBook /
|
||||
/// Playlist `role_grants` point decision — the only `check()` arms that had
|
||||
/// NO result cache, re-run on every CalDAV/CardDAV/music request by clients
|
||||
/// that poll continuously. Same invalidation contract as
|
||||
/// `cascade_grant_cache`: grant writes on these resource types flush the
|
||||
/// whole cache; group/expiry churn self-heals within the TTL
|
||||
/// (benches/ROUND11.md §Q2).
|
||||
const DIRECT_GRANT_CACHE_CAPACITY: u64 = 100_000;
|
||||
const DIRECT_GRANT_CACHE_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
/// `file_parent_cache` bound/TTL: `file_id → Option<folder_id>` point rows
|
||||
/// (~50 B each) resolved on the file-cascade path so an N-file album pays
|
||||
/// ONE folder-cascade query instead of N (ROUND9). Parentage changes only
|
||||
@@ -212,6 +222,11 @@ pub struct PgAclEngine {
|
||||
/// only positively-or-negatively for at most the TTL. A revoke via
|
||||
/// `clear_role` flushes immediately; anything missed self-heals in ≤30 s.
|
||||
cascade_grant_cache: Cache<(Subject, Resource, Permission), bool>,
|
||||
|
||||
/// Memoised Calendar/AddressBook/Playlist direct-grant decision (the
|
||||
/// top-level resources with no cascade parent). See
|
||||
/// `DIRECT_GRANT_CACHE_CAPACITY` for the contract.
|
||||
direct_grant_cache: Cache<(Subject, Resource, Permission), bool>,
|
||||
/// `file_id → Option<parent folder_id>` memo for the file-cascade
|
||||
/// decomposition (see `cascade_grant_cached`): resolving the parent lets
|
||||
/// a whole folder's files share ONE folder-cascade decision, so a shared
|
||||
@@ -315,6 +330,10 @@ impl PgAclEngine {
|
||||
.max_capacity(CASCADE_GRANT_CACHE_CAPACITY)
|
||||
.time_to_live(CASCADE_GRANT_CACHE_TTL)
|
||||
.build(),
|
||||
direct_grant_cache: Cache::builder()
|
||||
.max_capacity(DIRECT_GRANT_CACHE_CAPACITY)
|
||||
.time_to_live(DIRECT_GRANT_CACHE_TTL)
|
||||
.build(),
|
||||
file_parent_cache: Cache::builder()
|
||||
.max_capacity(FILE_PARENT_CACHE_CAPACITY)
|
||||
.time_to_live(FILE_PARENT_CACHE_TTL)
|
||||
@@ -395,6 +414,10 @@ impl PgAclEngine {
|
||||
.max_capacity(1)
|
||||
.time_to_live(Duration::from_secs(1))
|
||||
.build(),
|
||||
direct_grant_cache: Cache::builder()
|
||||
.max_capacity(1)
|
||||
.time_to_live(Duration::from_secs(1))
|
||||
.build(),
|
||||
file_parent_cache: Cache::builder()
|
||||
.max_capacity(1)
|
||||
.time_to_live(Duration::from_secs(1))
|
||||
@@ -568,26 +591,38 @@ impl PgAclEngine {
|
||||
// belong to the Internal virtual group. Unknown user (no row) is
|
||||
// treated as external to fail closed: a deleted or bogus user_id
|
||||
// must not gain implicit Internal membership.
|
||||
//
|
||||
// The `is_external` point read and the recursive groups CTE are
|
||||
// independent — `join!` overlaps their round-trips on every cold
|
||||
// expansion instead of paying them serially (benches/ROUND11.md
|
||||
// §Q3; the ROUND9/10 pattern).
|
||||
counters.sql_queries.fetch_add(1, Ordering::Relaxed);
|
||||
let is_external: bool =
|
||||
sqlx::query_scalar("SELECT is_external FROM auth.users WHERE id = $1")
|
||||
let is_external_fut = async {
|
||||
sqlx::query_scalar::<_, bool>("SELECT is_external FROM auth.users WHERE id = $1")
|
||||
.bind(user_id)
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
DomainError::internal_error("PgAcl", format!("lookup is_external: {e}"))
|
||||
})?
|
||||
.unwrap_or(true);
|
||||
|
||||
if !is_external {
|
||||
})
|
||||
.map(|row| row.unwrap_or(true))
|
||||
};
|
||||
let groups_fut = async {
|
||||
match &self.group_repo {
|
||||
Some(repo) => {
|
||||
counters.sql_queries.fetch_add(1, Ordering::Relaxed);
|
||||
repo.groups_for_user(user_id).await.map(Some).map_err(|e| {
|
||||
DomainError::internal_error("PgAcl", format!("groups_for_user: {e}"))
|
||||
})
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
};
|
||||
let (is_external, direct) = tokio::join!(is_external_fut, groups_fut);
|
||||
if !is_external? {
|
||||
set.insert(INTERNAL_GROUP_ID);
|
||||
}
|
||||
|
||||
if let Some(repo) = &self.group_repo {
|
||||
counters.sql_queries.fetch_add(1, Ordering::Relaxed);
|
||||
let direct = repo.groups_for_user(user_id).await.map_err(|e| {
|
||||
DomainError::internal_error("PgAcl", format!("groups_for_user: {e}"))
|
||||
})?;
|
||||
if let Some(direct) = direct? {
|
||||
set.extend(direct);
|
||||
}
|
||||
|
||||
@@ -1099,6 +1134,48 @@ impl PgAclEngine {
|
||||
/// (on File/Folder grant writes — it holds file AND folder decisions in
|
||||
/// the same map) and the 30 s TTL (indirect changes, incl. moves for the
|
||||
/// parent memo) keep it fresh. See the `cascade_grant_cache` field doc.
|
||||
/// Cached wrapper for the Calendar/AddressBook/Playlist direct-grant
|
||||
/// decision (`try_get_with`: a cold herd on one key coalesces into ONE
|
||||
/// loader run, the ROUND10 single-flight pattern; loader errors are
|
||||
/// never cached). `resource_type` is the `role_grants.resource_type`
|
||||
/// discriminant for `resource`.
|
||||
async fn direct_grant_cached(
|
||||
&self,
|
||||
subject: Subject,
|
||||
resource: Resource,
|
||||
permission: Permission,
|
||||
resource_type: &'static str,
|
||||
id: Uuid,
|
||||
counters: &QueryCounters,
|
||||
) -> Result<bool, DomainError> {
|
||||
if let Some(allowed) = self
|
||||
.direct_grant_cache
|
||||
.get(&(subject, resource, permission))
|
||||
.await
|
||||
{
|
||||
counters.cache_hit.fetch_add(1, Ordering::Relaxed);
|
||||
return Ok(allowed);
|
||||
}
|
||||
self.direct_grant_cache
|
||||
.try_get_with((subject, resource, permission), async {
|
||||
let (subject_types, subject_ids) =
|
||||
self.subject_match_set(subject, counters).await?;
|
||||
self.direct_grant_exists(
|
||||
&subject_types,
|
||||
&subject_ids,
|
||||
permission,
|
||||
resource_type,
|
||||
id,
|
||||
counters,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
.map_err(|e: Arc<DomainError>| {
|
||||
DomainError::internal_error("PgAcl", format!("direct grant load: {e}"))
|
||||
})
|
||||
}
|
||||
|
||||
async fn cascade_grant_cached(
|
||||
&self,
|
||||
subject: Subject,
|
||||
@@ -1493,24 +1570,13 @@ impl PgAclEngine {
|
||||
// round-trip — no drive_role_cache short-circuit (no
|
||||
// drive), no cascade.
|
||||
Resource::Calendar(id) => {
|
||||
let (subject_types, subject_ids) =
|
||||
self.subject_match_set(subject, counters).await?;
|
||||
self.direct_grant_exists(
|
||||
&subject_types,
|
||||
&subject_ids,
|
||||
permission,
|
||||
"calendar",
|
||||
id,
|
||||
counters,
|
||||
)
|
||||
.await
|
||||
self.direct_grant_cached(subject, resource, permission, "calendar", id, counters)
|
||||
.await
|
||||
}
|
||||
Resource::AddressBook(id) => {
|
||||
let (subject_types, subject_ids) =
|
||||
self.subject_match_set(subject, counters).await?;
|
||||
self.direct_grant_exists(
|
||||
&subject_types,
|
||||
&subject_ids,
|
||||
self.direct_grant_cached(
|
||||
subject,
|
||||
resource,
|
||||
permission,
|
||||
"address_book",
|
||||
id,
|
||||
@@ -1519,17 +1585,8 @@ impl PgAclEngine {
|
||||
.await
|
||||
}
|
||||
Resource::Playlist(id) => {
|
||||
let (subject_types, subject_ids) =
|
||||
self.subject_match_set(subject, counters).await?;
|
||||
self.direct_grant_exists(
|
||||
&subject_types,
|
||||
&subject_ids,
|
||||
permission,
|
||||
"playlist",
|
||||
id,
|
||||
counters,
|
||||
)
|
||||
.await
|
||||
self.direct_grant_cached(subject, resource, permission, "playlist", id, counters)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2874,6 +2931,13 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
if matches!(resource, Resource::File(_) | Resource::Folder(_)) {
|
||||
self.invalidate_cascade_grant_cache_all().await;
|
||||
}
|
||||
// Same immediacy contract for the memoised top-level decisions.
|
||||
if matches!(
|
||||
resource,
|
||||
Resource::Calendar(_) | Resource::AddressBook(_) | Resource::Playlist(_)
|
||||
) {
|
||||
self.direct_grant_cache.invalidate_all();
|
||||
}
|
||||
|
||||
Self::row_to_grant(row)
|
||||
}
|
||||
@@ -2903,6 +2967,14 @@ impl AuthorizationEngine for PgAclEngine {
|
||||
if matches!(resource, Resource::File(_) | Resource::Folder(_)) {
|
||||
self.invalidate_cascade_grant_cache_all().await;
|
||||
}
|
||||
// A revoked calendar/address-book/playlist grant must fail the next
|
||||
// check now, not in ≤30 s (see `set_role`).
|
||||
if matches!(
|
||||
resource,
|
||||
Resource::Calendar(_) | Resource::AddressBook(_) | Resource::Playlist(_)
|
||||
) {
|
||||
self.direct_grant_cache.invalidate_all();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -57,14 +57,20 @@ impl RetryBlobBackend {
|
||||
}
|
||||
|
||||
/// Execute an async closure with exponential backoff retry.
|
||||
async fn retry_async<F, Fut, T>(
|
||||
///
|
||||
/// `name` is a lazy label: the success path (the overwhelmingly common
|
||||
/// case) never materializes it, so per-op `format!("op({hash})")`
|
||||
/// allocations only happen on an actual retry (benches/ROUND11.md §14:
|
||||
/// 64.5 → 0.7 ns, −2 allocs per blob op).
|
||||
async fn retry_async<F, Fut, T, L>(
|
||||
policy: &RetryPolicy,
|
||||
name: &str,
|
||||
name: L,
|
||||
mut f: F,
|
||||
) -> Result<T, DomainError>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = Result<T, DomainError>>,
|
||||
L: Fn() -> String,
|
||||
{
|
||||
let mut attempt = 0u32;
|
||||
let mut backoff = policy.initial_backoff;
|
||||
@@ -78,7 +84,7 @@ where
|
||||
"Retry {}/{} for {} after error: {} (backoff {:?})",
|
||||
attempt,
|
||||
policy.max_retries,
|
||||
name,
|
||||
name(),
|
||||
e,
|
||||
backoff
|
||||
);
|
||||
@@ -112,10 +118,14 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let inner = self.inner.clone();
|
||||
let policy = self.policy.clone();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, "initialize", || {
|
||||
let inner = inner.clone();
|
||||
async move { inner.initialize().await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| "initialize".to_string(),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
async move { inner.initialize().await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -130,12 +140,16 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let hash = hash.to_string();
|
||||
let path = source_path.to_path_buf();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("put_blob({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
let path = path.clone();
|
||||
async move { inner.put_blob(&hash, &path).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("put_blob({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
let path = path.clone();
|
||||
async move { inner.put_blob(&hash, &path).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -149,12 +163,16 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let policy = self.policy.clone();
|
||||
let hash = hash.to_string();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("put_blob_from_bytes({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
let data = data.clone();
|
||||
async move { inner.put_blob_from_bytes(&hash, data).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("put_blob_from_bytes({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
let data = data.clone();
|
||||
async move { inner.put_blob_from_bytes(&hash, data).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -174,7 +192,7 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
Box::pin(async move {
|
||||
retry_async(
|
||||
&policy,
|
||||
&format!("put_blob_from_bytes_unsynced({hash})"),
|
||||
|| format!("put_blob_from_bytes_unsynced({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
@@ -205,11 +223,15 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let policy = self.policy.clone();
|
||||
let hash = hash.to_string();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("get_blob_stream({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.get_blob_stream(&hash).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("get_blob_stream({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.get_blob_stream(&hash).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -225,11 +247,15 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let policy = self.policy.clone();
|
||||
let hash = hash.to_string();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("get_blob_range({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.get_blob_range_stream(&hash, start, end).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("get_blob_range({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.get_blob_range_stream(&hash, start, end).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -242,11 +268,15 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let policy = self.policy.clone();
|
||||
let hash = hash.to_string();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("delete_blob({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.delete_blob(&hash).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("delete_blob({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.delete_blob(&hash).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -259,11 +289,15 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let policy = self.policy.clone();
|
||||
let hash = hash.to_string();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("blob_exists({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.blob_exists(&hash).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("blob_exists({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.blob_exists(&hash).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -276,11 +310,15 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let policy = self.policy.clone();
|
||||
let hash = hash.to_string();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, &format!("blob_size({hash})"), || {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.blob_size(&hash).await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| format!("blob_size({hash})"),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
let hash = hash.clone();
|
||||
async move { inner.blob_size(&hash).await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
@@ -293,10 +331,14 @@ impl BlobStorageBackend for RetryBlobBackend {
|
||||
let inner = self.inner.clone();
|
||||
let policy = self.policy.clone();
|
||||
Box::pin(async move {
|
||||
retry_async(&policy, "health_check", || {
|
||||
let inner = inner.clone();
|
||||
async move { inner.health_check().await }
|
||||
})
|
||||
retry_async(
|
||||
&policy,
|
||||
|| "health_check".to_string(),
|
||||
|| {
|
||||
let inner = inner.clone();
|
||||
async move { inner.health_check().await }
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
@@ -141,8 +141,10 @@ pub fn append_clear_cookies(headers: &mut HeaderMap) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a named cookie value from the `Cookie` request header.
|
||||
pub fn extract_cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
/// Extract a named cookie value from the `Cookie` request header,
|
||||
/// borrowing from the header map. Callers that only compare or parse the
|
||||
/// value (CSRF check) avoid the per-request copy.
|
||||
pub fn extract_cookie_str<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> {
|
||||
let cookie_header = headers.get(axum::http::header::COOKIE)?;
|
||||
let cookie_str = cookie_header.to_str().ok()?;
|
||||
|
||||
@@ -151,13 +153,18 @@ pub fn extract_cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
if let Some(val) = pair.strip_prefix(name) {
|
||||
let val = val.strip_prefix('=')?;
|
||||
if !val.is_empty() {
|
||||
return Some(val.to_string());
|
||||
return Some(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Extract a named cookie value from the `Cookie` request header.
|
||||
pub fn extract_cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
extract_cookie_str(headers, name).map(str::to_string)
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────
|
||||
// CSRF double-submit cookie helpers
|
||||
// ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -10,8 +10,7 @@ use tracing::info;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for, intern_display,
|
||||
intern_mime,
|
||||
classify_display, format_file_size, intern_display, intern_mime,
|
||||
};
|
||||
use crate::application::dtos::favorites_dto::{
|
||||
FavoritesResourceItemDto, FavoritesResourcesDto, FavoritesResourcesQuery,
|
||||
@@ -247,10 +246,10 @@ pub async fn list_favorites_resources(
|
||||
};
|
||||
// Name-derived display classes borrow `row.name`;
|
||||
// compute them before the name moves into the DTO.
|
||||
let icon_class = intern_display(icon_class_for(&row.name, mime));
|
||||
let icon_special_class =
|
||||
intern_display(icon_special_class_for(&row.name, mime));
|
||||
let category = intern_display(category_for(&row.name, mime));
|
||||
let classes = classify_display(&row.name, mime);
|
||||
let icon_class = intern_display(classes.icon_class);
|
||||
let icon_special_class = intern_display(classes.icon_special_class);
|
||||
let category = intern_display(classes.category);
|
||||
let dto = FileDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name,
|
||||
|
||||
@@ -404,7 +404,18 @@ impl FileHandler {
|
||||
// (file_id, size, format) triple. If the browser already has it, return
|
||||
// 304 with zero I/O or DB work. Format is in the ETag so a client that
|
||||
// switched codecs doesn't get a stale 304.
|
||||
let etag = format!("\"thumb-{}-{:?}-{:?}\"", id, thumb_size, format);
|
||||
let etag = {
|
||||
let (s, f) = (thumb_size.as_str(), format.as_str());
|
||||
let mut e = String::with_capacity(9 + id.len() + s.len() + f.len());
|
||||
e.push_str("\"thumb-");
|
||||
e.push_str(&id);
|
||||
e.push('-');
|
||||
e.push_str(s);
|
||||
e.push('-');
|
||||
e.push_str(f);
|
||||
e.push('"');
|
||||
e
|
||||
};
|
||||
if let Some(if_none_match) = headers.get(header::IF_NONE_MATCH)
|
||||
&& let Ok(val) = if_none_match.to_str()
|
||||
&& (val == etag || val == "*")
|
||||
@@ -776,9 +787,15 @@ impl FileHandler {
|
||||
|
||||
// Use the ownership-scoped optimized download.
|
||||
// Ownership was already verified by get_file_owned above,
|
||||
// so we can safely use the preloaded variant.
|
||||
// so we can safely use the preloaded variant. Capture the two
|
||||
// fields the stream arm needs (one Arc bump + a u64 copy) and MOVE
|
||||
// the DTO in — the old `file_dto.clone()` deep-copied all 7 owned
|
||||
// Strings on every download, purely to read mime/size afterwards
|
||||
// (benches/ROUND11.md §1).
|
||||
let dto_mime = file_dto.mime_type.clone();
|
||||
let dto_size = file_dto.size;
|
||||
match retrieval
|
||||
.get_file_optimized_preloaded(&id, file_dto.clone(), accept_webp, prefer_original)
|
||||
.get_file_optimized_preloaded(&id, file_dto, accept_webp, prefer_original)
|
||||
.await
|
||||
{
|
||||
Ok((_file, content)) => match content {
|
||||
@@ -788,9 +805,9 @@ impl FileHandler {
|
||||
.into_response(),
|
||||
OptimizedFileContent::Stream(pinned_stream) => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, &*file_dto.mime_type)
|
||||
.header(header::CONTENT_TYPE, &*dto_mime)
|
||||
.header(header::CONTENT_DISPOSITION, &disposition)
|
||||
.header(header::CONTENT_LENGTH, file_dto.size)
|
||||
.header(header::CONTENT_LENGTH, dto_size)
|
||||
.header(header::ETAG, &etag)
|
||||
.header(
|
||||
header::CACHE_CONTROL,
|
||||
|
||||
@@ -8,8 +8,7 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for, intern_display,
|
||||
intern_mime,
|
||||
classify_display, format_file_size, intern_display, intern_mime,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::{
|
||||
@@ -520,10 +519,10 @@ pub async fn list_folder_resources(
|
||||
// (they borrow `&row.name`), so `name` can be moved into
|
||||
// the DTO below instead of cloned — one fewer String
|
||||
// alloc per file row (benches/ROUND7.md).
|
||||
let icon_class = intern_display(icon_class_for(&row.name, mime));
|
||||
let icon_special_class =
|
||||
intern_display(icon_special_class_for(&row.name, mime));
|
||||
let category = intern_display(category_for(&row.name, mime));
|
||||
let classes = classify_display(&row.name, mime);
|
||||
let icon_class = intern_display(classes.icon_class);
|
||||
let icon_special_class = intern_display(classes.icon_special_class);
|
||||
let category = intern_display(classes.category);
|
||||
let dto = FileDto {
|
||||
id: row.id.to_string(),
|
||||
name: row.name,
|
||||
|
||||
@@ -8,8 +8,7 @@ use std::sync::Arc;
|
||||
use tracing::info;
|
||||
|
||||
use crate::application::dtos::display_helpers::{
|
||||
category_for, format_file_size, icon_class_for, icon_special_class_for, intern_display,
|
||||
intern_mime,
|
||||
classify_display, format_file_size, intern_display, intern_mime,
|
||||
};
|
||||
use crate::application::dtos::file_dto::FileDto;
|
||||
use crate::application::dtos::folder_dto::FolderDto;
|
||||
@@ -57,8 +56,10 @@ pub async fn record_item_access(
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let mut id_buf = [0u8; 36];
|
||||
let item_id_str: &str = item_id.as_hyphenated().encode_lower(&mut id_buf);
|
||||
match recent_service
|
||||
.record_item_access(user_id, &item_id.to_string(), &item_type)
|
||||
.record_item_access(user_id, item_id_str, &item_type)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
@@ -100,8 +101,10 @@ pub async fn remove_from_recent(
|
||||
) -> impl IntoResponse {
|
||||
let user_id = auth_user.id;
|
||||
|
||||
let mut id_buf = [0u8; 36];
|
||||
let item_id_str: &str = item_id.as_hyphenated().encode_lower(&mut id_buf);
|
||||
match recent_service
|
||||
.remove_from_recent(user_id, &item_id.to_string(), &item_type)
|
||||
.remove_from_recent(user_id, item_id_str, &item_type)
|
||||
.await
|
||||
{
|
||||
Ok(removed) => {
|
||||
@@ -261,10 +264,10 @@ pub async fn list_recent_resources(
|
||||
};
|
||||
// Name-derived display classes borrow `row.name`;
|
||||
// compute them before the name moves into the DTO.
|
||||
let icon_class = intern_display(icon_class_for(&row.name, mime));
|
||||
let icon_special_class =
|
||||
intern_display(icon_special_class_for(&row.name, mime));
|
||||
let category = intern_display(category_for(&row.name, mime));
|
||||
let classes = classify_display(&row.name, mime);
|
||||
let icon_class = intern_display(classes.icon_class);
|
||||
let icon_special_class = intern_display(classes.icon_special_class);
|
||||
let category = intern_display(classes.category);
|
||||
let dto = FileDto {
|
||||
id: row.resource_id.to_string(),
|
||||
name: row.name,
|
||||
|
||||
@@ -46,8 +46,23 @@ async fn get_version() -> AxumJson<serde_json::Value> {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn get_openapi_spec() -> AxumJson<utoipa::openapi::OpenApi> {
|
||||
AxumJson(super::ApiDoc::openapi())
|
||||
/// Pre-serialized OpenAPI spec. `ApiDoc::openapi()` reconstructs the whole
|
||||
/// 171 KiB paths/schemas tree and re-serializes it per request (2.8 ms /
|
||||
/// 12 474 allocs); the spec is process-invariant, so serialize once and
|
||||
/// hand back a `Bytes` refcount bump (~18 ns — benches/ROUND11.md).
|
||||
static OPENAPI_BODY: std::sync::OnceLock<bytes::Bytes> = std::sync::OnceLock::new();
|
||||
|
||||
async fn get_openapi_spec() -> axum::response::Response {
|
||||
let body = OPENAPI_BODY.get_or_init(|| {
|
||||
bytes::Bytes::from(
|
||||
serde_json::to_vec(&super::ApiDoc::openapi()).expect("openapi spec serializes"),
|
||||
)
|
||||
});
|
||||
axum::response::Response::builder()
|
||||
.status(axum::http::StatusCode::OK)
|
||||
.header(axum::http::header::CONTENT_TYPE, "application/json")
|
||||
.body(axum::body::Body::from(body.clone()))
|
||||
.expect("static openapi response")
|
||||
}
|
||||
|
||||
use crate::interfaces::api::handlers::admin_handler;
|
||||
|
||||
+27
-21
@@ -3,6 +3,8 @@
|
||||
//! This module contains error types specific to the HTTP/API layer.
|
||||
//! These errors handle the conversion from domain errors to HTTP responses.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use axum::Json;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
@@ -13,25 +15,28 @@ use crate::domain::errors::{DomainError, ErrorKind};
|
||||
/// Error type for HTTP/API responses.
|
||||
///
|
||||
/// This struct represents errors that will be returned to HTTP clients.
|
||||
/// It contains the HTTP status code, a user-friendly message, and an error type identifier.
|
||||
/// It contains the HTTP status code, a user-friendly message, and an error
|
||||
/// type identifier. `error_type` is a `Cow`: every built-in constructor and
|
||||
/// the `DomainError` conversion use a `&'static str` from a closed set, so
|
||||
/// the common 4xx path allocates nothing for it (benches/ROUND11.md §9).
|
||||
#[derive(Debug)]
|
||||
pub struct AppError {
|
||||
pub status_code: StatusCode,
|
||||
pub message: String,
|
||||
pub error_type: String,
|
||||
pub error_type: Cow<'static, str>,
|
||||
}
|
||||
|
||||
/// JSON response structure for errors.
|
||||
///
|
||||
/// Both `error` and `message` carry the same content for backwards compatibility:
|
||||
/// - Legacy ad-hoc handlers returned `{"error": "..."}` (frontend reads `.error`)
|
||||
/// - AppError returned `{"message": "..."}` (admin panel reads `.message`)
|
||||
/// JSON response structure for errors, borrowing from the `AppError` it
|
||||
/// renders — `error` and `message` intentionally serialize the SAME string
|
||||
/// for backwards compatibility (legacy handlers returned `{"error": …}`,
|
||||
/// AppError returned `{"message": …}`); serializing one buffer twice
|
||||
/// replaces the old per-response deep clone.
|
||||
#[derive(Serialize)]
|
||||
pub struct ErrorResponse {
|
||||
pub status: String,
|
||||
pub error: String,
|
||||
pub message: String,
|
||||
pub error_type: String,
|
||||
pub struct ErrorResponse<'a> {
|
||||
pub status: &'a str,
|
||||
pub error: &'a str,
|
||||
pub message: &'a str,
|
||||
pub error_type: &'a str,
|
||||
}
|
||||
|
||||
impl AppError {
|
||||
@@ -39,7 +44,7 @@ impl AppError {
|
||||
pub fn new(
|
||||
status_code: StatusCode,
|
||||
message: impl Into<String>,
|
||||
error_type: impl Into<String>,
|
||||
error_type: impl Into<Cow<'static, str>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
status_code,
|
||||
@@ -131,7 +136,7 @@ impl From<DomainError> for AppError {
|
||||
Self {
|
||||
status_code,
|
||||
message: err.message,
|
||||
error_type: err.kind.to_string(),
|
||||
error_type: Cow::Borrowed(err.kind.as_str()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,25 +149,26 @@ impl IntoResponse for AppError {
|
||||
// Log the full error server-side for debugging, return a generic
|
||||
// message to the client. Other status codes (including 5xx like
|
||||
// 501, 503, 507) keep their intentionally user-facing messages.
|
||||
let client_message = if status == StatusCode::INTERNAL_SERVER_ERROR {
|
||||
let client_message: &str = if status == StatusCode::INTERNAL_SERVER_ERROR {
|
||||
tracing::error!(
|
||||
error_type = %self.error_type,
|
||||
"Internal server error: {}",
|
||||
self.message
|
||||
);
|
||||
"An internal error occurred. Please try again later.".to_string()
|
||||
"An internal error occurred. Please try again later."
|
||||
} else {
|
||||
self.message
|
||||
&self.message
|
||||
};
|
||||
|
||||
let status_line = status.to_string();
|
||||
let error_response = ErrorResponse {
|
||||
status: status.to_string(),
|
||||
error: client_message.clone(),
|
||||
status: &status_line,
|
||||
error: client_message,
|
||||
message: client_message,
|
||||
error_type: self.error_type,
|
||||
error_type: &self.error_type,
|
||||
};
|
||||
|
||||
let body = Json(error_response);
|
||||
let body = Json(&error_response);
|
||||
(status, body).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,16 +39,17 @@ pub async fn csrf_middleware(request: Request, next: Next) -> Result<Response, R
|
||||
return Ok(next.run(request).await);
|
||||
}
|
||||
|
||||
// Extract the CSRF token from the cookie.
|
||||
let cookie_token =
|
||||
cookie_auth::extract_cookie_value(request.headers(), cookie_auth::CSRF_COOKIE);
|
||||
// Extract the CSRF token from the cookie (borrow-only).
|
||||
let cookie_token = cookie_auth::extract_cookie_str(request.headers(), cookie_auth::CSRF_COOKIE);
|
||||
|
||||
// Extract the CSRF token from the request header.
|
||||
// Extract the CSRF token from the request header. Borrow-only:
|
||||
// `String: PartialEq<&str>` covers the comparison, so materializing an
|
||||
// owned copy per state-changing request was a pure waste
|
||||
// (benches/ROUND11.md §6: 15.7 → 1.3 ns, −1 alloc).
|
||||
let header_token = request
|
||||
.headers()
|
||||
.get(cookie_auth::CSRF_HEADER)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(|s| s.to_string());
|
||||
.and_then(|v| v.to_str().ok());
|
||||
|
||||
match (cookie_token, header_token) {
|
||||
(Some(c), Some(h)) if !c.is_empty() && c == h => {
|
||||
|
||||
@@ -55,18 +55,18 @@ impl RateLimiter {
|
||||
/// `Err(StatusCode::TOO_MANY_REQUESTS)`.
|
||||
#[allow(clippy::result_unit_err)]
|
||||
pub fn check_and_increment(&self, ip: &str) -> Result<u32, ()> {
|
||||
let key = ip.to_string();
|
||||
// moka's entry API lets us atomically read-modify-write.
|
||||
// On first access the entry is inserted with count = 1 and the TTL
|
||||
// starts. Subsequent accesses within the window increment the count.
|
||||
let count = self.cache.entry(key).or_insert_with(|| 0).into_value() + 1;
|
||||
// Lock-free read (borrows the key — no allocation), then one
|
||||
// write-back. The previous shape allocated the key TWICE and paid
|
||||
// a locking `entry()` op on top of the insert; moka's
|
||||
// `and_upsert_with` alternative benchmarked slower still
|
||||
// (benches/ROUND11.md §20). Read-then-write is not atomic, but it
|
||||
// never was — under a concurrent burst both shapes can undercount
|
||||
// the same way, which only makes the limiter marginally lenient,
|
||||
// never wrongly strict.
|
||||
let count = self.cache.get(ip).unwrap_or(0) + 1;
|
||||
|
||||
// Write back the incremented value. Because `or_insert_with` returns
|
||||
// the *existing* value when the key was already present, we must always
|
||||
// re-insert so the counter actually advances. The TTL of the **first**
|
||||
// insert still governs eviction because moka uses insert-time TTL.
|
||||
// However, on re-insert moka resets the TTL, for rate limiting this
|
||||
// is fine because it means the window "slides" forward on activity.
|
||||
// On re-insert moka resets the TTL; for rate limiting this is fine
|
||||
// because it means the window "slides" forward on activity.
|
||||
self.cache.insert(ip.to_string(), count);
|
||||
|
||||
if count > self.max_requests {
|
||||
|
||||
@@ -35,12 +35,12 @@ fn ocs_err(statuscode: u16, message: &str) -> serde_json::Value {
|
||||
}
|
||||
|
||||
pub async fn handle_capabilities_v1(State(state): State<Arc<AppState>>) -> Response {
|
||||
tracing::info!("[NC] capabilities v1 requested, returning payload");
|
||||
tracing::debug!("[NC] capabilities v1 requested, returning payload");
|
||||
capabilities_response(&state, 1)
|
||||
}
|
||||
|
||||
pub async fn handle_capabilities_v2(State(state): State<Arc<AppState>>) -> Response {
|
||||
tracing::info!("[NC] capabilities v2 requested, returning payload");
|
||||
tracing::debug!("[NC] capabilities v2 requested, returning payload");
|
||||
capabilities_response(&state, 2)
|
||||
}
|
||||
|
||||
|
||||
@@ -144,7 +144,16 @@ pub async fn handle_preview(
|
||||
// compared it, so every revalidation re-ran the whole pipeline and
|
||||
// re-shipped the body (ROUND10). Authz already passed above; a 304
|
||||
// must never skip the Read check.
|
||||
let etag = format!("\"thumb-{}-{:?}\"", object_id, thumb_size);
|
||||
let etag = {
|
||||
let s = thumb_size.as_str();
|
||||
let mut e = String::with_capacity(9 + object_id.len() + s.len());
|
||||
e.push_str("\"thumb-");
|
||||
e.push_str(&object_id);
|
||||
e.push('-');
|
||||
e.push_str(s);
|
||||
e.push('"');
|
||||
e
|
||||
};
|
||||
if let Some(inm) = headers.get(header::IF_NONE_MATCH)
|
||||
&& let Ok(client_etag) = inm.to_str()
|
||||
&& (client_etag == etag || client_etag == "*")
|
||||
|
||||
@@ -1,22 +1,36 @@
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::http::header;
|
||||
use axum::response::Response;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::common::di::AppState;
|
||||
|
||||
/// Pre-serialized `/status.php` body. The payload is process-invariant
|
||||
/// (pure config: emulated NC version), yet every NC desktop/mobile client
|
||||
/// polls it on connect and periodically — the old handler re-built the
|
||||
/// `json!` tree and re-serialized on every poll (793 ns / 14 allocs;
|
||||
/// now a `Bytes` refcount bump at ~29 ns / 0 allocs — benches/ROUND11.md).
|
||||
static STATUS_BODY: std::sync::OnceLock<bytes::Bytes> = std::sync::OnceLock::new();
|
||||
|
||||
pub async fn handle_status(State(state): State<Arc<AppState>>) -> Response {
|
||||
let (major, minor, patch) = state.core.config.nextcloud.emulated_version;
|
||||
let version_string = state.core.config.nextcloud.version_string();
|
||||
Json(json!({
|
||||
"installed": true,
|
||||
"maintenance": false,
|
||||
"needsDbUpgrade": false,
|
||||
"version": format!("{}.{}.{}.1", major, minor, patch),
|
||||
"versionstring": version_string,
|
||||
"productname": "OxiCloud",
|
||||
"edition": ""
|
||||
}))
|
||||
.into_response()
|
||||
let body = STATUS_BODY.get_or_init(|| {
|
||||
let (major, minor, patch) = state.core.config.nextcloud.emulated_version;
|
||||
let version_string = state.core.config.nextcloud.version_string();
|
||||
let v = json!({
|
||||
"installed": true,
|
||||
"maintenance": false,
|
||||
"needsDbUpgrade": false,
|
||||
"version": format!("{}.{}.{}.1", major, minor, patch),
|
||||
"versionstring": version_string,
|
||||
"productname": "OxiCloud",
|
||||
"edition": ""
|
||||
});
|
||||
bytes::Bytes::from(serde_json::to_vec(&v).expect("status.php body serializes"))
|
||||
});
|
||||
Response::builder()
|
||||
.status(axum::http::StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(axum::body::Body::from(body.clone()))
|
||||
.expect("static status.php response")
|
||||
}
|
||||
|
||||
@@ -171,53 +171,71 @@ async fn handle_propfind_session(
|
||||
// `handle_assemble`'s destination-URL parsing. Storage-side keying
|
||||
// stays on `user.username` — upload sessions are per-user, not
|
||||
// per-drive.
|
||||
let session_href = format!(
|
||||
"/remote.php/dav/uploads/{}/{}/",
|
||||
session.raw_username, upload_id
|
||||
);
|
||||
let session_last_modified =
|
||||
chrono::DateTime::<chrono::Utc>::from_timestamp(listing.session_mtime as i64, 0)
|
||||
.unwrap_or_else(chrono::Utc::now)
|
||||
.to_rfc2822();
|
||||
// `write!` formats every element straight into a pre-sized `body`; the
|
||||
// old `push_str(&format!(…))` chain allocated a throwaway String per
|
||||
// element per chunk plus growth reallocations from `String::new()`, and
|
||||
// ran the chrono format interpreter per chunk (benches/ROUND11.md §4:
|
||||
// 2.3-2.6x, allocs 2582 → 772 on a 256-chunk session).
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let mut body = String::new();
|
||||
/// `<d:getlastmodified>` via the stack renderer; chrono fallback for
|
||||
/// out-of-range timestamps (same shape as `nextcloud/webdav_handler`).
|
||||
/// RFC 2822 output contains no XML-special characters by construction.
|
||||
fn write_lastmodified(body: &mut String, secs: i64) {
|
||||
let mut buf = [0u8; 31];
|
||||
match crate::common::fmt::rfc2822_utc(&mut buf, secs) {
|
||||
Some(s) => {
|
||||
let _ = write!(body, "<d:getlastmodified>{}</d:getlastmodified>", s);
|
||||
}
|
||||
None => {
|
||||
let dt = chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0)
|
||||
.unwrap_or_else(chrono::Utc::now)
|
||||
.to_rfc2822();
|
||||
let _ = write!(
|
||||
body,
|
||||
"<d:getlastmodified>{}</d:getlastmodified>",
|
||||
xml_escape(&dt)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut body = String::with_capacity(256 + listing.chunks.len() * 256);
|
||||
body.push_str(r#"<?xml version="1.0" encoding="utf-8"?>"#);
|
||||
body.push_str(r#"<d:multistatus xmlns:d="DAV:">"#);
|
||||
|
||||
// Session collection itself.
|
||||
body.push_str("<d:response>");
|
||||
body.push_str(&format!("<d:href>{}</d:href>", xml_escape(&session_href)));
|
||||
let _ = write!(
|
||||
body,
|
||||
"<d:href>/remote.php/dav/uploads/{}/{}/</d:href>",
|
||||
xml_escape(&session.raw_username),
|
||||
xml_escape(upload_id)
|
||||
);
|
||||
body.push_str("<d:propstat><d:prop>");
|
||||
body.push_str("<d:resourcetype><d:collection/></d:resourcetype>");
|
||||
body.push_str(&format!(
|
||||
"<d:getlastmodified>{}</d:getlastmodified>",
|
||||
xml_escape(&session_last_modified)
|
||||
));
|
||||
write_lastmodified(&mut body, listing.session_mtime as i64);
|
||||
body.push_str("</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>");
|
||||
body.push_str("</d:response>");
|
||||
|
||||
// One entry per chunk file.
|
||||
for chunk in &listing.chunks {
|
||||
let chunk_href = format!(
|
||||
"/remote.php/dav/uploads/{}/{}/{}",
|
||||
session.raw_username, upload_id, chunk.name
|
||||
);
|
||||
let chunk_modified = chrono::DateTime::<chrono::Utc>::from_timestamp(chunk.mtime as i64, 0)
|
||||
.unwrap_or_else(chrono::Utc::now)
|
||||
.to_rfc2822();
|
||||
|
||||
body.push_str("<d:response>");
|
||||
body.push_str(&format!("<d:href>{}</d:href>", xml_escape(&chunk_href)));
|
||||
let _ = write!(
|
||||
body,
|
||||
"<d:href>/remote.php/dav/uploads/{}/{}/{}</d:href>",
|
||||
xml_escape(&session.raw_username),
|
||||
xml_escape(upload_id),
|
||||
xml_escape(&chunk.name)
|
||||
);
|
||||
body.push_str("<d:propstat><d:prop>");
|
||||
body.push_str("<d:resourcetype/>");
|
||||
body.push_str(&format!(
|
||||
let _ = write!(
|
||||
body,
|
||||
"<d:getcontentlength>{}</d:getcontentlength>",
|
||||
chunk.size
|
||||
));
|
||||
body.push_str(&format!(
|
||||
"<d:getlastmodified>{}</d:getlastmodified>",
|
||||
xml_escape(&chunk_modified)
|
||||
));
|
||||
);
|
||||
write_lastmodified(&mut body, chunk.mtime as i64);
|
||||
body.push_str("</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>");
|
||||
body.push_str("</d:response>");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user