From 141b732894e8d04dba821fb12db54ea5ba273909 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Tue, 21 Jul 2026 15:12:10 -0500 Subject: [PATCH] perf(media): persist cache entries off the load path --- src/app/utils/mediaCache.ts | 74 ++++++++++++++++++++++++---- src/app/utils/mediaTransport.test.ts | 14 ++++++ src/app/utils/mediaTransport.ts | 3 +- 3 files changed, 81 insertions(+), 10 deletions(-) diff --git a/src/app/utils/mediaCache.ts b/src/app/utils/mediaCache.ts index c95a67b64..ff702d612 100644 --- a/src/app/utils/mediaCache.ts +++ b/src/app/utils/mediaCache.ts @@ -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(); +let writesSinceEviction = 0; +let evictionScheduled = false; +let legacyCachesCleaned = false; export async function clearMediaCache(): Promise { + 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 { async function openCache(): Promise { 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 { + 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 async function evictIfNeeded(cache: Cache): Promise { 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[] = []; + + // 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 { + 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); } } diff --git a/src/app/utils/mediaTransport.test.ts b/src/app/utils/mediaTransport.test.ts index 7afc7f129..95cd1e140 100644 --- a/src/app/utils/mediaTransport.test.ts +++ b/src/app/utils/mediaTransport.test.ts @@ -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()); }); @@ -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'; diff --git a/src/app/utils/mediaTransport.ts b/src/app/utils/mediaTransport.ts index e694fff6b..d253c7598 100644 --- a/src/app/utils/mediaTransport.ts +++ b/src/app/utils/mediaTransport.ts @@ -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; };