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:
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('$lib/api/client', () => ({ apiFetch: vi.fn(), apiJson: vi.fn() }));
|
||||
|
||||
import { apiJson } from '$lib/api/client';
|
||||
import type { FolderItem } from '$lib/api/types';
|
||||
import { getFolder } from './folders';
|
||||
|
||||
/**
|
||||
* Benchmark gate for the in-flight dedup in {@link getFolder}.
|
||||
*
|
||||
* Audit finding: on a cold deep-link the breadcrumb builder and the files
|
||||
* view's drive-id resolver both call `getFolder(currentFolderId)` in the same
|
||||
* frame — two identical concurrent `GET /api/folders/{id}` round-trips per
|
||||
* navigation. The fix keeps a `Map<id, Promise>` of in-flight requests (the
|
||||
* `resolveUser` pattern) so concurrent duplicates share one fetch, while
|
||||
* SEQUENTIAL calls still hit the network every time (freshness unchanged).
|
||||
*
|
||||
* Gates:
|
||||
* 1. Two concurrent calls for the same id → exactly ONE network call, both
|
||||
* callers get the same result.
|
||||
* 2. Sequential calls (second after the first settled) → two network calls
|
||||
* (no staleness introduced).
|
||||
* 3. Distinct ids in flight do not cross-talk.
|
||||
*/
|
||||
|
||||
const mockedApiJson = vi.mocked(apiJson);
|
||||
|
||||
function folder(id: string): FolderItem {
|
||||
return { id, name: `Folder ${id}` } as unknown as FolderItem;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockedApiJson.mockReset();
|
||||
});
|
||||
|
||||
describe('getFolder in-flight dedup (benchmark gate)', () => {
|
||||
it('concurrent duplicate calls collapse to one request', async () => {
|
||||
let release!: (v: FolderItem) => void;
|
||||
mockedApiJson.mockImplementation(
|
||||
() => new Promise<FolderItem>((r) => (release = r)) as Promise<never>
|
||||
);
|
||||
|
||||
const a = getFolder('f1');
|
||||
const b = getFolder('f1');
|
||||
expect(mockedApiJson).toHaveBeenCalledTimes(1); // the dedup win
|
||||
|
||||
release(folder('f1'));
|
||||
const [ra, rb] = await Promise.all([a, b]);
|
||||
expect(ra).toEqual(rb);
|
||||
expect(ra.id).toBe('f1');
|
||||
console.log(
|
||||
`[bench] cold deep-link double-fetch: requests BEFORE=2 AFTER=${mockedApiJson.mock.calls.length}`
|
||||
);
|
||||
});
|
||||
|
||||
it('sequential calls still refetch (freshness preserved)', async () => {
|
||||
mockedApiJson.mockResolvedValue(folder('f2') as never);
|
||||
await getFolder('f2');
|
||||
await getFolder('f2');
|
||||
expect(mockedApiJson).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('distinct ids resolve independently', async () => {
|
||||
mockedApiJson.mockImplementation(((url: string) => {
|
||||
const id = String(url).split('/').pop() ?? '';
|
||||
return Promise.resolve(folder(id));
|
||||
}) as never);
|
||||
const [x, y] = await Promise.all([getFolder('fx'), getFolder('fy')]);
|
||||
expect(x.id).toBe('fx');
|
||||
expect(y.id).toBe('fy');
|
||||
expect(mockedApiJson).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('a failed in-flight request clears the slot so a retry refetches', async () => {
|
||||
mockedApiJson.mockRejectedValueOnce(new Error('boom') as never);
|
||||
await expect(getFolder('f3')).rejects.toThrow('boom');
|
||||
mockedApiJson.mockResolvedValue(folder('f3') as never);
|
||||
await expect(getFolder('f3')).resolves.toMatchObject({ id: 'f3' });
|
||||
});
|
||||
});
|
||||
@@ -88,10 +88,26 @@ export function getFolderName(id: string): string | undefined {
|
||||
return folderNames.get(id);
|
||||
}
|
||||
|
||||
export async function getFolder(id: string): Promise<FolderItem> {
|
||||
const folder = await apiJson<FolderItem>(`/api/folders/${id}`, NO_CACHE);
|
||||
rememberFolderName(folder.id, folder.name);
|
||||
return folder;
|
||||
// In-flight dedup (the `resolveUser` pattern): on a cold deep-link the
|
||||
// breadcrumb builder and the drive-id resolver both request the same folder
|
||||
// concurrently — collapse duplicates into one GET. Entries only live while
|
||||
// the request is in flight, so freshness semantics are unchanged.
|
||||
const folderInflight = new Map<string, Promise<FolderItem>>();
|
||||
|
||||
export function getFolder(id: string): Promise<FolderItem> {
|
||||
const inflight = folderInflight.get(id);
|
||||
if (inflight) return inflight;
|
||||
const request = (async () => {
|
||||
try {
|
||||
const folder = await apiJson<FolderItem>(`/api/folders/${id}`, NO_CACHE);
|
||||
rememberFolderName(folder.id, folder.name);
|
||||
return folder;
|
||||
} finally {
|
||||
folderInflight.delete(id);
|
||||
}
|
||||
})();
|
||||
folderInflight.set(id, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface SearchOptions {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
sortBy?: SortBy;
|
||||
/** Abort the request when a newer search supersedes it. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export function searchFiles(query: string, opts: SearchOptions = {}): Promise<SearchResults> {
|
||||
@@ -38,7 +40,10 @@ export function searchFiles(query: string, opts: SearchOptions = {}): Promise<Se
|
||||
params.append('limit', String(opts.limit ?? 100));
|
||||
params.append('offset', String(opts.offset ?? 0));
|
||||
params.append('sort_by', opts.sortBy ?? 'relevance');
|
||||
return apiJson<SearchResults>(`/api/search?${params.toString()}`, { credentials: 'same-origin' });
|
||||
return apiJson<SearchResults>(`/api/search?${params.toString()}`, {
|
||||
credentials: 'same-origin',
|
||||
signal: opts.signal
|
||||
});
|
||||
}
|
||||
|
||||
/** A single autocomplete suggestion returned by the lightweight suggest endpoint. */
|
||||
@@ -50,6 +55,8 @@ export interface SearchSuggestions {
|
||||
export interface SuggestOptions {
|
||||
folderId?: string;
|
||||
limit?: number;
|
||||
/** Abort the request when a newer keystroke supersedes it. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -65,7 +72,8 @@ export function searchSuggest(
|
||||
if (opts.folderId) params.append('folder_id', opts.folderId);
|
||||
if (opts.limit != null) params.append('limit', String(opts.limit));
|
||||
return apiJson<SearchSuggestions>(`/api/search/suggest?${params.toString()}`, {
|
||||
credentials: 'same-origin'
|
||||
credentials: 'same-origin',
|
||||
signal: opts.signal
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user