perf(media): persist cache entries off the load path

This commit is contained in:
7w1 committed 2026-07-21 15:18:24 -05:00
1 parent e3f1422c3f
commit 141b732894
3 files changed
+81 -10

No files matched your search

+65 -9
View File
@@ -1,10 +1,20 @@
const CACHE_NAME = 'sable-media-v1';
const CACHE_NAME = 'sable-media-v2';
const LEGACY_CACHE_NAMES = ['sable-media-v1'];
const MAX_ENTRIES = 500;
const MAX_CACHE_BYTES = 256 * 1024 * 1024;
const EVICT_EVERY_WRITES = 25;
const pendingBlobs = new Map<string, Blob>();
let writesSinceEviction = 0;
let evictionScheduled = false;
let legacyCachesCleaned = false;
export async function clearMediaCache(): Promise<void> {
pendingBlobs.clear();
writesSinceEviction = 0;
if (typeof caches === 'undefined') return;
try {
await caches.delete(CACHE_NAME);
await Promise.all([CACHE_NAME, ...LEGACY_CACHE_NAMES].map((name) => caches.delete(name)));
} catch {
// ignore
}
@@ -13,6 +23,12 @@ export async function clearMediaCache(): Promise<void> {
async function openCache(): Promise<Cache | undefined> {
if (typeof caches === 'undefined') return undefined;
try {
if (!legacyCachesCleaned) {
legacyCachesCleaned = true;
void Promise.all(LEGACY_CACHE_NAMES.map((name) => caches.delete(name))).catch(
() => undefined
);
}
return await caches.open(CACHE_NAME);
} catch {
return undefined;
@@ -33,6 +49,9 @@ function getCacheRequest(url: string): Request {
}
export async function getFromMediaCache(url: string): Promise<Blob | undefined> {
const pendingBlob = pendingBlobs.get(url);
if (pendingBlob) return pendingBlob;
const cache = await openCache();
if (!cache) return undefined;
try {
@@ -47,31 +66,68 @@ export async function getFromMediaCache(url: string): Promise<Blob | undefined>
async function evictIfNeeded(cache: Cache): Promise<void> {
try {
const keys = await cache.keys();
const overflow = keys.length - MAX_ENTRIES;
if (overflow <= 0) return;
// Delete oldest entries (keys() returns insertion order).
await Promise.all(keys.slice(0, overflow).map((req) => cache.delete(req)));
const responses = await Promise.all(keys.map((request) => cache.match(request)));
const sizes = responses.map((response) => {
const value = Number(response?.headers.get('Content-Length'));
return Number.isFinite(value) && value > 0 ? value : 0;
});
let totalBytes = sizes.reduce((total, size) => total + size, 0);
let remainingEntries = keys.length;
const deletions: Promise<boolean>[] = [];
// keys() is insertion ordered, so remove the oldest entries until both budgets fit.
for (let index = 0; index < keys.length; index += 1) {
if (remainingEntries <= MAX_ENTRIES && totalBytes <= MAX_CACHE_BYTES) break;
const request = keys[index];
if (!request) continue;
deletions.push(cache.delete(request));
remainingEntries -= 1;
totalBytes -= sizes[index] ?? 0;
}
await Promise.all(deletions);
} catch {
// Best-effort eviction.
}
}
function scheduleEviction(cache: Cache, force = false): void {
writesSinceEviction += 1;
if ((!force && writesSinceEviction < EVICT_EVERY_WRITES) || evictionScheduled) return;
writesSinceEviction = 0;
evictionScheduled = true;
globalThis.setTimeout(() => {
void evictIfNeeded(cache).finally(() => {
evictionScheduled = false;
});
}, 0);
}
// Cache contract:
// - keyed by the final media URL
// - stores successful responses only
// - persists blobs, never error responses or intermediate auth state
export async function putInMediaCache(url: string, blob: Blob): Promise<void> {
pendingBlobs.set(url, blob);
const cache = await openCache();
if (!cache) return;
if (!cache) {
pendingBlobs.delete(url);
return;
}
try {
await cache.put(
getCacheRequest(url),
new Response(blob, {
headers: { 'Content-Type': blob.type || 'application/octet-stream' },
headers: {
'Content-Type': blob.type || 'application/octet-stream',
'Content-Length': String(blob.size),
},
})
);
await evictIfNeeded(cache);
scheduleEviction(cache, blob.size > MAX_CACHE_BYTES);
} catch {
// Storage full or unavailable — silently degrade to in-memory only.
} finally {
if (pendingBlobs.get(url) === blob) pendingBlobs.delete(url);
}
}
+14
View File
@@ -40,6 +40,9 @@ describe('fetchMediaBlob', () => {
mediaCache.cache.clear();
mediaCache.getFromMediaCache.mockClear();
mediaCache.putInMediaCache.mockClear();
mediaCache.putInMediaCache.mockImplementation(async (url: string, blob: Blob) => {
mediaCache.cache.set(url, blob);
});
localStorage.clear();
vi.stubGlobal('fetch', vi.fn<typeof globalThis.fetch>());
});
@@ -202,6 +205,17 @@ describe('fetchMediaBlob', () => {
expect(mediaCache.putInMediaCache).toHaveBeenCalledWith(scopedUrl, freshBlob);
});
it('does not wait for persistent cache writes before returning media', async () => {
const { fetchMediaBlob } = await import('./mediaTransport');
const url = 'https://example.org/media.png';
const freshBlob = new Blob(['fresh'], { type: 'image/png' });
vi.mocked(fetch).mockResolvedValueOnce(new Response(freshBlob, { status: 200 }));
mediaCache.putInMediaCache.mockReturnValueOnce(new Promise(() => {}));
await expect(fetchMediaBlob(url)).resolves.toEqual(freshBlob);
expect(mediaCache.putInMediaCache).toHaveBeenCalledOnce();
});
it('skips cache reads and writes for bypass requests', async () => {
const { fetchMediaBlob } = await import('./mediaTransport');
const url = 'https://example.org/media.png';
+2 -1
View File
@@ -289,7 +289,8 @@ async function fetchMediaBlobInternal(url: string, options?: MediaTransportOptio
const blob = await response.blob();
if (cacheMode !== 'bypass') {
await putInMediaCache(scopedCacheKey, blob);
// Persistence is best-effort and must not delay first paint/playback.
void putInMediaCache(scopedCacheKey, blob).catch(() => undefined);
}
return blob;
};