perf: accelerate production request hot paths
Quality / quality (ubuntu-latest) (push) Failing after 12m23s
Quality / quality (windows-latest) (push) Canceled after 0s

This commit is contained in:
2026-08-03 01:08:43 +05:30
parent fed1d5d3f4
commit 1a1d2e9d08
4 changed files with 164 additions and 8 deletions
+33 -1
View File
@@ -41,6 +41,11 @@ function cachePolicy(filePath: string, mode: Mode): string {
/** Cache the public-dir existence check so it isn't a sync stat on every request. */
const publicDirExistsCache = new Map<string, boolean>();
const productionPublicFileCache = new Map<
string,
{ body: Uint8Array; contentType: string; cacheControl: string }
>();
const PRODUCTION_PUBLIC_FILE_CACHE_MAX = 256;
function publicDirExists(dir: string): boolean {
let exists = publicDirExistsCache.get(dir);
if (exists === undefined) {
@@ -73,6 +78,21 @@ export async function servePublicAsset(
let filePath = resolve(base, rel);
if (!isInside(base, filePath)) return fallback;
if (mode === "production") {
const cached = productionPublicFileCache.get(filePath);
if (cached) {
productionPublicFileCache.delete(filePath);
productionPublicFileCache.set(filePath, cached);
return new Response(cached.body.slice(), {
headers: {
"content-type": cached.contentType,
"cache-control": cached.cacheControl,
"x-content-type-options": "nosniff",
},
});
}
}
try {
const info = await stat(filePath);
if (info.isDirectory()) {
@@ -86,10 +106,22 @@ export async function servePublicAsset(
const body = await readFile(filePath);
const contentType =
CONTENT_TYPES[extname(filePath).toLowerCase()] ?? "application/octet-stream";
const cacheControl = cachePolicy(filePath, mode);
if (mode === "production") {
productionPublicFileCache.set(filePath, {
body: new Uint8Array(body),
contentType,
cacheControl,
});
if (productionPublicFileCache.size > PRODUCTION_PUBLIC_FILE_CACHE_MAX) {
const oldest = productionPublicFileCache.keys().next().value;
if (oldest) productionPublicFileCache.delete(oldest);
}
}
return new Response(body, {
headers: {
"content-type": contentType,
"cache-control": cachePolicy(filePath, mode),
"cache-control": cacheControl,
"x-content-type-options": "nosniff",
},
});