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:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user