Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 11 additions & 16 deletions packages/void/src/runtime/routing/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export type ManifestLoader = (
) => Promise<ClientManifest | null>;
export function createManifestLoader(): ManifestLoader {
let cached: ClientManifest | null = null;
let pending: Promise<ClientManifest | null> | null = null;
return async (request, env) => {
if (cached) {
return cached;
Expand All @@ -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 = {
Expand Down
21 changes: 10 additions & 11 deletions packages/void/src/runtime/routing/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function createAssetCachePolicy(
assetsDir?: string,
loadManifest: ManifestLoader = createManifestLoader(),
): (request: Request, env: RuntimeEnvironment, asset: Response) => Promise<Response> {
let files: Promise<Set<string>> | undefined;
let files: Set<string> | undefined;
return async (request, env, asset) => {
const path = new URL(request.url).pathname;
if (
Expand All @@ -87,18 +87,17 @@ 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 : [],
),
),
() => new Set(),
// A failed lookup must not break a served asset. The in-flight request is not
// held here: if it never settles it would stall every later asset request in
// this isolate.
const manifest = await loadManifest(request, env).catch(() => null);
files = new Set(
Object.values(manifest ?? {}).flatMap((entry) =>
Array.isArray(entry?.immutableFiles) ? entry.immutableFiles : [],
),
);
}
return applyAssetCachePolicy(request, asset, assetsDir, (await files).has(path.slice(1)));
return applyAssetCachePolicy(request, asset, assetsDir, files.has(path.slice(1)));
};
}

Expand Down
63 changes: 52 additions & 11 deletions packages/void/test/unit/routing-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -819,6 +824,33 @@ describe('typed asset fallthrough', () => {
expect(response.headers.get('cache-control')).toBe('no-store');
await expect(response.text()).resolves.toBe('asset');
});
it('keeps a stalled manifest lookup from blocking later asset requests', async () => {
const load = vi
.fn<ManifestLoader>()
.mockImplementationOnce(() => new Promise<ClientManifest | null>(() => {}))
.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'),
);
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('preserves non-success, redirects and mutation responses', () => {
for (const source of [
new Response('missing', { status: 404 }),
Expand Down Expand Up @@ -1589,16 +1621,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<Response>>()
.mockImplementationOnce(() => new Promise<Response>(() => {}))
.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);
});

Expand All @@ -1614,9 +1657,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);
Expand Down
Loading