mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-16 06:19:21 +00:00
perf(cli): serve the studio bundle compressed and cache hashed assets
The 4.1MB studio bundle was served uncompressed with Cache-Control: no-store, so every open of the studio re-downloaded and re-parsed it. Vite names built assets with an 8-character content hash, so their bytes can never change: those now ship gzip-compressed (1.25MB on the wire, byte-identical after inflation) with a one-year immutable cache policy. Unhashed files under public/ keep no-store, and the HTML shell, which previously sent no Cache-Control at all, now sends no-store explicitly: it is the only thing that names the current hashed bundle, and it must keep revalidating for the immutable policy to be safe. The hash test only accepts the segment after the last hyphen and requires a digit, underscore or capital, so an ordinary hyphenated name like user-Guide-v2.js is not mistaken for a hash and served forever.
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { createStudioServer, isContentHashedAsset, type StudioServer } from "./studioServer.js";
|
||||
|
||||
/**
|
||||
* Cache and transfer policy for the studio bundle. A content-hashed URL can
|
||||
* never serve different bytes, so it is safe to keep forever; everything else
|
||||
* the same routes serve (public/ files, the HTML shell) changes under a
|
||||
* stable URL and must keep revalidating.
|
||||
*/
|
||||
|
||||
const hooks = vi.hoisted(() => ({ studioDir: "" }));
|
||||
|
||||
// The bundle directory is resolved from __dirname at server construction, so
|
||||
// point that one `resolve(<...>/server, "studio")` call at a temp tree.
|
||||
vi.mock("node:path", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof path>();
|
||||
return {
|
||||
...actual,
|
||||
resolve: (...parts: string[]) =>
|
||||
hooks.studioDir && parts.length === 2 && parts[0]?.endsWith("server") && parts[1] === "studio"
|
||||
? hooks.studioDir
|
||||
: actual.resolve(...parts),
|
||||
};
|
||||
});
|
||||
|
||||
const HASHED_BUNDLE = "index-BRr1JoHX.js";
|
||||
// Large enough to clear hono's 1KB compression threshold.
|
||||
const BUNDLE_BYTES = `export const studio = ${JSON.stringify("x".repeat(4096))};\n`;
|
||||
|
||||
let root: string;
|
||||
let server: StudioServer;
|
||||
|
||||
beforeEach(() => {
|
||||
root = fs.mkdtempSync(path.join(tmpdir(), "hf-studio-assets-"));
|
||||
hooks.studioDir = path.join(root, "studio");
|
||||
const projectDir = path.join(root, "project");
|
||||
fs.mkdirSync(projectDir);
|
||||
fs.mkdirSync(path.join(hooks.studioDir, "assets"), { recursive: true });
|
||||
fs.writeFileSync(path.join(hooks.studioDir, "assets", HASHED_BUNDLE), BUNDLE_BYTES);
|
||||
fs.writeFileSync(path.join(hooks.studioDir, "assets", "unhashed.js"), BUNDLE_BYTES);
|
||||
fs.writeFileSync(
|
||||
path.join(hooks.studioDir, "index.html"),
|
||||
"<html><head></head><body>Studio</body></html>",
|
||||
);
|
||||
server = createStudioServer({ projectDir });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.watcher.close();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
hooks.studioDir = "";
|
||||
});
|
||||
|
||||
describe("studio bundle cache policy", () => {
|
||||
it("serves a content-hashed asset as immutable", async () => {
|
||||
const response = await server.app.request(`/assets/${HASHED_BUNDLE}`);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("Cache-Control")).toBe("public, max-age=31536000, immutable");
|
||||
});
|
||||
|
||||
it("keeps an unhashed asset revalidating", async () => {
|
||||
const response = await server.app.request("/assets/unhashed.js");
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
});
|
||||
|
||||
it("keeps the HTML shell revalidating, since it names the hashed bundle", async () => {
|
||||
const response = await server.app.request("/");
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
});
|
||||
|
||||
// The first four are real filenames from `bun run --filter @hyperframes/studio build`.
|
||||
it.each([
|
||||
["index-BRr1JoHX.js", true],
|
||||
["index-DnRfAiK2.css", true],
|
||||
["hyperframes-player-lPOqAC3l.js", true],
|
||||
["index-RPEcu_bT.js", true],
|
||||
["unhashed.js", false],
|
||||
["vite-manifest.json", false],
|
||||
["favicon.svg", false],
|
||||
// A hyphenated name is not a hash, however many capitals it carries: only
|
||||
// the segment after the last hyphen is a hash candidate.
|
||||
["user-Guide-v2.js", false],
|
||||
["brand-Logo-Dark.svg", false],
|
||||
])("classifies %s", (name, hashed) => {
|
||||
expect(isContentHashedAsset(name)).toBe(hashed);
|
||||
});
|
||||
});
|
||||
|
||||
describe("studio bundle transfer encoding", () => {
|
||||
it("compresses a bundle for a client that accepts gzip", async () => {
|
||||
const response = await server.app.request(`/assets/${HASHED_BUNDLE}`, {
|
||||
headers: { "Accept-Encoding": "gzip, deflate, br" },
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("Content-Encoding")).toBe("gzip");
|
||||
// The middleware must not corrupt the payload it shrinks. `Response.text()`
|
||||
// does not decode Content-Encoding, so unwrap it explicitly.
|
||||
const body = response.body;
|
||||
if (!body) throw new Error("compressed response had no body");
|
||||
const decoded = await new Response(body.pipeThrough(new DecompressionStream("gzip"))).text();
|
||||
expect(decoded).toBe(BUNDLE_BYTES);
|
||||
});
|
||||
|
||||
it("sends the raw bytes to a client that accepts no encoding", async () => {
|
||||
const response = await server.app.request(`/assets/${HASHED_BUNDLE}`);
|
||||
|
||||
expect(response.headers.get("Content-Encoding")).toBeNull();
|
||||
expect(await response.text()).toBe(BUNDLE_BYTES);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
|
||||
import { Hono, type Context } from "hono";
|
||||
import { compress } from "hono/compress";
|
||||
import { streamSSE } from "hono/streaming";
|
||||
import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
|
||||
import { resolve, join, basename } from "node:path";
|
||||
@@ -58,6 +59,26 @@ import {
|
||||
} from "../browser/gpuPolicy.js";
|
||||
|
||||
const STUDIO_MANUAL_EDITS_PATH = ".hyperframes/studio-manual-edits.json";
|
||||
|
||||
// Vite emits built chunks and assets as `<name>-<hash>.<ext>` with rollup's
|
||||
// 8-character base64url content hash (`index-BRr1JoHX.js`), so a hashed URL's
|
||||
// bytes can never change and the browser may keep them forever. The HTML shell
|
||||
// and public/ files keep their names across builds and must keep revalidating.
|
||||
const HASH_SUFFIX_RE = /-([A-Za-z0-9_]{8,})\.[A-Za-z0-9]+$/;
|
||||
const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
|
||||
|
||||
/**
|
||||
* Only the segment after the LAST hyphen counts, and it must carry a digit,
|
||||
* underscore or capital. That is what separates a real hash from an ordinary
|
||||
* hyphenated word of the same length (`vite-manifest.json`, `user-Guide-v2.js`),
|
||||
* and it errs the safe way: an all-lower-case hash would simply keep
|
||||
* revalidating, which is the behaviour before this change.
|
||||
*/
|
||||
export function isContentHashedAsset(filePath: string): boolean {
|
||||
const suffix = HASH_SUFFIX_RE.exec(basename(filePath))?.[1];
|
||||
return suffix !== undefined && /[A-Z0-9_]/.test(suffix);
|
||||
}
|
||||
|
||||
const REMOTE_GIF_IMG_SRC_RE =
|
||||
/<img\b[^>]*?\bsrc\s*=\s*["'](https?:\/\/[^"']+\.gif(?:[?#][^"']*)?)["'][^>]*>/gi;
|
||||
|
||||
@@ -879,9 +900,17 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
|
||||
const content = readBundleFile(filePath);
|
||||
if (content === null) return c.text("not found", 404);
|
||||
return new Response(content, {
|
||||
headers: { "Content-Type": getMimeType(filePath), "Cache-Control": "no-store" },
|
||||
headers: {
|
||||
"Content-Type": getMimeType(filePath),
|
||||
"Cache-Control": isContentHashedAsset(filePath) ? IMMUTABLE_CACHE_CONTROL : "no-store",
|
||||
},
|
||||
});
|
||||
};
|
||||
// Runtime gzip: the studio bundle is several megabytes of JavaScript and was
|
||||
// being shipped raw on every cold open. Hono's middleware already skips
|
||||
// already-compressed content types and anything under its size threshold, so
|
||||
// only /assets/* needs it — public/ holds icons and the favicon.
|
||||
app.use("/assets/*", compress());
|
||||
app.get("/assets/*", serveStudioStaticFile);
|
||||
app.get("/icons/*", serveStudioStaticFile);
|
||||
app.get("/favicon.svg", serveStudioStaticFile);
|
||||
@@ -980,7 +1009,9 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
|
||||
if (headScript) {
|
||||
html = html.replace("<head>", `<head>${headScript}`);
|
||||
}
|
||||
return c.html(html);
|
||||
// The shell must never be cached: it is the only thing that names the
|
||||
// current hashed bundle, and those are now served as immutable.
|
||||
return c.html(html, 200, { "Cache-Control": "no-store" });
|
||||
});
|
||||
|
||||
return { app, watcher, adapter };
|
||||
|
||||
Reference in New Issue
Block a user