diff --git a/packages/void/src/runtime/routing/assets.ts b/packages/void/src/runtime/routing/assets.ts index b84c7cdff..c7bd3d9c7 100644 --- a/packages/void/src/runtime/routing/assets.ts +++ b/packages/void/src/runtime/routing/assets.ts @@ -54,7 +54,6 @@ export type ManifestLoader = ( ) => Promise; export function createManifestLoader(): ManifestLoader { let cached: ClientManifest | null = null; - let pending: Promise | null = null; return async (request, env) => { if (cached) { return cached; @@ -69,21 +68,17 @@ export function createManifestLoader(): ManifestLoader { if (!assets || typeof assets.fetch !== 'function') { return null; } - // Concurrent cold requests share one fetch and parse. A missing or failed - // manifest is not cached, so a later request retries. - pending ??= (async () => { - const response = await assets.fetch( - new Request(new URL('/.vite/manifest.json', request.url).toString()), - ); - if (!response.ok) { - return null; - } - cached = (await response.json()) as ClientManifest; - return cached; - })().finally(() => { - pending = null; - }); - return pending; + // Workers scope I/O to the request that starts it: if this fetch is shared, a + // canceled request can leave the promise unsettled and every later request waits + // on it. Cache the parsed manifest only. A failed load retries on the next request. + const response = await assets.fetch( + new Request(new URL('/.vite/manifest.json', request.url).toString()), + ); + if (!response.ok) { + return null; + } + cached = (await response.json()) as ClientManifest; + return cached; }; } export type ClientAssetOptions = { diff --git a/packages/void/src/runtime/routing/worker.ts b/packages/void/src/runtime/routing/worker.ts index 35763f5ac..e7b7155ed 100644 --- a/packages/void/src/runtime/routing/worker.ts +++ b/packages/void/src/runtime/routing/worker.ts @@ -76,7 +76,7 @@ export function createAssetCachePolicy( assetsDir?: string, loadManifest: ManifestLoader = createManifestLoader(), ): (request: Request, env: RuntimeEnvironment, asset: Response) => Promise { - let files: Promise> | undefined; + let files: Set | undefined; return async (request, env, asset) => { const path = new URL(request.url).pathname; if ( @@ -87,18 +87,18 @@ export function createAssetCachePolicy( return applyAssetCachePolicy(request, asset, assetsDir); } if (!files) { - // Optional cache metadata must not make a successfully served asset fail. - files = loadManifest(request, env).then( - (manifest) => - new Set( - Object.values(manifest ?? {}).flatMap((entry) => - Array.isArray(entry?.immutableFiles) ? entry.immutableFiles : [], - ), + // Keep the lookup scoped to this request. A miss uses the conservative policy + // until a request successfully loads the manifest. + const manifest = await loadManifest(request, env).catch(() => null); + if (manifest) { + files ??= new Set( + Object.values(manifest).flatMap((entry) => + Array.isArray(entry?.immutableFiles) ? entry.immutableFiles : [], ), - () => new Set(), - ); + ); + } } - return applyAssetCachePolicy(request, asset, assetsDir, (await files).has(path.slice(1))); + return applyAssetCachePolicy(request, asset, assetsDir, files?.has(path.slice(1))); }; } diff --git a/packages/void/test/unit/routing-runtime.test.ts b/packages/void/test/unit/routing-runtime.test.ts index 080d97ff3..80f1a2d54 100644 --- a/packages/void/test/unit/routing-runtime.test.ts +++ b/packages/void/test/unit/routing-runtime.test.ts @@ -15,7 +15,12 @@ import { defineMiddleware, type CloudContext, } from '../../src/runtime/handler/index.ts'; -import { createClientAssetTags, createManifestLoader } from '../../src/runtime/routing/assets.ts'; +import { + createClientAssetTags, + createManifestLoader, + type ClientManifest, + type ManifestLoader, +} from '../../src/runtime/routing/assets.ts'; import { createErrorRenderer } from '../../src/runtime/routing/errors.ts'; import { createHttpRouteHandler, @@ -786,7 +791,7 @@ describe('typed asset fallthrough', () => { applyAssetCachePolicy(request, cookie, 'static', true).headers.get('cache-control'), ).toBe('no-store'); }); - it.each([null, { client: { file: 'assets/client-abcdefgh.js' } }])( + it.each([{}, { client: { file: 'assets/client-abcdefgh.js' } }])( 'uses conservative cache policy without build provenance: %j', async (manifest) => { const load = vi.fn(async () => manifest); @@ -807,18 +812,100 @@ describe('typed asset fallthrough', () => { expect(load).toHaveBeenCalledTimes(1); }, ); - it('keeps assets available when optional manifest lookup fails', async () => { - const policy = createAssetCachePolicy('assets', async () => { - throw new Error('unavailable'); - }); - const response = await policy( - new Request('https://app.test/assets/app-settings.json'), + it.each(['missing', 'rejected'])( + 'serves assets and retries after a %s manifest lookup', + async (failure) => { + const path = 'assets/client-abcdefgh.js'; + const load = vi + .fn() + .mockImplementationOnce(async () => { + if (failure === 'rejected') { + throw new Error('unavailable'); + } + return null; + }) + .mockResolvedValue({ client: { file: path, immutableFiles: [path] } }); + const policy = createAssetCachePolicy('assets', load); + const request = () => new Request(`https://app.test/${path}`); + const response = await policy(request(), {}, new Response('asset')); + expect(response.headers.get('cache-control')).toBe('no-store'); + await expect(response.text()).resolves.toBe('asset'); + const recovered = await policy(request(), {}, new Response('asset')); + expect(recovered.headers.get('cache-control')).toBe('public, max-age=31536000, immutable'); + await policy(request(), {}, new Response('asset')); + expect(load).toHaveBeenCalledTimes(2); + }, + ); + it('keeps a stalled manifest lookup from blocking later asset requests', async () => { + const load = vi + .fn() + .mockImplementationOnce(() => new Promise(() => {})) + .mockImplementation(async () => ({ + client: { + file: 'assets/client-abcdefgh.js', + immutableFiles: ['assets/client-abcdefgh.js'], + }, + })); + const policy = createAssetCachePolicy('assets', load); + // The first request's lookup never settles, as a canceled request's fetch may not. + void policy( + new Request('https://app.test/assets/stalled-11111111.js'), {}, new Response('asset'), ); - expect(response.headers.get('cache-control')).toBe('no-store'); - await expect(response.text()).resolves.toBe('asset'); - }); + const response = await policy( + new Request('https://app.test/assets/client-abcdefgh.js'), + {}, + new Response('asset', { + headers: { 'cache-control': 'public, max-age=0, must-revalidate' }, + }), + ); + expect(response.headers.get('cache-control')).toBe('public, max-age=31536000, immutable'); + expect(load).toHaveBeenCalledTimes(2); + }); + it.each(['success', 'miss'])( + 'caches the successful manifest when %s resolves first', + async (first) => { + let resolveHit!: (manifest: ClientManifest | null) => void; + let resolveMiss!: (manifest: ClientManifest | null) => void; + const hit = new Promise((resolve) => (resolveHit = resolve)); + const miss = new Promise((resolve) => (resolveMiss = resolve)); + const load = vi.fn((request) => + new URL(request.url).pathname.includes('/hit-') ? hit : miss, + ); + const policy = createAssetCachePolicy('assets', load); + const asset = () => + new Response('asset', { + headers: { 'cache-control': 'public, max-age=0, must-revalidate' }, + }); + const ranHit = policy(new Request('https://app.test/assets/hit-11111111.js'), {}, asset()); + const ranMiss = policy(new Request('https://app.test/assets/miss-22222222.js'), {}, asset()); + const finishHit = () => + resolveHit({ + client: { + file: 'assets/client-abcdefgh.js', + immutableFiles: ['assets/client-abcdefgh.js'], + }, + }); + if (first === 'success') { + finishHit(); + await ranHit; + resolveMiss(null); + } else { + resolveMiss(null); + await ranMiss; + finishHit(); + } + await Promise.all([ranHit, ranMiss]); + const response = await policy( + new Request('https://app.test/assets/client-abcdefgh.js'), + {}, + asset(), + ); + expect(response.headers.get('cache-control')).toBe('public, max-age=31536000, immutable'); + expect(load).toHaveBeenCalledTimes(2); + }, + ); it('preserves non-success, redirects and mutation responses', () => { for (const source of [ new Response('missing', { status: 404 }), @@ -1589,16 +1676,27 @@ describe('typed client asset tags', () => { expect(binding).toHaveBeenCalledTimes(1); }); - it('shares one manifest fetch between concurrent cold loads', async () => { + it('keeps a stalled manifest fetch from blocking later requests', async () => { + const binding = vi + .fn<() => Promise>() + .mockImplementationOnce(() => new Promise(() => {})) + .mockImplementation(async () => Response.json({ page: { file: 'page.js' } })); + const loader = createManifestLoader(); + const env = { ASSETS: { fetch: binding } }; + // The first request's fetch never settles, as a canceled request's fetch may not. + void loader(new Request('https://app.test/first'), env); + await expect(loader(new Request('https://app.test/second'), env)).resolves.toEqual({ + page: { file: 'page.js' }, + }); + expect(binding).toHaveBeenCalledTimes(2); + }); + + it('caches the parsed manifest instead of the fetch', async () => { const binding = vi.fn(async () => Response.json({ page: { file: 'page.js' } })); const loader = createManifestLoader(); const env = { ASSETS: { fetch: binding } }; - const request = new Request('https://app.test/page'); - const manifests = await Promise.all(Array.from({ length: 8 }, () => loader(request, env))); - expect(binding).toHaveBeenCalledTimes(1); - expect(new Set(manifests).size).toBe(1); - expect(manifests[0]).toEqual({ page: { file: 'page.js' } }); - expect(await loader(request, env)).toBe(manifests[0]); + const first = await loader(new Request('https://app.test/page'), env); + await expect(loader(new Request('https://app.test/other'), env)).resolves.toBe(first); expect(binding).toHaveBeenCalledTimes(1); }); @@ -1614,9 +1712,7 @@ describe('typed client asset tags', () => { const request = new Request('https://app.test/page'); expect(await loader(request, env)).toBeNull(); expect(binding).toHaveBeenCalledTimes(1); - const rejected = [loader(request, env), loader(request, env)]; - await expect(rejected[0]).rejects.toThrow('assets unavailable'); - await expect(rejected[1]).rejects.toThrow('assets unavailable'); + await expect(loader(request, env)).rejects.toThrow('assets unavailable'); expect(binding).toHaveBeenCalledTimes(2); expect(await loader(request, env)).toEqual(manifest); expect(binding).toHaveBeenCalledTimes(3);