mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(studio-server): refuse a sub-composition preview past the render's limits (#8308)
* fix(core): give the preview bundler the render's expansion budget The preview bundler inlined every sub-composition mount with only a depth limit, so a few small files that mount each other many times assembled a page without bound. The producer's expansion budget now lives in core, and the bundler charges every mount and the scripts and styles generated for it to that budget, and checks each file's size before reading it. Studio preview shows the refusal instead of falling back to the raw page, whose mounts the browser would expand the same way. * refactor: drop comments the names already carry * fix(studio-server): refuse a sub-composition preview past the render's limits The single sub-composition page is served without bundling its mounts, and the browser runtime then fetches one copy for every data-composition-src host in it, with no count or byte limit. The page build now charges each host the browser will fetch to the shared expansion budget, reading each target's size once, and the route serves the preview's refusal page. Also moves the preview route's size-limit check above the comment it had displaced, and uses core's check through a light subpath. * fix(core): give the preview bundler the render's element cap #8295 added a 100,000-element cap to the render's expansion budget. The preview bundler now passes chargeElements to the shared inliner too, so preview refuses the same compositions. * fix(studio-server): charge a percent-encoded composition src for the file it serves The comp page build looked up each data-composition-src by its raw text, so an encoded spelling such as b%69g.html counted as a mount but was charged 0 bytes, while the preview route decodes it and serves big.html. Resolve the same decoded path the route serves. * test(core): give the preview fan-out budget test a 30 s timeout The flake gate saw it pass 9 of 10 runs under CPU contention, timing out at the default 5 s. The neighbouring scoper bound tests use 30 s too.
This commit is contained in:
@@ -530,6 +530,12 @@
|
||||
"types": "./dist/runtime/levelTap.d.ts",
|
||||
"environments": ["browser", "bun", "node"]
|
||||
},
|
||||
"./compiler/composition-size-limit": {
|
||||
"source": "./src/compiler/compositionSizeLimit.ts",
|
||||
"runtime": "./dist/compiler/compositionSizeLimit.js",
|
||||
"types": "./dist/compiler/compositionSizeLimit.d.ts",
|
||||
"environments": ["bun", "node"]
|
||||
},
|
||||
"./compiler/html-document": {
|
||||
"source": "./src/compiler/htmlDocument.ts",
|
||||
"runtime": "./dist/compiler/htmlDocument.js",
|
||||
|
||||
@@ -537,6 +537,12 @@
|
||||
"import": "./src/runtime/levelTap.ts",
|
||||
"types": "./src/runtime/levelTap.ts"
|
||||
},
|
||||
"./compiler/composition-size-limit": {
|
||||
"bun": "./src/compiler/compositionSizeLimit.ts",
|
||||
"node": "./dist/compiler/compositionSizeLimit.js",
|
||||
"import": "./src/compiler/compositionSizeLimit.ts",
|
||||
"types": "./src/compiler/compositionSizeLimit.ts"
|
||||
},
|
||||
"./compiler/html-document": {
|
||||
"bun": "./src/compiler/htmlDocument.ts",
|
||||
"node": "./dist/compiler/htmlDocument.js",
|
||||
@@ -1051,6 +1057,10 @@
|
||||
"import": "./dist/runtime/levelTap.js",
|
||||
"types": "./dist/runtime/levelTap.d.ts"
|
||||
},
|
||||
"./compiler/composition-size-limit": {
|
||||
"import": "./dist/compiler/compositionSizeLimit.js",
|
||||
"types": "./dist/compiler/compositionSizeLimit.d.ts"
|
||||
},
|
||||
"./compiler/html-document": {
|
||||
"import": "./dist/compiler/htmlDocument.js",
|
||||
"types": "./dist/compiler/htmlDocument.d.ts"
|
||||
|
||||
@@ -72,6 +72,20 @@ describe("preview bundle expansion budget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses mounts that copy more elements than the limit", async () => {
|
||||
const dir = project({
|
||||
"index.html": root(mounts("scene.html", 60)),
|
||||
"scene.html": scene("<i></i>".repeat(2_000)),
|
||||
});
|
||||
|
||||
const error = await bundleError(dir);
|
||||
|
||||
expect(error).toMatchObject({
|
||||
code: "COMPOSITION_TOO_LARGE",
|
||||
publicMetadata: { exceeded: "elements" },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses scripts and styles generated for mounts past the limit", async () => {
|
||||
const scripts = `<script>window.n = (window.n || 0) + 1;</script>`.repeat(
|
||||
Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 10_000),
|
||||
|
||||
@@ -1226,6 +1226,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
|
||||
return source;
|
||||
},
|
||||
chargeEmitted: (srcPath: string, bytes: number) => budget.chargeGenerated(srcPath, bytes),
|
||||
chargeElements: (srcPath: string, count: number) => budget.chargeElements(srcPath, count),
|
||||
parseHtml: parseHTMLContent,
|
||||
hostIdentityMap: hostIdentityByElement,
|
||||
rewriteInlineStyles: true,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { existsSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { parseHTML } from "linkedom";
|
||||
import { firstHtmlTemplate } from "@hyperframes/parsers/sub-composition-validity";
|
||||
import { decodedUrlPath } from "@hyperframes/parsers/asset-paths";
|
||||
import {
|
||||
rewriteAssetPaths,
|
||||
rewriteCssAssetUrls,
|
||||
@@ -15,6 +16,10 @@ import {
|
||||
import { findStartTags, isFullHtmlDocument } from "@hyperframes/core/compiler/html-document";
|
||||
import { gsapCdnDist } from "@hyperframes/core/gsap-cdn";
|
||||
import { resolveWithinProject } from "@hyperframes/core/safe-path";
|
||||
import {
|
||||
assertCompositionFileSize,
|
||||
CompositionExpansionBudget,
|
||||
} from "@hyperframes/core/compiler/composition-size-limit";
|
||||
import { TIMELINE_REGISTRY_SCRIPT } from "./authoredCode.js";
|
||||
import { htmlHasGsapCore, insertGsapCoreBeforeHeadPlugin } from "./gsapCoreScript.js";
|
||||
import { withRootPathsRelative } from "./rootPaths.js";
|
||||
@@ -366,6 +371,7 @@ export function buildSubCompositionHtml(
|
||||
`<!DOCTYPE html><html><head></head><body>${rewrittenContent}</body></html>`,
|
||||
);
|
||||
deferScriptsUntilFonts(scriptsDoc as unknown as Document);
|
||||
chargeMountsTheBrowserFetches(projectDir, scriptsDoc as unknown as Document);
|
||||
rewrittenContent = scriptsDoc.body.innerHTML;
|
||||
|
||||
// The comp's root carries data-composition-id but (unlike inlined sub-comps,
|
||||
@@ -425,6 +431,32 @@ ${rewrittenContent}
|
||||
</html>`;
|
||||
}
|
||||
|
||||
function mountedFileBytes(projectDir: string, src: string): number {
|
||||
const file = resolveWithinProject(projectDir, decodedUrlPath(src));
|
||||
if (!file) return 0;
|
||||
assertCompositionFileSize(file, src);
|
||||
try {
|
||||
const stats = statSync(file);
|
||||
return stats.isFile() ? stats.size : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function chargeMountsTheBrowserFetches(projectDir: string, doc: Document): void {
|
||||
const budget = new CompositionExpansionBudget();
|
||||
const bytesBySrc = new Map<string, number>();
|
||||
for (const host of doc.querySelectorAll("[data-composition-src]")) {
|
||||
const src = host.getAttribute("data-composition-src") ?? "";
|
||||
let bytes = bytesBySrc.get(src);
|
||||
if (bytes === undefined) {
|
||||
bytes = mountedFileBytes(projectDir, src);
|
||||
bytesBySrc.set(src, bytes);
|
||||
}
|
||||
budget.charge(src, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/** True for a real `<base>` element; the text "<base" inside a script or comment does not count. */
|
||||
export function hasBaseElement(html: string): boolean {
|
||||
return findStartTags(html, "base").length > 0;
|
||||
|
||||
@@ -25,7 +25,9 @@ export interface FinishJob {
|
||||
}
|
||||
|
||||
export type SubCompositionJob = BuildJob | FinishJob;
|
||||
type Result<J> = J extends BuildJob ? { html: string; references: string[] } | null : string;
|
||||
type Result<J> = J extends BuildJob
|
||||
? { html: string; references: string[] } | { refused: string } | null
|
||||
: string;
|
||||
|
||||
export class SubCompositionDeadlineError extends Error {
|
||||
constructor(compPath: string) {
|
||||
|
||||
@@ -6,11 +6,21 @@ import { injectStudioPreviewAugmentations, withPreviewRuntime } from "../routes/
|
||||
import { previewReferences } from "./previewReads.js";
|
||||
import { injectPreviewVariables } from "./previewVariables.js";
|
||||
import { withRootImportMap } from "./rootImportMap.js";
|
||||
import { isCompositionTooLargeError } from "@hyperframes/core/compiler/composition-size-limit";
|
||||
import { buildSubCompositionHtml } from "./subComposition.js";
|
||||
import type { BuildJob, FinishJob, SubCompositionJob } from "./subCompositionBuild.js";
|
||||
|
||||
function buildOrRefuse(buildPage: () => string | null): string | { refused: string } | null {
|
||||
try {
|
||||
return buildPage();
|
||||
} catch (error) {
|
||||
if (isCompositionTooLargeError(error)) return { refused: error.message };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** The page with its runtime and the files it names, hf-ids pinned to the source's; null once the file is gone. */
|
||||
function build(job: BuildJob): { html: string; references: string[] } | null {
|
||||
function build(job: BuildJob): { html: string; references: string[] } | { refused: string } | null {
|
||||
const { projectDir, compPath, compFile, runtimeUrl, baseHref, gsapBaseUrl } = job;
|
||||
let pinned: string | undefined;
|
||||
if (/\.html?$/i.test(compPath)) {
|
||||
@@ -20,15 +30,10 @@ function build(job: BuildJob): { html: string; references: string[] } | null {
|
||||
return null; // removed between the route's stat and this read
|
||||
}
|
||||
}
|
||||
const built = buildSubCompositionHtml(
|
||||
projectDir,
|
||||
compPath,
|
||||
runtimeUrl,
|
||||
baseHref,
|
||||
pinned,
|
||||
gsapBaseUrl,
|
||||
const built = buildOrRefuse(() =>
|
||||
buildSubCompositionHtml(projectDir, compPath, runtimeUrl, baseHref, pinned, gsapBaseUrl),
|
||||
);
|
||||
if (!built) return null;
|
||||
if (typeof built !== "string") return built;
|
||||
const html = withPreviewRuntime(withRootImportMap(built, baseHref), runtimeUrl);
|
||||
return { html, references: [...previewReferences(html)] };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment node
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark";
|
||||
import { MAX_EXPANDED_COMPOSITION_BYTES } from "@hyperframes/core/compiler/composition-size-limit";
|
||||
import { createStudioApi } from "../createStudioApi";
|
||||
import type { StudioApiAdapter } from "../types";
|
||||
|
||||
const projectDir = mkdtempSync(join(tmpdir(), "hf-preview-comp-too-large-"));
|
||||
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
|
||||
|
||||
const mounts = (src: string, count: number) =>
|
||||
`<div data-composition-id="scene" data-composition-src="${src}"></div>`.repeat(count);
|
||||
const page = (body: string) =>
|
||||
`<template><div data-composition-id="page" data-width="320" data-height="180">${body}</div></template>`;
|
||||
|
||||
writeFileSync(join(projectDir, "index.html"), "<html><head></head><body></body></html>");
|
||||
writeFileSync(join(projectDir, "leaf.html"), page("<h1>Leaf</h1>"));
|
||||
writeFileSync(join(projectDir, "many.html"), page(mounts("leaf.html", 10_001)));
|
||||
writeFileSync(
|
||||
join(projectDir, "big.html"),
|
||||
page(`<p>${"x".repeat(Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 5))}</p>`),
|
||||
);
|
||||
writeFileSync(join(projectDir, "heavy.html"), page(mounts("big.html", 6)));
|
||||
writeFileSync(join(projectDir, "heavy-encoded.html"), page(mounts("b%69g.html", 6)));
|
||||
writeFileSync(join(projectDir, "few.html"), page(mounts("leaf.html", 3)));
|
||||
|
||||
const adapter: StudioApiAdapter = {
|
||||
listProjects: () => [],
|
||||
resolveProject: async (id: string) => ({ id, dir: projectDir }),
|
||||
bundle: async () => null,
|
||||
lint: async () => ({ findings: [] }),
|
||||
runtimeUrl: "/api/runtime.js",
|
||||
rendersDir: () => join(projectDir, "renders"),
|
||||
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "/tmp/out.mp4" }),
|
||||
};
|
||||
const api = createStudioApi(adapter);
|
||||
const open = (file: string) => api.request(`http://localhost/projects/demo/preview/comp/${file}`);
|
||||
|
||||
describe("a sub-composition preview over a size limit", () => {
|
||||
it("refuses a page whose mounts the browser would fetch past the mount limit", async () => {
|
||||
const html = await (await open("many.html")).text();
|
||||
expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`);
|
||||
expect(html).toContain("Mount large or repeated scenes fewer times");
|
||||
expect(html).not.toContain('data-composition-src="leaf.html"');
|
||||
});
|
||||
|
||||
it("refuses a page whose mounts add up past the byte limit", async () => {
|
||||
const html = await (await open("heavy.html")).text();
|
||||
expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`);
|
||||
expect(html).not.toContain('data-composition-src="big.html"');
|
||||
});
|
||||
|
||||
it("charges a percent-encoded src for the file the route serves for it", async () => {
|
||||
const html = await (await open("heavy-encoded.html")).text();
|
||||
expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`);
|
||||
expect(html).not.toContain('data-composition-src="b%69g.html"');
|
||||
});
|
||||
|
||||
it("still serves a page with a few mounts", async () => {
|
||||
const res = await open("few.html");
|
||||
expect(res.status).toBe(200);
|
||||
const html = await res.text();
|
||||
expect(html.split('data-composition-src="leaf.html"').length - 1).toBe(3);
|
||||
expect(html).not.toContain(`window.${STUDIO_PREVIEW_ERRORS}=["`);
|
||||
});
|
||||
});
|
||||
@@ -111,6 +111,7 @@ import {
|
||||
} from "../helpers/mediaProxyPreview.js";
|
||||
import { requestSubPath } from "../helpers/requestSubPath.js";
|
||||
import { previewRefusalPage } from "../helpers/previewErrorPage.js";
|
||||
import { isCompositionTooLargeError } from "@hyperframes/core/compiler/composition-size-limit";
|
||||
import { lazyPreviewImages } from "../helpers/lazyPreviewImages.js";
|
||||
import { corsProjectVideos } from "../helpers/captureVideos.js";
|
||||
import { createJobSlots, JobAbandonedError, JobQueueFullError } from "../helpers/jobSlots.js";
|
||||
@@ -166,10 +167,6 @@ function parseStudioMotionManifestContent(content: string): {
|
||||
}
|
||||
|
||||
/** Preview hooks must install before authored head scripts register media consumers. */
|
||||
function isCompositionTooLarge(error: unknown): error is Error {
|
||||
return error instanceof Error && "code" in error && error.code === "COMPOSITION_TOO_LARGE";
|
||||
}
|
||||
|
||||
export function withPreviewRuntime(html: string, runtimeUrl: string): string {
|
||||
const tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1" src="${runtimeUrl}"></script>`;
|
||||
return insertRuntimeTag(stripEmbeddedRuntimeScripts(html), tag, true);
|
||||
@@ -590,7 +587,7 @@ export function registerPreviewRoutes(
|
||||
}
|
||||
return bundled;
|
||||
} catch (error) {
|
||||
if (isCompositionTooLarge(error)) return previewRefusalPage(error.message);
|
||||
if (isCompositionTooLargeError(error)) return previewRefusalPage(error.message);
|
||||
// Re-read disk on bundle failure so we serve the latest file content,
|
||||
// not the pre-request snapshot that may have been saved over.
|
||||
const fallback = resolveProjectMainHtml(project.dir, project.id);
|
||||
@@ -711,6 +708,7 @@ export function registerPreviewRoutes(
|
||||
compPath,
|
||||
);
|
||||
if (!built) return c.text("not found", 404);
|
||||
if ("refused" in built) return c.html(previewRefusalPage(built.refused), 200);
|
||||
for (const path of built.references) recordPreviewRead(project.dir, path);
|
||||
const transformed = await withinDeadline(
|
||||
transformPreviewHtml(built.html, adapter, project, compPath),
|
||||
|
||||
Reference in New Issue
Block a user