perf: round 10 — auth alloc purge, parent-herd batching, query-shape pack, NC 304s
Benchmark-gated (benches/ROUND10.md; every change carries a BEFORE/AFTER harness with equivalence/safety gates — two designs were rejected or rewritten by their own benches before adoption): - Auth hot path: TokenClaims/CurrentUser display fields to Arc<str>, role to inline SmolStr end-to-end (Bearer, cookie, Basic-auth cache) — 4→1 allocs per authenticated request, 3→0 per warm DAV request; JWT Encoding/Decoding/Validation built once. - Cold shared-album herd: leader-inline parent batching in PgAclEngine (+ cascade try_get_with single-flight) — 100→2 parent queries per 100-thumb cold herd, herd wall 1.9x, sequential + warm paths unchanged, all ROUND8/9 safety gates plus new herd-equivalence gates. - Query-shape pack: share download double-fetch 2→1 (2.18x), contact-group COUNT(*) 14.9x, save_faces UNNEST 3.9x, playlist reorder UNNEST 63.7x (now atomic), search files∥folders join! 1.45x, move drive-lookup join! 2.14x, trash partial (drive_id, trashed_at) indexes, CalDAV event-gate narrow read, favorites/recents binary-decode port, dead count_files removed. - NC surface: preview + avatar honour If-None-Match (e2e: 5 KB and 197 KB → 0 bytes per revalidation), avatar WebP→PNG transcode memoised, PROPFIND/trashbin integer+date emits on stack formatters, folder-header enrichment join!, chunk-PUT retry stat folded into create_new open. - common::fmt integer rendering rewritten on the std 2-digit LUT after the round's own bench caught the div-loop losing to to_string (16.1 ns vs 22.5; speeds every prior-round call site). - Micro-pack: WebDAV scope probe borrow-only, ShareService base_url snapshot, cookie_secure OnceLock, Arc'd AES-GCM cipher, stack request-id, tantivy analyzer clone dropped. - SPA: search stale-guard + AbortController (10→1 completed round-trips, stale-clobber gone), getFolder in-flight dedup, gridColumns matchMedia hoist (10k→0 style reads). Backend: cargo fmt + clippy -D warnings clean, 524 tests green. Frontend: npm run check clean, 301 vitest green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018DdM7V7M3QPW7HEHg3gLov
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
//! for audit / ownership purposes.
|
||||
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use smol_str::SmolStr;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::application::ports::auth_ports::TokenServicePort;
|
||||
@@ -26,7 +27,7 @@ use crate::interfaces::middleware::user::{LiveRole, resolve_live_role};
|
||||
pub async fn require_admin(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<(Uuid, String), AppError> {
|
||||
) -> Result<(Uuid, SmolStr), AppError> {
|
||||
let auth = state
|
||||
.auth_service
|
||||
.as_ref()
|
||||
@@ -85,7 +86,7 @@ pub async fn require_admin(
|
||||
pub async fn require_authenticated(
|
||||
state: &AppState,
|
||||
headers: &HeaderMap,
|
||||
) -> Result<(Uuid, String), AppError> {
|
||||
) -> Result<(Uuid, SmolStr), AppError> {
|
||||
let auth = state
|
||||
.auth_service
|
||||
.as_ref()
|
||||
|
||||
@@ -204,10 +204,14 @@ pub async fn auth_middleware(
|
||||
LiveRole::Active(role) => role,
|
||||
LiveRole::Revoked => return Err(AuthError::AccountInactive),
|
||||
};
|
||||
// `username`/`email` are `Arc<str>` refcount
|
||||
// bumps out of the cached claims; `role` is an
|
||||
// inline SmolStr — the whole build is 1 alloc
|
||||
// (the `Arc::new`) instead of 4.
|
||||
let current_user = Arc::new(CurrentUser {
|
||||
id: user_id,
|
||||
username: claims.username.clone(),
|
||||
email: claims.email.clone(),
|
||||
username: Arc::clone(&claims.username),
|
||||
email: Arc::clone(&claims.email),
|
||||
role,
|
||||
});
|
||||
request.extensions_mut().insert(current_user);
|
||||
@@ -319,8 +323,8 @@ pub async fn auth_middleware(
|
||||
LiveRole::Active(role) => {
|
||||
let current_user = Arc::new(CurrentUser {
|
||||
id: user_id,
|
||||
username: claims.username.clone(),
|
||||
email: claims.email.clone(),
|
||||
username: Arc::clone(&claims.username),
|
||||
email: Arc::clone(&claims.email),
|
||||
role,
|
||||
});
|
||||
request.extensions_mut().insert(current_user);
|
||||
|
||||
@@ -69,8 +69,11 @@ pub struct UuidRequestId;
|
||||
|
||||
impl MakeRequestId for UuidRequestId {
|
||||
fn make_request_id<B>(&mut self, _request: &axum::http::Request<B>) -> Option<RequestId> {
|
||||
let id = Uuid::now_v7().to_string();
|
||||
axum::http::HeaderValue::from_str(&id)
|
||||
// Stack-encode the UUID: `to_string()` allocated an intermediate
|
||||
// String per request just for HeaderValue to copy it again.
|
||||
let mut buf = [0u8; uuid::fmt::Hyphenated::LENGTH];
|
||||
let id = Uuid::now_v7();
|
||||
axum::http::HeaderValue::from_str(id.hyphenated().encode_lower(&mut buf))
|
||||
.ok()
|
||||
.map(RequestId::new)
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ use axum::extract::{Request, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use smol_str::SmolStr;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -109,8 +110,9 @@ pub async fn require_admin_user(
|
||||
pub enum LiveRole {
|
||||
/// The account exists and is active. Carries the caller's *current*
|
||||
/// role string (`"admin"` / `"user"`), which is authoritative and
|
||||
/// supersedes the — possibly stale — JWT `role` claim.
|
||||
Active(String),
|
||||
/// supersedes the — possibly stale — JWT `role` claim. `SmolStr` so the
|
||||
/// per-request render of the (≤23-byte) role never heap-allocates.
|
||||
Active(SmolStr),
|
||||
/// The account is deactivated or deleted: the request must be rejected
|
||||
/// even though its token is still cryptographically valid.
|
||||
Revoked,
|
||||
@@ -152,7 +154,7 @@ fn decide_live_role(
|
||||
claim_role: &str,
|
||||
) -> LiveRole {
|
||||
match flags {
|
||||
Ok(flags) if flags.active => LiveRole::Active(flags.role.to_string()),
|
||||
Ok(flags) if flags.active => LiveRole::Active(SmolStr::new_static(flags.role.as_str())),
|
||||
Ok(_) => {
|
||||
audit_token_revoked(user_id, "deactivated");
|
||||
LiveRole::Revoked
|
||||
@@ -170,7 +172,7 @@ fn decide_live_role(
|
||||
error = %e,
|
||||
"live-user re-check failed transiently; allowing request on the JWT claim role (fail-open)"
|
||||
);
|
||||
LiveRole::Active(claim_role.to_string())
|
||||
LiveRole::Active(SmolStr::new(claim_role))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,14 +259,14 @@ mod tests {
|
||||
let live = decide_live_role(Ok(flags(UserRole::Admin, true)), Uuid::nil(), "user");
|
||||
// The live record wins over the (stale) claim — a freshly promoted
|
||||
// user is admin even though their token still says "user".
|
||||
assert_eq!(live, LiveRole::Active("admin".to_string()));
|
||||
assert_eq!(live, LiveRole::Active(SmolStr::new_static("admin")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_user_yields_current_user_role() {
|
||||
// A demoted admin: token claim still "admin", live record "user".
|
||||
let live = decide_live_role(Ok(flags(UserRole::User, true)), Uuid::nil(), "admin");
|
||||
assert_eq!(live, LiveRole::Active("user".to_string()));
|
||||
assert_eq!(live, LiveRole::Active(SmolStr::new_static("user")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -285,6 +287,6 @@ mod tests {
|
||||
// A DB blip must not lock everyone out: allow on the claim role.
|
||||
let err = DomainError::new(ErrorKind::InternalError, "User", "connection reset");
|
||||
let live = decide_live_role(Err(err), Uuid::nil(), "admin");
|
||||
assert_eq!(live, LiveRole::Active("admin".to_string()));
|
||||
assert_eq!(live, LiveRole::Active(SmolStr::new_static("admin")));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user