perf(bundle): answer HEAD from the stat without reading the chunk

This commit is contained in:
Menghuan1918 committed 2026-10-24 02:17:12 +08:00
1 parent 0a4a94c704
commit 81b2e8077e
2 files changed
+48 -13

No files matched your search

+29 -13
View File
@@ -9,8 +9,11 @@
* ETag (content hash, memoized per file by mtime/size) and honors
* If-None-Match — the browser revalidates each fetch, but a 304 avoids
* re-downloading multi-MB chunks that did not change (page refresh, HMR
* re-activation). Same browser-trust fence as every other /sidebar route;
* only allowlisted chunk names are servable (no path traversal).
* re-activation). A HEAD answers from the stat alone (headers + content-length,
* no body): the client re-checks every loaded chunk with HEAD when the sidebar
* re-activates, and Node discards the body of a HEAD response anyway. Same
* browser-trust fence as every other /sidebar route; only allowlisted chunk
* names are servable (no path traversal).
*/
import { createHash } from 'node:crypto'
import { stat, readFile } from 'node:fs/promises'
@@ -40,22 +43,23 @@ interface ChunkEtag {
const etags = new Map<string, ChunkEtag>()
/**
* The chunk file's ETag (quoted hash), or undefined when the file is
* missing. Hash is recomputed only when mtime/size changed (hashing a
* multi-MB chunk per request is wasteful).
* The chunk file's ETag (quoted hash) and byte size, or undefined when the
* file is missing. Hash is recomputed only when mtime/size changed (hashing a
* multi-MB chunk per request is wasteful); the size comes from the same stat,
* so a HEAD never has to read the body.
*/
async function etagOf(name: ChunkName, chunkDir: string): Promise<string | undefined> {
async function etagOf(name: ChunkName, chunkDir: string): Promise<{ etag: string; size: number } | undefined> {
const path = join(chunkDir, `client-${name}.js`)
const key = `${chunkDir}:${name}`
try {
const info = await stat(path)
const memo = etags.get(key)
if (memo !== undefined && memo.mtimeMs === info.mtimeMs && memo.size === info.size) {
return memo.etag
return { etag: memo.etag, size: info.size }
}
const etag = `"${shortHash(await readFile(path))}"`
etags.set(key, { mtimeMs: info.mtimeMs, size: info.size, etag })
return etag
return { etag, size: info.size }
} catch {
return undefined
}
@@ -89,17 +93,29 @@ export function createBundleRouteHandler(
res.end('not found')
return
}
const etag = await etagOf(name, chunkDir)
if (etag === undefined) {
const info = await etagOf(name, chunkDir)
if (info === undefined) {
// Registered name but unreadable (bundle not built yet): loud 404.
res.writeHead(404)
res.end('not found')
return
}
if (req.headers['if-none-match'] === etag) {
if (req.headers['if-none-match'] === info.etag) {
// Revalidation hit: unchanged chunk, no body — avoids re-downloading
// multi-MB scripts on page refresh / HMR re-activation.
res.writeHead(304, { 'cache-control': 'no-cache', etag })
res.writeHead(304, { 'cache-control': 'no-cache', etag: info.etag })
res.end()
return
}
if (req.method === 'HEAD') {
// Header-only answer straight from the stat: the client only wants the
// ETag, and the body of a HEAD response is discarded by Node anyway.
res.writeHead(200, {
'content-type': 'text/javascript; charset=utf-8',
'cache-control': 'no-cache',
etag: info.etag,
'content-length': String(info.size),
})
res.end()
return
}
@@ -108,7 +124,7 @@ export function createBundleRouteHandler(
res.writeHead(200, {
'content-type': 'text/javascript; charset=utf-8',
'cache-control': 'no-cache',
etag,
etag: info.etag,
})
res.end(body)
} catch {
+19
View File
@@ -64,6 +64,25 @@ describe('/sidebar/bundle route', () => {
}
})
it('answers HEAD with the headers only, without materializing the chunk', async () => {
// The client HEADs every loaded chunk when the sidebar re-activates (and
// once after each lazy load) to read the ETag. Reading the multi-MB body
// for a request whose body Node discards is pure waste.
const { handler, cleanup } = setup()
try {
const res = fakeRes()
await handler(req('HEAD', '/sidebar/bundle/editor.js'), res as unknown as ServerResponse)
expect(res.status).toBe(200)
expect(res.headers['content-type']).toBe('text/javascript; charset=utf-8')
expect(res.headers['cache-control']).toBe('no-cache')
expect(res.headers.etag).toMatch(/^"[0-9a-f]{12}"$/)
expect(res.headers['content-length']).toBe(String('window.__ModuleLoader__ && 0;'.length))
expect(res.body, 'HEAD must not read the chunk body').toBe('')
} finally {
cleanup()
}
})
it('revalidates with a 304 when If-None-Match matches (no re-download)', async () => {
const { handler, cleanup } = setup()
try {