diff --git a/src/app/components/media/Image.test.tsx b/src/app/components/media/Image.test.tsx index d3dd236d7..50f8c0ef7 100644 --- a/src/app/components/media/Image.test.tsx +++ b/src/app/components/media/Image.test.tsx @@ -107,6 +107,80 @@ describe('Image', () => { fetchSpy.mockRestore(); }); + it('forwards one error for an undeclared broken non-lottie image', async () => { + const onError = vi.fn<(event: React.SyntheticEvent) => void>(); + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response('not a gzip file')); + render( + undeclared broken image + ); + + const image = screen.getByAltText('undeclared broken image'); + fireEvent.error(image); + expect(image).not.toHaveAttribute('src'); + expect(onError).not.toHaveBeenCalled(); + + await waitFor(() => + expect(image).toHaveAttribute('src', 'https://example.com/undeclared-broken-media') + ); + fireEvent.error(image); + + expect(onError).toHaveBeenCalledOnce(); + expect(fetchSpy).toHaveBeenCalledOnce(); + fetchSpy.mockRestore(); + }); + + it('shares lottie resolution work for repeated media', async () => { + const bytes = Uint8Array.from(gzipSync(lottieJson)); + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValue(new Response(bytes, { headers: { 'content-length': `${bytes.length}` } })); + render( + <> + + + + ); + + await waitFor(() => { + expect(screen.getAllByLabelText('repeated lottie')).toHaveLength(2); + expect( + screen.getAllByLabelText('repeated lottie').every((item) => item.tagName === 'CANVAS') + ).toBe(true); + }); + expect(fetchSpy).toHaveBeenCalledOnce(); + fetchSpy.mockRestore(); + }); + + it('retries lottie resolution after a transient failure', async () => { + const bytes = Uint8Array.from(gzipSync(lottieJson)); + const fetchSpy = vi + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(new Response('temporary failure')) + .mockResolvedValueOnce( + new Response(bytes, { headers: { 'content-length': `${bytes.length}` } }) + ); + const source = 'https://example.com/transient-sticker.tgs'; + const firstRender = render(); + + await waitFor(() => expect(screen.getByLabelText('transient lottie')).toHaveAttribute('src')); + expect(screen.getByLabelText('transient lottie').tagName).toBe('IMG'); + firstRender.unmount(); + + render(); + await waitFor(() => { + expect(screen.getByLabelText('transient lottie').tagName).toBe('CANVAS'); + }); + + expect(fetchSpy).toHaveBeenCalledTimes(2); + fetchSpy.mockRestore(); + }); + it('aborts an in-flight lottie download when unmounted', async () => { let requestSignal: AbortSignal | undefined; const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((_input, init) => { diff --git a/src/app/components/media/Image.tsx b/src/app/components/media/Image.tsx index 059f8dd5f..8a864c18b 100644 --- a/src/app/components/media/Image.tsx +++ b/src/app/components/media/Image.tsx @@ -37,6 +37,9 @@ const MAX_DECOMPRESSED_LOTTIE_BYTES = 8 * 1024 * 1024; const MAX_LOTTIE_DIMENSION = 4096; const MAX_LOTTIE_FRAMES = 10_000; const MAX_LOTTIE_LAYERS = 1_000; +const LOTTIE_PROBE_TIMEOUT_MS = 5_000; +const MAX_LOTTIE_CACHE_ENTRIES = 32; +const MAX_CACHED_LOTTIE_DATA_URL_LENGTH = 2 * 1024 * 1024; const UNSAFE_LOTTIE_KEYS = new Set([ 'expression', 'expressions', @@ -182,6 +185,107 @@ async function resolveLottieDataUrl(src: string, signal: AbortSignal): Promise; +}; + +const lottieResolutionCache = new Map(); + +function trimLottieResolutionCache(): void { + let scanned = 0; + + while ( + lottieResolutionCache.size > MAX_LOTTIE_CACHE_ENTRIES && + scanned < lottieResolutionCache.size + ) { + const oldest = lottieResolutionCache.entries().next().value as + | [string, LottieResolutionEntry] + | undefined; + if (!oldest) return; + const [source, entry] = oldest; + + if (entry.settled && entry.consumers === 0) { + lottieResolutionCache.delete(source); + scanned = 0; + continue; + } + + lottieResolutionCache.delete(source); + lottieResolutionCache.set(source, entry); + scanned += 1; + } +} + +function createLottieResolutionEntry(src: string): LottieResolutionEntry { + const controller = new AbortController(); + const entry = { + controller, + consumers: 0, + settled: false, + } as LottieResolutionEntry; + const timeout = window.setTimeout(() => controller.abort(), LOTTIE_PROBE_TIMEOUT_MS); + + entry.promise = resolveLottieDataUrl(src, controller.signal).then((result) => { + entry.settled = true; + window.clearTimeout(timeout); + if ( + controller.signal.aborted || + result === null || + result.length > MAX_CACHED_LOTTIE_DATA_URL_LENGTH + ) { + if (lottieResolutionCache.get(src) === entry) lottieResolutionCache.delete(src); + } else { + trimLottieResolutionCache(); + } + return result; + }); + lottieResolutionCache.set(src, entry); + return entry; +} + +function resolveCachedLottieDataUrl(src: string, signal: AbortSignal): Promise { + let entry = lottieResolutionCache.get(src); + if (!entry) { + entry = createLottieResolutionEntry(src); + } else { + lottieResolutionCache.delete(src); + lottieResolutionCache.set(src, entry); + } + entry.consumers += 1; + + return new Promise((resolve) => { + let released = false; + const release = () => { + if (released) return; + released = true; + signal.removeEventListener('abort', handleAbort); + entry.consumers -= 1; + if (entry.consumers === 0) { + if (!entry.settled) { + entry.controller.abort(); + if (lottieResolutionCache.get(src) === entry) lottieResolutionCache.delete(src); + } else { + trimLottieResolutionCache(); + } + } + }; + const handleAbort = () => { + release(); + resolve(null); + }; + + signal.addEventListener('abort', handleAbort, { once: true }); + entry.promise.then((result) => { + release(); + resolve(result); + }); + if (signal.aborted) handleAbort(); + }); +} + type LottieImageProps = LottieDotProps & { src: string; alt?: string; @@ -327,7 +431,7 @@ export const Image = forwardRef { + void resolveCachedLottieDataUrl(src, controller.signal).then((result) => { if (!controller.signal.aborted) { setLottieResolution({ source: src, resolved: result }); }